switch off/on screen on PARTIAL_WAKE_LOCK - android

I'm using this code to enter in PARTIAL_WAKE_LOCK mode:
PowerManager pm = PowerManager.getSystemService(Context.POWER_SERVICE);
screenWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"screenWakeLock");
pm.acquire();
but I do not succeed to switch off the screen and switch on when I need it,I read tens of examples without succeed in it.
I can't use code that require the permission DEVICE_POWER like goToSleep() and wakeUp().
My goal is switch on the screen for 1 second and to switch off it for 10 seconds, and then start again.
Thanks all.

The use of PowerManager requires DEVICE_POWER permission that is only for applications that are signed by the same signature was used to sign the firmware. That is why you cannot use goToSleep() and wakeUp().
This code worked for me to turn on/off the screen:
//Turn off - brighness to 0;
WindowManager.LayoutParams params = getWindow().getAttributes();
params.flags |= LayoutParams.FLAG_KEEP_SCREEN_ON;
params.screenBrightness = 0;
getWindow().setAttributes(params);
To turn on just change the brighness to >0;

Related

AMOLED display does not save power with full black display. Why is it so? [duplicate]

Before marking this post as a "duplicate", I am writing this post because no other post holds the solution to the problem.
I am trying to turn off the device, then after a few minutes or sensor change, turn it back on.
Turn Off Display Tests
I am able to turn off the screen using:
params.flags |= LayoutParams.FLAG_KEEP_SCREEN_ON;
params.screenBrightness = 0;
getWindow().setAttributes(params);
I have been unable to turn off the screen using the wl.release() method.
Turn On Display Test
My first guess, as follows, does not work. Nothing happens, screen remains off.
params.flags |= LayoutParams.FLAG_KEEP_SCREEN_ON;
params.screenBrightness = -1f;
getWindow().setAttributes(params);
I also then tried to use wakelocks, with no success.
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "tag");
wl.acquire();
Finally I have tried the following, with no result.
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
All in all, I don't get any kind of error in the console for any of these methods. My test text "Screen should be on", is on the the screen when I turn on the device using the power button. This shows that the code should have ran. Please only answer if you have tested the code, it seems like many of the functions such as params.screenBrightness = -1, do not work as they should according to the sdk.
I am going to assume you only want this to be in effect while your application is in the foreground.
This code:
params.flags |= LayoutParams.FLAG_KEEP_SCREEN_ON;
params.screenBrightness = 0;
getWindow().setAttributes(params);
Does not turn the screen off in the traditional sense. It makes the screen as dim as possible. In the standard platform there is a limit to how dim it can be; if your device is actually allowing the screen to turn completely off, then it is some peculiarity of the implementation of that device and not a behavior you can count on across devices.
In fact using this in conjunction with FLAG_KEEP_SCREEN_ON means that you will never allow the screen to go off (and thus the device to go into low-power mode) even if the particular device is allowing you to set the screen brightness to full-off. Keep this very strongly in mind. You will be using much more power than you would if the screen was really off.
Now for turning the screen back to regular brightness, just setting the brightness value should do it:
WindowManager.LayoutParams params = getWindow().getAttributes();
params.screenBrightness = -1;
getWindow().setAttributes(params);
I can't explain why this wouldn't replace the 0 value you had previously set. As a test, you could try putting a forced full brightness in there to force to that specific brightness:
WindowManager.LayoutParams params = getWindow().getAttributes();
params.screenBrightness = 1;
getWindow().setAttributes(params);
This definitely works. For example, Google's Books apps uses this to allow you to set the screen brightness to dim while using a book and then return to regular brightness when turning that off.
To help debug, you can use "adb shell dumpsys window" to see the current state of your window. In the data for your window, it will tell you the current LayoutParams that have been set for it. Ensure the value you think is actually there.
And again, FLAG_KEEP_SCREEN_ON is a separate concept; it and the brightness have no direct impact on each other. (And there would be no reason to set the flag again when undoing the brightness, if you had already set it when putting the brightness to 0. The flag will stay set until you change it.)
I had written this method to turn on the screen after screen lock. It works perfectly for me. Try it-
private void unlockScreen() {
Window window = this.getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
window.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
window.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
}
And call this method from onResume().
I would suggest this one:
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "tag");
wl.acquire();
The flag ACQUIRE_CAUSES_WAKEUP is explained like that:
Normal wake locks don't actually turn on the illumination. Instead,
they cause the illumination to remain on once it turns on (e.g. from
user activity). This flag will force the screen and/or keyboard to
turn on immediately, when the WakeLock is acquired. A typical use
would be for notifications which are important for the user to see
immediately.
Also, make sure you have the following permission in the AndroidManifewst.xml file:
<uses-permission android:name="android.permission.WAKE_LOCK" />
Hi I hope this will help:
private PowerManager mPowerManager;
private PowerManager.WakeLock mWakeLock;
public void turnOnScreen(){
// turn on screen
Log.v("ProximityActivity", "ON!");
mWakeLock = mPowerManager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "tag");
mWakeLock.acquire();
}
#TargetApi(21) //Suppress lint error for PROXIMITY_SCREEN_OFF_WAKE_LOCK
public void turnOffScreen(){
// turn off screen
Log.v("ProximityActivity", "OFF!");
mWakeLock = mPowerManager.newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, "tag");
mWakeLock.acquire();
}
WakeLock screenLock = ((PowerManager)getSystemService(POWER_SERVICE)).newWakeLock(
PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "TAG");
screenLock.acquire();
//later
screenLock.release();
//User Manifest file
Are you sure you requested the proper permission in your Manifest file?
<uses-permission android:name="android.permission.WAKE_LOCK" />
You can use the AlarmManager1 class to fire off an intent that starts your activity and acquires the wake lock. This will turn on the screen and keep it on. Releasing the wakelock will allow the device to go to sleep on its own.
You can also take a look at using the PowerManager to set the device to sleep: http://developer.android.com/reference/android/os/PowerManager.html#goToSleep(long)
Simply add
android:keepScreenOn="true"
or call
setKeepScreenOn(true)
on parent view.
The best way to do it ( using rooted devices) :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
.
.
.
int flags = WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON;
getWindow().addFlags(flags); // this is how your app will wake up the screen
//you will call this activity later
.
.
.
}
Now we have this two functions:
private void turnOffScreen(){
try{
Class c = Class.forName("android.os.PowerManager");
PowerManager mPowerManager = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
for(Method m : c.getDeclaredMethods()){
if(m.getName().equals("goToSleep")){
m.setAccessible(true);
if(m.getParameterTypes().length == 1){
m.invoke(mPowerManager,SystemClock.uptimeMillis()-2);
}
}
}
} catch (Exception e){
}
}
And this:
public void turnOnScreen(){
Intent i = new Intent(this,YOURACTIVITYWITHFLAGS.class);
startActivity(i);
}
Sorry for my bad english.
Here is a successful example of an implementation of the same thing, on a device which supported lower screen brightness values (I tested on an Allwinner Chinese 7" tablet running API15).
WindowManager.LayoutParams params = this.getWindow().getAttributes();
/** Turn off: */
params.flags = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
//TODO Store original brightness value
params.screenBrightness = 0.1f;
this.getWindow().setAttributes(params);
/** Turn on: */
params.flags = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
//TODO restoring from original value
params.screenBrightness = 0.9f;
this.getWindow().setAttributes(params);
If someone else tries this out, pls comment below if it worked/didn't work and the device, Android API.
To keep screen on:
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
Back to screen default mode:
just clear the flag FLAG_KEEP_SCREEN_ON
getWindow().clearFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
This is worked on Marshmallow
private final String TAG = "OnOffScreen";
private PowerManager _powerManager;
private PowerManager.WakeLock _screenOffWakeLock;
public void turnOnScreen() {
if (_screenOffWakeLock != null) {
_screenOffWakeLock.release();
}
}
public void turnOffScreen() {
try {
_powerManager = (PowerManager) this.getSystemService(POWER_SERVICE);
if (_powerManager != null) {
_screenOffWakeLock = _powerManager.newWakeLock(PROXIMITY_SCREEN_OFF_WAKE_LOCK, TAG);
if (_screenOffWakeLock != null) {
_screenOffWakeLock.acquire();
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
If your app is a system app,you can use PowerManager.goToSleep() to turn screen off,you requires a special permission
before you use goToSleep(), you need use reflection just like:
public static void goToSleep(Context context) {
PowerManager powerManager= (PowerManager)context.getSystemService(Context.POWER_SERVICE);
try {
powerManager.getClass().getMethod("goToSleep", new Class[]{long.class}).invoke(powerManager, SystemClock.uptimeMillis());
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
Now,you can use goToSleep() to turn screen off.
This is what happens when the power key is pressed to turn off the screen.
As per Android API 28 and above you need to do the following to turn on the screen
setShowWhenLocked(true);
setTurnScreenOn(true);
KeyguardManager keyguardManager = (KeyguardManager)
getSystemService(Context.KEYGUARD_SERVICE);
keyguardManager.requestDismissKeyguard(this, null);
Regarding to Android documentation it can be achieve by using following code line:
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
I have added this in my onCreate method and it works fine.
On the link you will find different ways to achieve this and general explanation as well.
Link to the documenation: https://developer.android.com/training/scheduling/wakelock.html
I wouldn't have hope of "waking the screen" in the activity. If the screen is off the activity is probably in a paused state and shouldn't be running any code.
When waking up, there is the issue of the lockscreen. I don't know how any app can automatically bypass the lockscreen.
You should consider running your background tasks in a service, and then using the notification manager to send a notification when whatever is detected. The notification should provide some sort of device alert (screen wake up, notification icon, notification led, etc). When clicking the notification it can launch the intent to start your activity.
You could also attempt to start the activity direct from the service, but I really don't know if that will turn the screen on or bypass the lockscreen.
I have tried all above solution but none worked for me. so I googled and found below solutions. I tried and it worked.
https://www.tutorialspoint.com/how-to-turn-android-device-screen-on-and-off-programmatically
if there is any suggestion then please give

Android 4.3 : How can I check if user has lock enabled?

I want my app to behave differently (not store stuff) if the user does not have a lock screen or only swipe enabled.
The top answer here: check whether lock was enabled or not has been edited to say the code no longer works after upgrade to Android 4.3.
Is there anyway to detect this on Android 4.3?
Ok, so it seems it is possible with some reflection. Not the best solution, but at least it works on the devices we tried:
Class<?> clazz = Class.forName("com.android.internal.widget.LockPatternUtils");
Constructor<?> constructor = clazz.getConstructor(Context.class);
constructor.setAccessible(true);
Object utils = constructor.newInstance(context);
Method method = clazz.getMethod("isSecure");
return (Boolean)method.invoke(utils);
You can check it with KeyguardManager:
KeyguardManager keyguardMgr = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
if(keyguardMgr.isKeyguardSecure()){
// Secure keyguard, the keyguard requires a password to unlock
} else {
// Insecure keyguard, the keyguard doesn't require a password to unlock
}
You can check with KeyguardManager's method isKeyguardSecure() to make sure if lock or passcode is enabled or not.
KeyguardManager keyguardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
Toast.makeText(this,"KeyGuardEnabled ? "+ keyguardManager.isKeyguardSecure(),Toast.LENGTH_LONG).show();

Prevent screen sleeping

Android v4.2.2. I'm trying to stop the screen from going to sleep. I've tried a few things like changing the relevant settings in the db:
adb shell "sqlite3 /data/data/com.android.providers.settings/databases/settings.db \"update system set value='-1' where name='screen_off_timeout'\";"
But that didn't work - screen just went to sleep almost immediately. If I go to the settings app there isn't an option to disable it. Instead, it ranges from 15s to 30m.
I have also tried to set the KEEP_SCREEN_ON FLAG in the application but that stops working when I switch to a new activity.
Is there anything else I can try. I was hoping a db setting would do the job. Here is my system db as it stands. Perhaps a setting I am missing and can insert?
1|volume_music|11
2|volume_ring|5
3|volume_system|7
4|volume_voice|4
5|volume_alarm|6
6|volume_notification|5
7|volume_bluetooth_sco|7
8|mode_ringer_streams_affected|174
9|mute_streams_affected|46
10|vibrate_when_ringing|0
11|dim_screen|0
13|dtmf_tone_type|0
14|hearing_aid|0
15|tty_mode|0
16|screen_brightness|102
17|screen_brightness_mode|0
18|window_animation_scale|1.0
19|transition_animation_scale|1.0
20|accelerometer_rotation|1
21|haptic_feedback_enabled|1
22|notification_light_pulse|1
23|dtmf_tone|1
24|sound_effects_enabled|1
26|lockscreen_sounds_enabled|1
27|pointer_speed|0
28|next_alarm_formatted|
29|alarm_alert|content://media/internal/audio/media/5
30|notification_sound|content://media/internal/audio/media/7
31|ringtone|content://media/internal/audio/media/9
32|volume_music_headset|10
33|volume_music_last_audible_headset|10
34|volume_music_headphone|10
35|volume_music_last_audible_headphone|10
36|time_12_24|24
37|date_format|dd-MM-yyyy
39|stay_on_while_plugged_in|1
45|screen_off_timeout|-1
Your setting db contains default time out set by the system which is probably low so the device went to sleep immediately due to low timeout value. You can issue adb shell command to increase screen timeout.
adb shell settings put system screen_off_timeout 60000
Note: 60000 = 1 minute
You can also update setting db with the desired timeout and then push db back to device but it requires root. Above command does not require device to be rooted.
This is related to Activity , There is no impact from DB. Just add android:keepScreenOn="true" to the layout in your xml
Did you try this
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
wl.acquire();
For more go through this link http://thiranjith.com/2012/02/22/android-prevent-screen-timeout/

How to show Activity over lock screen in 4.2 jellybean while in sleep mode

i have implemented keyguard.wakelock to show activity on lock-screen(sleep mode) but
it show activity only in android version 2.2 and get crashed on above 2.3 version and some time on version 2.2 it show activity for few sec and then dis-appear over lock screen .so plz guide me to obtain this scenario working on every Android version .
here is the code i have used .
KeyguardManager km = (KeyguardManager)getSystemService(KEYGUARD_SERVICE);
boolean iskeyguardopen =km.inKeyguardRestrictedInputMode();
//KeyguardManager.KeyguardLock kl = km.newKeyguardLock("IN");
Log.v("check key guard is enabled or not",""+km.inKeyguardRestrictedInputMode());
//setContentView(R.layout.customactivitypop);
count=1;
kl = km.newKeyguardLock("Taxi");
kl.disableKeyguard();
PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
PowerManager.WakeLock wl=pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.FULL_WAKE_LOCK , "My_App");
wl.acquire();
wl.release();
Thank all.

Android: How to turn screen on and off programmatically?

Before marking this post as a "duplicate", I am writing this post because no other post holds the solution to the problem.
I am trying to turn off the device, then after a few minutes or sensor change, turn it back on.
Turn Off Display Tests
I am able to turn off the screen using:
params.flags |= LayoutParams.FLAG_KEEP_SCREEN_ON;
params.screenBrightness = 0;
getWindow().setAttributes(params);
I have been unable to turn off the screen using the wl.release() method.
Turn On Display Test
My first guess, as follows, does not work. Nothing happens, screen remains off.
params.flags |= LayoutParams.FLAG_KEEP_SCREEN_ON;
params.screenBrightness = -1f;
getWindow().setAttributes(params);
I also then tried to use wakelocks, with no success.
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "tag");
wl.acquire();
Finally I have tried the following, with no result.
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
All in all, I don't get any kind of error in the console for any of these methods. My test text "Screen should be on", is on the the screen when I turn on the device using the power button. This shows that the code should have ran. Please only answer if you have tested the code, it seems like many of the functions such as params.screenBrightness = -1, do not work as they should according to the sdk.
I am going to assume you only want this to be in effect while your application is in the foreground.
This code:
params.flags |= LayoutParams.FLAG_KEEP_SCREEN_ON;
params.screenBrightness = 0;
getWindow().setAttributes(params);
Does not turn the screen off in the traditional sense. It makes the screen as dim as possible. In the standard platform there is a limit to how dim it can be; if your device is actually allowing the screen to turn completely off, then it is some peculiarity of the implementation of that device and not a behavior you can count on across devices.
In fact using this in conjunction with FLAG_KEEP_SCREEN_ON means that you will never allow the screen to go off (and thus the device to go into low-power mode) even if the particular device is allowing you to set the screen brightness to full-off. Keep this very strongly in mind. You will be using much more power than you would if the screen was really off.
Now for turning the screen back to regular brightness, just setting the brightness value should do it:
WindowManager.LayoutParams params = getWindow().getAttributes();
params.screenBrightness = -1;
getWindow().setAttributes(params);
I can't explain why this wouldn't replace the 0 value you had previously set. As a test, you could try putting a forced full brightness in there to force to that specific brightness:
WindowManager.LayoutParams params = getWindow().getAttributes();
params.screenBrightness = 1;
getWindow().setAttributes(params);
This definitely works. For example, Google's Books apps uses this to allow you to set the screen brightness to dim while using a book and then return to regular brightness when turning that off.
To help debug, you can use "adb shell dumpsys window" to see the current state of your window. In the data for your window, it will tell you the current LayoutParams that have been set for it. Ensure the value you think is actually there.
And again, FLAG_KEEP_SCREEN_ON is a separate concept; it and the brightness have no direct impact on each other. (And there would be no reason to set the flag again when undoing the brightness, if you had already set it when putting the brightness to 0. The flag will stay set until you change it.)
I had written this method to turn on the screen after screen lock. It works perfectly for me. Try it-
private void unlockScreen() {
Window window = this.getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
window.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
window.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
}
And call this method from onResume().
I would suggest this one:
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "tag");
wl.acquire();
The flag ACQUIRE_CAUSES_WAKEUP is explained like that:
Normal wake locks don't actually turn on the illumination. Instead,
they cause the illumination to remain on once it turns on (e.g. from
user activity). This flag will force the screen and/or keyboard to
turn on immediately, when the WakeLock is acquired. A typical use
would be for notifications which are important for the user to see
immediately.
Also, make sure you have the following permission in the AndroidManifewst.xml file:
<uses-permission android:name="android.permission.WAKE_LOCK" />
Hi I hope this will help:
private PowerManager mPowerManager;
private PowerManager.WakeLock mWakeLock;
public void turnOnScreen(){
// turn on screen
Log.v("ProximityActivity", "ON!");
mWakeLock = mPowerManager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "tag");
mWakeLock.acquire();
}
#TargetApi(21) //Suppress lint error for PROXIMITY_SCREEN_OFF_WAKE_LOCK
public void turnOffScreen(){
// turn off screen
Log.v("ProximityActivity", "OFF!");
mWakeLock = mPowerManager.newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, "tag");
mWakeLock.acquire();
}
WakeLock screenLock = ((PowerManager)getSystemService(POWER_SERVICE)).newWakeLock(
PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "TAG");
screenLock.acquire();
//later
screenLock.release();
//User Manifest file
Are you sure you requested the proper permission in your Manifest file?
<uses-permission android:name="android.permission.WAKE_LOCK" />
You can use the AlarmManager1 class to fire off an intent that starts your activity and acquires the wake lock. This will turn on the screen and keep it on. Releasing the wakelock will allow the device to go to sleep on its own.
You can also take a look at using the PowerManager to set the device to sleep: http://developer.android.com/reference/android/os/PowerManager.html#goToSleep(long)
Simply add
android:keepScreenOn="true"
or call
setKeepScreenOn(true)
on parent view.
The best way to do it ( using rooted devices) :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
.
.
.
int flags = WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON;
getWindow().addFlags(flags); // this is how your app will wake up the screen
//you will call this activity later
.
.
.
}
Now we have this two functions:
private void turnOffScreen(){
try{
Class c = Class.forName("android.os.PowerManager");
PowerManager mPowerManager = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
for(Method m : c.getDeclaredMethods()){
if(m.getName().equals("goToSleep")){
m.setAccessible(true);
if(m.getParameterTypes().length == 1){
m.invoke(mPowerManager,SystemClock.uptimeMillis()-2);
}
}
}
} catch (Exception e){
}
}
And this:
public void turnOnScreen(){
Intent i = new Intent(this,YOURACTIVITYWITHFLAGS.class);
startActivity(i);
}
Sorry for my bad english.
Here is a successful example of an implementation of the same thing, on a device which supported lower screen brightness values (I tested on an Allwinner Chinese 7" tablet running API15).
WindowManager.LayoutParams params = this.getWindow().getAttributes();
/** Turn off: */
params.flags = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
//TODO Store original brightness value
params.screenBrightness = 0.1f;
this.getWindow().setAttributes(params);
/** Turn on: */
params.flags = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
//TODO restoring from original value
params.screenBrightness = 0.9f;
this.getWindow().setAttributes(params);
If someone else tries this out, pls comment below if it worked/didn't work and the device, Android API.
To keep screen on:
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
Back to screen default mode:
just clear the flag FLAG_KEEP_SCREEN_ON
getWindow().clearFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
This is worked on Marshmallow
private final String TAG = "OnOffScreen";
private PowerManager _powerManager;
private PowerManager.WakeLock _screenOffWakeLock;
public void turnOnScreen() {
if (_screenOffWakeLock != null) {
_screenOffWakeLock.release();
}
}
public void turnOffScreen() {
try {
_powerManager = (PowerManager) this.getSystemService(POWER_SERVICE);
if (_powerManager != null) {
_screenOffWakeLock = _powerManager.newWakeLock(PROXIMITY_SCREEN_OFF_WAKE_LOCK, TAG);
if (_screenOffWakeLock != null) {
_screenOffWakeLock.acquire();
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
If your app is a system app,you can use PowerManager.goToSleep() to turn screen off,you requires a special permission
before you use goToSleep(), you need use reflection just like:
public static void goToSleep(Context context) {
PowerManager powerManager= (PowerManager)context.getSystemService(Context.POWER_SERVICE);
try {
powerManager.getClass().getMethod("goToSleep", new Class[]{long.class}).invoke(powerManager, SystemClock.uptimeMillis());
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
Now,you can use goToSleep() to turn screen off.
This is what happens when the power key is pressed to turn off the screen.
As per Android API 28 and above you need to do the following to turn on the screen
setShowWhenLocked(true);
setTurnScreenOn(true);
KeyguardManager keyguardManager = (KeyguardManager)
getSystemService(Context.KEYGUARD_SERVICE);
keyguardManager.requestDismissKeyguard(this, null);
Regarding to Android documentation it can be achieve by using following code line:
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
I have added this in my onCreate method and it works fine.
On the link you will find different ways to achieve this and general explanation as well.
Link to the documenation: https://developer.android.com/training/scheduling/wakelock.html
I wouldn't have hope of "waking the screen" in the activity. If the screen is off the activity is probably in a paused state and shouldn't be running any code.
When waking up, there is the issue of the lockscreen. I don't know how any app can automatically bypass the lockscreen.
You should consider running your background tasks in a service, and then using the notification manager to send a notification when whatever is detected. The notification should provide some sort of device alert (screen wake up, notification icon, notification led, etc). When clicking the notification it can launch the intent to start your activity.
You could also attempt to start the activity direct from the service, but I really don't know if that will turn the screen on or bypass the lockscreen.
I have tried all above solution but none worked for me. so I googled and found below solutions. I tried and it worked.
https://www.tutorialspoint.com/how-to-turn-android-device-screen-on-and-off-programmatically
if there is any suggestion then please give

Categories

Resources