Wake Android Device up
Asked Answered
T

8

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

Tequilater answered 1/9, 2010 at 19:45 Comment(0)
E
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.

Epicardium answered 2/9, 2010 at 1:9 Comment(6)
Do you have any thoughts for the alternative path?Tequilater
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.Epicardium
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.Chrominance
@Epicardium the "one important note" comment saved my day. Thanks a million!Monochord
@Chrominance 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 (developer.android.com/reference/android/view/…). "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"Night
this solution doesn't work with me, the device still in sleep modeMartynne
C
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.

Chrominance answered 16/4, 2012 at 18:55 Comment(8)
The upper 2 blocks of code go to onCreate() of an Activity. The lower block of code obviously goes to the Android Manifest.Chrominance
Thanks "Yar". BTW in India, the friend is called Yar. So Thanks my friend. It helped a lot.Cushy
SCREEN_BRIGHT_WAKE_LOCK and FULL_WAKE_LOCK are now deprecated. FLAG_KEEP_SCREEN_ON is suggested (see selected answer).Dehiscent
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.Gurnard
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."Neuroticism
This answer is deprecatedLymphangial
Possibly. Google must change things every 5 minutes.Chrominance
This still works for me on API 24 (Android 7.0 Nougat)Negrophobe
E
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.

Epicardium answered 2/9, 2010 at 1:9 Comment(6)
Do you have any thoughts for the alternative path?Tequilater
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.Epicardium
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.Chrominance
@Epicardium the "one important note" comment saved my day. Thanks a million!Monochord
@Chrominance 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 (developer.android.com/reference/android/view/…). "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"Night
this solution doesn't work with me, the device still in sleep modeMartynne
A
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!");
Aeronaut answered 27/12, 2010 at 21:32 Comment(2)
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.Mandrel
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"Mandrel
I
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.

It answered 21/3, 2019 at 14:38 Comment(0)
L
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);
    }
Lenni answered 11/8, 2020 at 13:32 Comment(0)
M
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);
}
Missile answered 21/1, 2017 at 15:59 Comment(0)
T
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.

Timmie answered 1/9, 2010 at 19:48 Comment(1)
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.Abject
A
1
getWindow().addFlags(LayoutParams.FLAG_DISMISS_KEYGUARD);

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

Acantho answered 12/1, 2014 at 12:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.