Android: Wake & unlock phone

Use this code below in your service.

PowerManager pm = (PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE);
        mWakeLock = pm.newWakeLock((PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP), "YourServie");
        mWakeLock.acquire();
        [...]
        mWakeLock.release();

If you want to unlock the screen as well, register a receiver in your service that monitors if the screen is turned on/off and if it is turned off and you want to unlock the phone, start an activity with this code in onCreate:

Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
this.finish();
return;

I know, this is a rather dirty, but as far as I know, there is no other way of unlocking the lockscreen (and this will only work if there are no passwords etc set, so it must be the normal "slide to unlock" screen).

And don't forget to add android.permission.WAKE_LOCK ;-)

/edit: I just saw you are already using an Activity. If you have one and don't need the service at all, just put this code into the activity.


For the service to be allways active you need to have this permission on manifest:

<uses-permission android:name="android.permission.WAKE_LOCK" />

Another thing you need to do is to adquire a WakeLock. Without it the service will end passed some time. You can do it like this:

getApplicationContext();
PowerManager pm = (PowerManager)getApplicationContext().getSystemService(Context.POWER_SERVICE);
WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
wl.acquire();

You might need to change PowerManager.PARTIAL_WAKE_LOCK to the one that you need. You can see info about that here.


There is WakefulBroadcastReceiver which does this for you. Example use:

import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;
import android.support.v4.content.WakefulBroadcastReceiver;
import android.util.Log;

public class SimpleWakefulReceiver extends WakefulBroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        // This is the Intent to deliver to our service.
        Intent service = new Intent(context, SimpleWakefulService.class);

        // Start the service, keeping the device awake while it is launching.
        Log.i("SimpleWakefulReceiver", "Starting service @ " + SystemClock.elapsedRealtime());
        startWakefulService(context, service);
    }
}

After completing the action in the service, call SimpleWakefulReceiver.completeWakefulIntent(intent) to release the wake lock.

(as @Force already gave you the details about the wakeLock, they need not be repeated here ;-)

Mind that the class is deprecated from api level 26.1.0, reference here