44

Hey i need to wake my sleeping android device up at a certain time. Any suggestions?

P.S. Wake up: turn display on and maybe unlock phone

Coxer
  • 549
  • 1
  • 8
  • 8

8 Answers8

81

To wake up the screen:

PowerManager pm = (PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE);
WakeLock wakeLock = pm.newWakeLock((PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP), "TAG");
wakeLock.acquire();

To release the screen lock:

KeyguardManager keyguardManager = (KeyguardManager) getApplicationContext().getSystemService(Context.KEYGUARD_SERVICE); 
KeyguardLock keyguardLock = keyguardManager.newKeyguardLock("TAG");
keyguardLock.disableKeyguard();

And the manifest needs to contain:

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

For more details about PowerManager, refer to the API documentation: http://developer.android.com/reference/android/os/PowerManager.html

EDIT: this answer is reported as deprecated.

Yar
  • 4,543
  • 2
  • 35
  • 42
  • 1
    The upper 2 blocks of code go to onCreate() of an Activity. The lower block of code obviously goes to the Android Manifest. – Yar Dec 06 '12 at 08:00
  • 3
    Thanks "Yar". BTW in India, the friend is called Yar. So Thanks my friend. It helped a lot. – Chintan Raghwani Apr 19 '13 at 06:58
  • 2
    `SCREEN_BRIGHT_WAKE_LOCK` and `FULL_WAKE_LOCK` are now deprecated. `FLAG_KEEP_SCREEN_ON` is suggested (see selected answer). – loeschg Nov 27 '13 at 15:56
  • 2
    Thanks for this. The KeyguardLock and WakeLock are deprecated in newer versions of Android and it's recommended to use window flags instead, but I needed to wake and unlock the screen from a service application that has no activity or window, so your solution was what I needed. – Josh Davis Feb 13 '16 at 02:04
  • Also this code passes two wake lock levels, which the docs forbid. You should chose one or the other. "The wake lock levels are: PARTIAL_WAKE_LOCK, FULL_WAKE_LOCK, SCREEN_DIM_WAKE_LOCK and SCREEN_BRIGHT_WAKE_LOCK. Exactly one wake lock level must be specified as part of the levelAndFlags parameter." – Daniel Lubarov Nov 14 '16 at 23:03
  • This answer is deprecated – Neon Warge Oct 23 '17 at 15:58
  • Possibly. Google must change things every 5 minutes. – Yar Oct 23 '17 at 17:09
  • This still works for me on API 24 (Android 7.0 Nougat) – olfek Oct 24 '18 at 15:12
35

Best is to use some appropriate combination of these window flags:

http://developer.android.com/reference/android/view/WindowManager.LayoutParams.html#FLAG_DISMISS_KEYGUARD
http://developer.android.com/reference/android/view/WindowManager.LayoutParams.html#FLAG_SHOW_WHEN_LOCKED
http://developer.android.com/reference/android/view/WindowManager.LayoutParams.html#FLAG_KEEP_SCREEN_ON
http://developer.android.com/reference/android/view/WindowManager.LayoutParams.html#FLAG_TURN_SCREEN_ON

If you want to run on older versions of the platform that don't support the desired flag(s), you can directly use wake locks and keyguard locks... but that path is fraught with peril.

ONE IMPORTANT NOTE: Your activity must be full screen in order for the above flag combination to work. In my app I tried to use these flags with an activity which is not full screen (Dialog Theme) and it didn't work. After looking at the documentation I found that these flags require the window to be a full screen window.

catalyst294
  • 129
  • 9
hackbod
  • 90,665
  • 16
  • 140
  • 154
  • Do you have any thoughts for the alternative path? – Coxer Sep 02 '10 at 14:50
  • The KeyguardManager and PowerManager APIs to directly control them. But it is very tricky to use these... in fact, I would argue that it is impossible to use them perfectly for this kind of stuff. That is one of the reasons the flags were introduced. – hackbod Sep 03 '10 at 02:29
  • 1
    This does not work for me. I added these flags in onCreate of my activity being called by my BroadcastReceiver in turn called by the AlarmService. The code is called but the screen remains black. – Yar Apr 16 '12 at 18:52
  • 1
    @hackbod the "one important note" comment saved my day. Thanks a million! – Thomas Mar 28 '13 at 10:29
  • 1
    @Yar and I are having the same problem. I have my window full screen but the screen remains off and locked. Does this approach require any permissions. I feel like I'm missing something but did find the following note here (http://developer.android.com/reference/android/view/WindowManager.LayoutParams.html#type). "System windows (ranging from FIRST_SYSTEM_WINDOW to LAST_SYSTEM_WINDOW) are special types of windows for use by the system for specific purposes. They should not normally be used by applications, and a special permission is required to use them" – Forrest Bice May 21 '14 at 19:28
  • this solution doesn't work with me, the device still in sleep mode – Muhammed Refaat Apr 10 '16 at 08:22
8

I found a way and it is not that complex... works on any API version.

You need to use PowerManager.userActivity(l, false) method and register your activity as broadcast received for SCREEN_OFF intent:

In your actiivity OnCreate put something like:

mReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.v(TAG, "Screen OFF onReceive()");
        screenOFFHandler.sendEmptyMessageDelayed(0, 2000L);
    }
};

It will kick off the handler after 2 seconds of Screen Off event.

Register receiver in your onResume() method:

IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
registerReceiver(mReceiver, filter);
Log.i(TAG, "broadcast receiver registered!");

Create a handler like the one below:

private Handler screenOFFHandler = new Handler() {

    @Override
    public void handleMessage(Message msg) {

        super.handleMessage(msg);
        // do something
        // wake up phone
        Log.i(TAG, "ake up the phone and disable keyguard");
        PowerManager powerManager = (PowerManager) YourActivityName.this
                .getSystemService(Context.POWER_SERVICE);
        long l = SystemClock.uptimeMillis();
        powerManager.userActivity(l, false);//false will bring the screen back as bright as it was, true - will dim it
    }
};

Request permission in your manifest file:

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

Do not forget to unregister broadcast receiver when you are done. You may do that in onDestroy() for example (which is not guaranteed)

unregisterReceiver(mReceiver);
Log.i(TAG, "broadcast UNregistred!");
MahdiY
  • 1,269
  • 21
  • 32
mishkin
  • 5,932
  • 8
  • 45
  • 64
  • 1
    For some reason I can get the code to work. I'm trying to have the service unlock the screen but for some reason it won't unlock. Should the code wake and unlock the phone after 2 seconds? Using the code above the phone just sits locked after I lock it. – Nick Oct 10 '11 at 01:55
  • The problem happends after the phone locks. Screen OFF Log.V tag shows then says about to give-up screen -> Wake up the phone and disable keyboard. Then it sits for about 30 secs and then says "Close() was never explicitly called on database" – Nick Oct 10 '11 at 02:05
3

On newer devices you should use something like this, since the mentioned Flags are deprecated.

class AlarmActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_alarm)

        // Keep screen always on, unless the user interacts (wakes the mess up...)
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)

        setTurnScreenOn(true)
        setShowWhenLocked(true)

        (getSystemService(KeyguardManager::class.java) as KeyguardManager).requestDismissKeyguard(this,
            object: KeyguardManager.KeyguardDismissCallback(){
                override fun onDismissCancelled() {
                    Log.d("Keyguard", "Cancelled")
                }

                override fun onDismissError() {
                    Log.d("Keyguard", "Error")
                }

                override fun onDismissSucceeded() {
                    Log.d("Keyguard", "Success")
                }
            }
        )
    }
}

KeyguardManager.requestDismissKeyguard only wakes up the device, if the setter setTurnScreenOn(true) was called before.

I tested this on my Android Pie device.

Palm
  • 699
  • 1
  • 6
  • 17
3

Try with the below code after setContentView(R.layout.YOUR_LAYOUT); in activity onCreate() method

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
        Log.d(TAG, "onCreate: set window flags for API level > 27");
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN
                        | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        KeyguardManager keyguardManager = (KeyguardManager) getApplicationContext().getSystemService(Context.KEYGUARD_SERVICE);
        keyguardManager.requestDismissKeyguard(this, null);
        setShowWhenLocked(true);
        setTurnScreenOn(true);
    } else {
        Log.d(TAG, "onCreate: onCreate:set window flags for API level < 27");
        getWindow().addFlags(
                WindowManager.LayoutParams.FLAG_FULLSCREEN
                        | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
                        | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
                        | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                        | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
    }
Rajesh.k
  • 2,327
  • 1
  • 16
  • 19
2

If you are showing a window when waking up, you can get it working easily by adding few flags to your activity, without using a wake lock.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.my_activity);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
}
Lahiru Chandima
  • 22,324
  • 22
  • 103
  • 179
1
getWindow().addFlags(LayoutParams.FLAG_DISMISS_KEYGUARD);

will dismiss the general keyguard and cause the device to unlock.

Prativa
  • 364
  • 6
  • 25
1

Settling an alarm programatically will wake up the phone(play a sound) and i guess the turn on display would be an option there.

I donot think there would be an exposed API that will unlock the phone automatically.

schar
  • 2,618
  • 5
  • 25
  • 24
  • if anything your activity would come up over the lock screen and once you exited it the lockscreen would be there. Like when you are in a phonecall. – Nathan Schwermann Sep 01 '10 at 20:20