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);
Related
I need help with my project , I'm supposed to make a BroadcastReceiver fires up a full screen activity over current lock screen .
I tried this on my activity :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i("onCreate","success");
PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = pm.newWakeLock((PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP), "TAG");
wakeLock.acquire(10*60*1000L /*10 minutes*/);
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);
this.setShowWhenLocked(true);
this.setTurnScreenOn(true);
setContentView(R.layout.activity_stop);
}
BroadcastReceiver:
Intent i = new Intent(context,StopTheAlarm.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
AndroidManifest.xml:
<activity android:name=".Stop"
android:showOnLockScreen="true"
android:screenOrientation="sensorPortrait">
</activity>
but it doesn't work on my android 7.0.1 phone
Update :
i removed
this.setShowWhenLocked(true);
this.setTurnScreenOn(true);
which were causing app to crash
Your solution won't work on Android API 27 and later. Use code from this thread.
I would like my app to be able to turn the screen on and display my app. Let's say I'm setting an alarm and every hour I want my app to be displayed for 2 mins before the device naturally sleeps.
I see that WakeLock (FULL_LOCK) and KeyguardManager are deprecated.
I have created a WakefulBroadcastReceiver and service and these are working.
#Override
protected void onHandleIntent(Intent intent) {
// I need to show the screen here!
for (int i=0; i<5; i++) {
Log.i("SimpleWakefulReceiver", "Running service " + (i + 1)
+ "/5 # " + SystemClock.elapsedRealtime());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
}
Log.i("SimpleWakefulReceiver", "Completed service # " +
SystemClock.elapsedRealtime());
SimpleWakefulReceiver.completeWakefulIntent(intent);
}
How do I programmatically turn on the screen, get past lock and display my Activity from the IntentService ?
Thanks
You can use this code to turn the screen on.
lock = ((KeyguardManager) getSystemService(Activity.KEYGUARD_SERVICE)).newKeyguardLock(KEYGUARD_SERVICE);
powerManager = ((PowerManager) getSystemService(Context.POWER_SERVICE));
wake = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "TAG");
lock.disableKeyguard();
wake.acquire();
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
| WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON);
You need the following permission in AndroidManifest.xml file:
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
EDIT (USE THIS ONE, NOTHING IS DEPRECATED):
There is an one more alternative for doing this, for that you need to launch an activity, In the activity onCreate() you need to add the flags to the window.
For example:
#Override
protected void onCreate(Bundle savedInstanceState) {
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 | WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON);`
}
I don't know what you're talking about, wakelock is definitely not deprecated. Certain types are no longer the Google preferred way of doing things, but normal wakelocks are still around and still the easiest way of doing this. Make sure to add the ACQUIRE_CAUSES_WAKEUP flag when taking the lock. In fact notice that a WakefulBroadcastReceiver is implemented by using wakelocks.
You can use this code to turn the screen on.
private void turnScreenOn() {
int flags = WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON;
getWindow().addFlags(flags);
}
You can use this code to keep it on until the wake lock is dimissed.
<uses-permission android:name="android.permission.WAKE_LOCK" />
private PowerManager mPowerManager;
private PowerManager.WakeLock mWakeLock;
#Override
public void onCreate() {
super.onCreate();
mPowerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
mWakeLock = mPowerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "Service");
}
private void acquireWakeLock() {
try {
mWakeLock.acquire();
}
catch (Exception e) {
e.printStackTrace();
}
}
private void releaseWakeLock() {
try {
mWakeLock.release();
}
catch (Exception e) {
}
}
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)
}
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.
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"/>