Android device wont switch on programatically - android

We have written a test app to try and debug a issue with a 3rd party by reproducing the issues with our own source code.
The app has a feature to allow us to set times for when the devices switches off then on. This is to comply with green power saving policies.
The app switches the device off fine, but on switch on, we hear a 'click' at the expected time, but the display remains off. We wrote a test app and found this works well on other Android devices, but on the problem device we get the same - just the sound of the power relay clicking on, but nothing else.
We are wondering if this is something to do with a system setting on the devices that controls this behaviour.
The code to switch on is as follows:
public void wakeupTimer(){
new CountDownTimer(wakeupTime * 1000, 1000) {
public void onTick(long millisUntilFinished) {
textTimer.setText("0:"+checkDigit(wakeupTime));
wakeupTime--;
}
public void onFinish() {
PowerManager pm = (PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = pm.newWakeLock(( PowerManager.FULL_WAKE_LOCK
| PowerManager.ON_AFTER_RELEASE
| PowerManager.ACQUIRE_CAUSES_WAKEUP), "commandandcontrol:TAG");
wakeLock.acquire();
finish();
}
}.start();
}

Related

PowerManager.isIgnoringBatteryOptimizations always returns true even if is removed from 'Not optimized apps'

I have a mileage logbook app which does GPS tracking and is able to establish a OBDII connection to a car in background.
Now I want to show a Popup which informs the users if my app is not whitelisted in doze since this may stop my background (actually foreground) services...
I do:
String PACKAGE_NAME = getApplicationContext().getPackageName();
PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
boolean status = false;
status = pm.isIgnoringBatteryOptimizations(PACKAGE_NAME);
if (!status) {
// show popup
}
but PowerManager.isIgnoringBatteryOptimizations always returns 'true' even if it is removed from 'Not optimized apps' again. Only if I uninstall the app 'false' is returned again...
Tested on Galaxy Note 8 (Android 8.0) and Emulator 8.1
Question is simple: Is this a bug? Or how to remove the app from whitelist so that PowerManager.isIgnoringBatteryOptimizations is returnung 'false' again?
I have made simple one activity app that requests
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
and put this code into onCreate
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent();
String packageName = this.getPackageName();
PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
if (pm.isIgnoringBatteryOptimizations(packageName))
intent.setAction(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS);
else {
intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
intent.setData(Uri.parse("package:" + packageName));
}
this.startActivity(intent);
}
I have tested it on 8.1 emulator and I got the same behavior. You can possibly unisntall app or switch its state from optimized to not optimized in all app list in settings. I guess Bob Snyder showed right issue in google tracker.
Same here. Android 9 emulator.
Uninstalling the app and installing it again makes the method to work again.

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

MediaPlayer cutting off playback too early on Lollipop when Screen is off

I've been running into an issue with the MediaPlayer on Lollipop devices. Basically when the device screen is off (i.e. user locked the device) the playback continues, but ends about 1 - 2 seconds too early. This doesn't happen when the screen is on though.
I have an onCompletionListener on the MediaPlayer:
#Override
public void onCompletion(final MediaPlayer mediaPlayer) {
int progress = mediaPlayer.getCurrentPosition();
int duration = mediaPlayer.getDuration();
Log.d("PlaybackController", "progress: " + progress + " duration: " + duration);
Log.d("PlaybackController", "Delay: " + (duration - progress)); // I'm seeing a difference of 1 - 3 seconds :(.
mServiceHandler.postDelayed(new Runnable() {
#Override
public void run() {
broadcastCompleted();
}
}, Math.max(duration - progress, 0));
}
This usually prints: Delay: [1500 - 3000]. I was wondering if there was a wake lock I'm missing, but I'm making the correct locks mentioned here: http://developer.android.com/guide/topics/media/mediaplayer.html, which include a PARTIAL_WAKE_LOCK and a WifiLock. Is there something else I'm missing?
Ok it looks like the issue is Android 5.0.1's experimental MediaPlayer called NuPlayer. NuPlayer is being enabled by default on all Android 5.0.1 devices and is only disabled through Developer Options. I've filed a bug against Android here: https://code.google.com/p/android/issues/detail?id=94069&thanks=94069&ts=1420659450
Here's a sample email you can send your users when they face issues with Media playback on Android 5.0.1 devices:
It looks like this might be a bug on Android's new experimental MediaPlayer called NuPlayer. To fix this, please follow these steps:
Go to Android Settings
Go to "About Phone"
Scroll down to "Build Number" and tap the Build number 7 times.
You'll see a message saying "you are now X steps away from being a developer".
After tapping it 7 times it will say "You are now a developer!"
Go back to the main settings screen and you'll see a new option called "Developer Options" right above "About Phone"
Go into Developer Options and Unselect "Use NuPlayer (experimental)" under the Media section.
Update:
Setting a partial wake lock on the MediaPlayer resolves this problem:
playerToPrepare.setWakeMode(context, PowerManager.PARTIAL_WAKE_LOCK);
A partial wake lock shouldn't have too big of an impact, and it seems like MediaPlayer itself cleans this up when playback completes.
-- Original Answer ---
I'm cross-posting my answer from here Prevent my audio app using NuPlayer on Android Lollipop 5.x?, until there's a fix out for NuPlayer, the best you can do is to detect when NuPlayer is enabled and take the user to the Developer Settings.
This approach checks Android's system properties values to see if the user have enabled the use of AwesomePlayer or not under Developer Settings. Since Lollipop have NuPlayer on by default, if this value is disabled, we know NuPlayer will be used.
Drop SystemProperties.java into your project for access to read the system properties, do not change its package name from android.os (it calls through to its corresponding JNI methods, so needs to stay the same).
You can now check if the phone is Lollipop/5.0, if AwesomePlayer is enabled, and act accordingly if it's not (e.g. by opening the Developer Settings):
public void openDeveloperSettingsIfAwesomePlayerNotActivated(final Context context) {
final boolean useAwesome = SystemProperties.getBoolean("persist.sys.media.use-awesome", false);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && !useAwesome) {
final Intent intent = new Intent(Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS);
context.startActivity(intent);
}
}

USB Host port disabled when Android screen is locked

I am developing an application that communicates with an Embedded Device via the Android Devices USB Host port. I noticed that when the screen is locked USB Host port is disabled and no communication occurs.
How can I prevent the USB Host port from turning off so that communication can occur when the screen is locked?
------------- USB Host ---------------
| Android | <------------------> | Device |
------------- ---------------
Note: I can have root access on the Android system if necessary.
Thanks for the tip Chris Stratton. Using a PARTIAL_WAKE_LOCK the screen can turn off yet the CPU remains running. This is suitable for my application.
I created a quick app to test this:
public class MainActivity extends Activity {
PowerManager pm;
PowerManager.WakeLock wl;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Tag");
}
#Override
protected void onStart() {
super.onStart();
if (wl != null) {
wl.acquire();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (wl != null) {
wl.release();
}
}
I tested it by connecting a mouse to the USB Host. When the screen was locked the mouse did not turn off as I would like.
Another option I came across which I have not tried. You may be able to adjust the system resource which controls the power management of the USB device. You probably need root access for this.
Changing the default idle-delay time
------------------------------------
The default autosuspend idle-delay time (in seconds) is controlled by
a module parameter in usbcore. You can specify the value when usbcore
is loaded. For example, to set it to 5 seconds instead of 2 you would
do:
modprobe usbcore autosuspend=5
Equivalently, you could add to a configuration file in /etc/modprobe.d
a line saying:
options usbcore autosuspend=5
Some distributions load the usbcore module very early during the boot
process, by means of a program or script running from an initramfs
image. To alter the parameter value you would have to rebuild that
image.
If usbcore is compiled into the kernel rather than built as a loadable
module, you can add
usbcore.autosuspend=5
to the kernel's boot command line.
Finally, the parameter value can be changed while the system is
running. If you do:
echo 5 >/sys/module/usbcore/parameters/autosuspend
then each new USB device will have its autosuspend idle-delay
initialized to 5. (The idle-delay values for already existing devices
will not be affected.)
Setting the initial default idle-delay to -1 will prevent any
autosuspend of any USB device. This has the benefit of allowing you
then to enable autosuspend for selected devices.
Source:
https://android.googlesource.com/kernel/common/+/android-3.10/Documentation/usb/power-management.txt

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