Question

I am trying to work on a simple android app that when the device is plugged in, i.e. via a dock, the screen aquires a wake lock so that the screen does not turn off, no matter what app their in, and when unplugged the wake lock is released.

At the moment I don't have any service runing as I was thinking it wasn't needed. It receives the broadcast intent for power connected and power disconnected. When the power is connected it seems to successfully aquires the wake lock but when the power is disconnected it tries to release the wake lock but instead throws a null pointer exception. I am guessing its because the app isn't necessarily running and there is no service so the variable doesn't get kept.

Below is the code I am using that receives the broadcasts.

public class BroadcastReceiveDetection extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) 
    {
        ManageScreenLight manageScreenLight = new ManageScreenLight(context);
        String action = intent.getAction();

        if (action == Intent.ACTION_POWER_CONNECTED)
        {
            manageScreenLight.receivedPowerConnected();
        }
        else if (action == Intent.ACTION_POWER_DISCONNECTED)
        {
            try {
                manageScreenLight.receivedPowerDisconnected();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

Below is the code that aquires and releases the wake lock.

Context context;
    PowerManager.WakeLock wakeLock;
    public ManageScreenLight(Context context)
    {
        this.context = context;
    }

    public void receivedPowerConnected()
    {
        Toast.makeText(context, "Power connected", Toast.LENGTH_LONG).show();

        PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "ScreenStay");
        wakeLock.acquire();
    }

        public void receivedPowerDisconnected() throws IOException
{
    try
    {
        Toast.makeText(context, "Power disconnected", Toast.LENGTH_LONG).show();
        wakeLock.release();
    }
    catch (Exception ex)
    {
        Toast.makeText(context, ex.toString(), Toast.LENGTH_LONG).show();
    }
}

Is there a way that this can work I would there need to be a service that is running when the wake lock is aquired, and once power is disconnected release and stop the service.

Thanks for any help you can provide.

Was it helpful?

Solution

Well, based on the BroadcastReceiver documentation, it looks like onReceive() doesn't get called when your application is killed, which makes sense. Android won't launch your application if it has killed it just to call onReceive(). You will need to use a service if you want to continue receiving/responding to these events.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top