Wake Android Device up - android

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

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.

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.

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!");

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.

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);
}

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);
}

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.

getWindow().addFlags(LayoutParams.FLAG_DISMISS_KEYGUARD);
will dismiss the general keyguard and cause the device to unlock.

Related

Activity does not start until the screen is turned on

My service starts an Activity like this:
Intent intent = new Intent(context, CallMonitor.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
this happens in CallMonitor.onCreate():
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
On most devices, the activity (called up from service) wakes up the device, turns on the screen and is displayed.
But - for example - on Galaxy Tab 4, the activity is only called if the screen is already switched on.
If the screen is switched off and the service calls up the activity, it is displayed with a delay - It will be displayed immediatly after turning the screen on.
There is also a voice output in the activity. When the Galaxy S4 is switched off, it will not be played back - but immediatly after turning the screen on again.
Any suggestions?
I don't want to use WakeLock!
It looks like that's a device limitation and I don't know how you could work around that without using a WakeLock. We have a really old piece of code which you could modify to your needs which pretty much always worked for us:
public static void bringToFront() {
try {
PowerManager pm = (PowerManager) MainActivity.getAppContext().getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE, "ALARM");
wl.acquire();
KeyguardManager keyguardManager = (KeyguardManager) MainActivity.getAppContext().getSystemService(Activity.KEYGUARD_SERVICE);
KeyguardManager.KeyguardLock lock = keyguardManager.newKeyguardLock(KEYGUARD_SERVICE);
lock.disableKeyguard();
if (MainActivity.getAppActivity() != null) {
MainActivity.getAppActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
}
} catch(Exception e){
e.printStackTrace();
Log.w(TAG, "bringToFront Err: "+e.toString());
}
}

Android: Which events do wakeup a device

I have written an android application and now there is a problem.
If my application is running and I power off my device, then sometimes it just wakes up after about 8 seconds and then the screen is on and it shows my application again.
My question is:
Which events or processing constraints (like handling broadcast intents) do wakeup a device?
Edit: Will an alarm with RCT_WAKEUP turn on the device screen?
Thanks in advance!
The AlarmManager won't actually turn the screen on for you. You can use a wakelock instead.
PowerManager.WakeLock wakelock;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
.........
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakelock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK
| PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "AlarmReceiver");
wakelock.acquire();
}
When you're done with the activity just be sure to release the wakelock:
#Override
protected void onStop() {
super.onStop();
wakelock.release();
}
You also need to add the wake lock permission in your manifest file:
<uses-permission android:name="android.permission.WAKE_LOCK"/>
Alternatively, if you don't want to have to include this extra permission you can use the following code in your activity instead of using a wakelock:
this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN |
WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD |
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED |
WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON |
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

FLAG_TURN_SCREEN_ON does not always work

i start an activity from a BroadcastReceiver, which is triggered by an alaram (RTC_WAKEUP type). in onCreate of that activity i add these flags
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD |
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED |
WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON |
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
);
problem is that sometimes (approximately 10% cases) the screen does not turn on. the alarm is correctly triggered (i here the sound of a notification, which is also fired in the receiver's onReceive(). then, if i hit the phone's power button, the screen turns on, showing my activity, and instantly turns off. after that, the power button works good. this happen on android 2.3.7 and here is the onReceive() method
#Override
public void onReceive(Context context, Intent intent) {
m_Context = context;
Bundle extras = intent.getExtras();
final int id = extras.getInt("timer_id");
Intent activityIntent = new Intent(m_Context, MyActivity.class);
activityIntent.putExtra("timer_id", id);
activityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
m_Context.startActivity(activityIntent);
// and now load the alarm sound and play it for the desired time
showFinishedNotification();
}
i would like to avoid using PowerManager, as it needs a permission, and the flags are the prefered way.
what could be a problem? logcat does not show any problems...
From my experience and research on this topic:
The FLAG_TURN_SCREEN_ON can not be used to turn the screen ON and OFF multiple times in your application.
The FLAG_TURN_SCREEN_ON can only be used once to turn the screen ON when creating a new activity (preferably in the onCreate() method) or when re-creating a view.
Now, you can get around this limitation by:
Launching a new activity and setting the flag there, then finishing the activity (by the user or programmatically) to let the screen turn off.
Setting the params.screenBrightness parameters to as "dim" as possible, sometimes the screen "appears OFF". You can then increase the brightness to "turn ON" the screen. However, this often does not work as the screen is still dim but visible, also this doesn't work if the user locks the phone.
Using the Power Manager Wakelock (this still works but Android deprecated this functionality, so they are discouraging the use of this technique). However, as far as I can tell this is the only way I can get my application to turn the screen ON/OFF reliably.
None of these are ideal (in fact they feel like hacks) but just use the one that better suits your application needs.
You can read more here:
Android Alarm Clock Source Code
Android Desk Clock Source Code
Dimming the screen to appear OFF/ON
Using a wakelock to keep the screen ON/OFF
Waking up device and turning screen ON multiple options
I'm a bit late to the party here but I've been fighting this for a while now and finally found a way to get the screen to unlock every time. I add the flags in the onAttachToWindow() event. Typically I do this from a WakefulBroadcastReceiver so the screen transitions smoothly but that's use-case dependent.
#Override
public void onAttachedToWindow() {
super.onAttachedToWindow();
//Screen On
getWindow().addFlags(
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
| WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
}
private void clearFlags() {
//Don't forget to clear the flags at some point in time.
getWindow().clearFlags(
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
| WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
}
problem is that sometimes (approximately 10% cases) the screen does not turn on
If I had to guess, the device is falling back asleep before the activity starts up. Once onReceive() returns, the device can and will fall back asleep, and it will be some time after onReceive() returns before your activity will start.
This same scenario, but replacing startActivity() with startService(), is why I had to write WakefulIntentService, which uses a WakeLock to ensure that the device stays awake long enough for it to do its work, then releases the WakeLock.
Late answer But it will help for anyone.
For higher and lower versions use following code (it working fine)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
setShowWhenLocked(true);
setTurnScreenOn(true);
KeyguardManager keyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
keyguardManager.requestDismissKeyguard(this, null);
}
else{
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
| WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD |
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED |
WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
}
setContentView(R.layout.activity_incoming_call);
}
Important Note: you should place before setContentView()
I use these three methods simultaneously which works at almost any device.
public static void turnScreenOnThroughKeyguard(#NonNull Activity activity) {
userPowerManagerWakeup(activity);
useWindowFlags(activity);
useActivityScreenMethods(activity);
}
private static void useActivityScreenMethods(#NonNull Activity activity) {
if (VERSION.SDK_INT >= VERSION_CODES.O_MR1) {
try {
activity.setTurnScreenOn(true);
activity.setShowWhenLocked(true);
} catch (NoSuchMethodError e) {
Log.e(e, "Enable setTurnScreenOn and setShowWhenLocked is not present on device!");
}
}
}
private static void useWindowFlags(#NonNull Activity activity) {
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
| WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
}
private static void userPowerManagerWakeup(#NonNull Activity activity) {
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
WakeLock wakelock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, tag);
wakeLock.acquire(TimeUnit.SECONDS.toMillis(5));
}
Targeting sdk 30
Following code enables to open Activity from PendingIntent, even if application
was cleared from recent apps
and screen is dimmed
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(view)
turnOnScreen()
}
private fun turnOnScreen() {
window.addFlags(
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON or
WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON
)
setTurnScreenOn(true)
setShowWhenLocked(true)
val keyguardManager = getSystemService(KEYGUARD_SERVICE) as KeyguardManager
keyguardManager.requestDismissKeyguard(this, null)
}

Android detect phone lock event

I want to be able to detect the phone lock event. When my app is running, if I press the red button (call end button/power button), the phone gets locked and the screen goes blank. I want to be able to detect this event, is it possible?
Alternatively you could do this:
#Override
protected void onPause()
{
super.onPause();
// If the screen is off then the device has been locked
PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
boolean isScreenOn;
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
isScreenOn = powerManager.isInteractive();
} else {
isScreenOn = powerManager.isScreenOn();
}
if (!isScreenOn) {
// The screen has been locked
// do stuff...
}
}
Have a Broadcast Receiver
android.intent.action.SCREEN_ON
and
android.intent.action.SCREEN_OFF
Related: Read CommonsWare's Answer Here.
Register a broadcast with IntentFilter filter.addAction(Intent.ACTION_USER_PRESENT)
works pretty well even screen is turned on/off
Koltin format of Robert's solution.
override fun onPause() {
super.onPause()
// If the screen is off then the device has been locked
val powerManager = getSystemService(POWER_SERVICE) as PowerManager
val isScreenOn: Boolean = powerManager.isInteractive
if (!isScreenOn) {
// The screen has been locked
// do stuff...
}
}
I am assuming Kitkat version is quite old already.

Turning on screen programmatically

I would like to unlock screen and switching it on to show a popup on an event trigger. I am able to unlock the screen using
newKeyguardLock = km.newKeyguardLock(HANDSFREE);
newKeyguardLock.disableKeyguard();
on KeyGuardService but I cannot turn on the screen. I am using
wl = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, HANDSFREE);
wl.acquire();
but with no success. The screen still remains off.
How can I achieve this?
Note from author: I wrote this back in 2012. I don't know if it works anymore. Be sure to check out the other more recent answers.
Amir's answer got me close, but you need the ACQUIRE_CAUSES_WAKEUP flag at least (Building against Android 2.3.3).
WakeLock screenLock = ((PowerManager)getSystemService(POWER_SERVICE)).newWakeLock(
PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "TAG");
screenLock.acquire();
//later
screenLock.release();
This is very popular question but the accepted answer now is outdated.
Below is latest way to Turn On Screen OR wake up your device screen from an activity:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
this.setTurnScreenOn(true);
} else {
final Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
}
Use WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON but FLAG_TURN_SCREEN_ON flag has been deprecated in API level 27 so you can use Activity.setTurnScreenOn(true) from API level 27 onward.
In your main activity's OnCreate() write following code:
((PowerManager)getSystemService(POWER_SERVICE)).newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "TAG").acquire();
It causes the device to wake up.
Do not forget disableKeyguard() to unlock the device...
undefined's answer with NullPointer check and set timeout :
private void turnOnScreen() {
PowerManager.WakeLock screenLock = null;
if ((getSystemService(POWER_SERVICE)) != null) {
screenLock = ((PowerManager)getSystemService(POWER_SERVICE)).newWakeLock(
PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "TAG");
screenLock.acquire(10*60*1000L /*10 minutes*/);
screenLock.release();
}
}
This is how you can do it:
PowerManager powerManager = (PowerManager) context.getSystemService(context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK |
PowerManager.ACQUIRE_CAUSES_WAKEUP |
PowerManager.ON_AFTER_RELEASE, "appname::WakeLock");
//acquire will turn on the display
wakeLock.acquire();
make sure to set permission in the manifest :
<uses-permission android:name="android.permission.WAKE_LOCK"/>

Categories

Resources