I m trying to implement wake lock and wifi lock for a service. More about my scenario in this like: Wakelock implementation in a service. I m acquiring during start and releasing when the service gets destroyed. I want to monitor the battery consumption for my project, though I understand that, this approach is not good. But when my phone screen is off, it is not working. I have enabled the option: Keep Wifi on during sleep. As soon as my screen turns off, my service stops.I m using the snippet :
PowerManager powerManager = (PowerManager)getSystemService(Context.POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Lock");
if(!wakeLock.isHeld())
{
wakeLock.acquire();
}
Log.d(TAG,"Acquired Wake lock successfully");
wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifiLock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL_HIGH_PERF , "WiFi LockTag");
if(!wifiLock.isHeld())
{
wifiLock.acquire();
}
Log.d(TAG,"Acquired Wifi lock successfully");
//TO RELEASE
try{
wifiLock.release();
}catch(Exception e){
e.printStackTrace();
Log.d(TAG,"Exception while releasing WakeLock :: Can be ignoredd");
}
Any idea of why this is happening ? Thanks in advance!
to protect screen from being lock use this Spinet
public static void unlockTheScreen(Context context) {
KeyguardManager keyguardManager = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
KeyguardLock keyguardLock = keyguardManager.newKeyguardLock("TAG");
keyguardLock.disableKeyguard();
}
Add below in your wake lock
wakeLock = powermanager.newWakeLock((PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP ), "TAG");
Related
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());
}
}
I´m doing an app and I´m testing it on devices Samsung galaxy Y (Android 2.3.6) and Engel tablet 7" (Android 4.0.x).
In my app´s code I´m using this snippet in order to wake up the devices(when they are in sleep mode) and works well , but now my problem is that after wake up they never go to sleep mode anymore, only they go if I press the hardware button.
Anyone know how I can set the default energy settings after use PowerManager ?.
KeyguardManager km = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
final KeyguardManager.KeyguardLock kl = km .newKeyguardLock("MyKeyguardLock");
kl.disableKeyguard();
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
WakeLock wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK
| PowerManager.ACQUIRE_CAUSES_WAKEUP
| PowerManager.ON_AFTER_RELEASE, "MyWakeLock");
wakeLock.acquire();
Try this:
void wakeUpGirls() {
if (wakeLock != null) {
wakeLock.release();
}
KeyguardManager km = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
KeyguardLock keyguardLock = km.newKeyguardLock("TAG");
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
keyguardLock.disableKeyguard();
PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK
| PowerManager.ACQUIRE_CAUSES_WAKEUP
| PowerManager.ON_AFTER_RELEASE
| PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "MyWakeLock");
wakeLock.acquire();
}
void sleepGirls() {
if (wakeLock != null) {
wakeLock.release();
wakeLock = null;
}
}
Use this one it works for me
PowerManager powermanager= ((PowerManager)getSystemService(Context.POWER_SERVICE));
WakeLock wakeLock = powermanager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "tag");
wakeLock.acquire(9000);
wakeLock.release
KeyguardManager km =(KeyguardManager)getSystemService(KEYGUARD_SERVICE);
k1 = km.newKeyguardLock("IN");
k1.disableKeyguard();
I've been looking around for the last days and none of the answers to the questions made have helped me and I'm bumping my head with something that perhaps is simple to solve .... I want to work with the proximity sensor and what I'm doing is that if I put the finger on the sensor it turns off the screen and if I remove the finger away it turns back on the screen! I'm sucessfully turning off the screen and I'm getting the "Log.i("info", "trying to turn on!")" message when I remove the finger but somehow the screen doesn't turn on .... I've tried with wakelock (commented) and with flags with no sucess! If I remove the finger the lights on the keypad turn on but the screen won't .. If I press the power button two times it turns on the screen sucessfully! Can anyone give me an help with it? :(
#Override
public void onSensorChanged(SensorEvent event) {
if(event.sensor.getType()==Sensor.TYPE_PROXIMITY){
ProximityReading.setText("\nProximity Sensor Reading:" + String.valueOf(event.values[0]));
}
if(event.values[0] == 0) {
WindowManager.LayoutParams params = getWindow().getAttributes();
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
params.screenBrightness = 0f;
getWindow().setAttributes(params);
} else {
WindowManager.LayoutParams params = getWindow().getAttributes();
params.screenBrightness = 1f;
getWindow().setAttributes(params);
/*powermanager = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = powermanager.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP, "TAG");
wakeLock.acquire();
Log.i("info", "trying to turn on!");
}
}
if you want turn screen on,you can use the API such as "TurnScreenOn" in PowerManager,or use ACQUIRE_CAUSES_WAKEUP combined with FULL_WAKE_LOCK
I use the following method to unlock the phone,lighten it up and then reenable the keyguard lock.
public void unlockAndPowerup(){
KeyguardManager km = (KeyguardManager) mContext.getSystemService(Context.KEYGUARD_SERVICE);
final KeyguardManager.KeyguardLock kl = km.newKeyguardLock("MyKeyguardLock");
kl.disableKeyguard();
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
WakeLock wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK
| PowerManager.ACQUIRE_CAUSES_WAKEUP
| PowerManager.ON_AFTER_RELEASE, "MyWakeLock");
wakeLock.acquire();
wakeLock.release();
kl.reenableKeyguard();
}
Your procedure is wrong. It may work on some devices by chance, but that's not the way to do it.
FLAG_TURN_SCREEN_ON is supposed to be applied on the onCreate method of an activity. You need to modify your app logic.
Your screen off technique is incorrect. You're modifying brightness, that's a hacky way, and may not turn off screen at all, and drain battery.
You need to achieve it via Device Admin permission. That's the official way to do it
Locking sample code
public static void lockNow(Context c) {
DevicePolicyManager dpm = (DevicePolicyManager)c.getSystemService(Context.DEVICE_POLICY_SERVICE);
if(dpm.isAdminActive(new ComponentName(c.getApplicationContext(),DeviceAdmin.class)))
dpm.lockNow();
}
DeviceAdmin.java
import android.app.admin.DeviceAdminReceiver;
public class DeviceAdmin extends DeviceAdminReceiver {
}
In the manifest
<receiver
android:name=".admin.DeviceAdmin"
android:permission="android.permission.BIND_DEVICE_ADMIN" >
<meta-data
android:name="android.app.device_admin"
android:resource="#xml/admin" />
<intent-filter>
<action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
</intent-filter>
</receiver>
And asking for Device Admin permission
private void askAdminPerm(){
Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN,
new ComponentName(root.getContext(), DeviceAdmin.class));
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, getString(R.string.lock_msg_big));
startActivity(intent);
}
For my application, I need to know that the screen is locked. How to check this is problematically. I used following flag:
if(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON != 0){
// some code
}else if((WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED)!= 0){
// some code
}
But this always executing both if and else part... which flag I have to use to check the screen is locked or not?
I'll try to answer this though the question is already old since it is unresolved and could help other googlers. ;)
First you must register a BroadcastReceiver for Intent.ACTION_SCREEN_OFF & Intent.ACTION_SCREEN_ON. Note that this receiver must be registered in codes and will not work when declared in the manifest.
In your broadcast receiver, when you receive Intent.ACTION_SCREEN_ON, you can check if the screen is locked by using the below codes:
KeyguardManager km = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
boolean locked = km.inKeyguardRestrictedInputMode();
KeyguardManager myKeyManager = (KeyguardManager)getSystemService(Context.KEYGUARD_SERVICE);
if( myKeyManager.inKeyguardRestrictedInputMode()) {
//screen is locked
} else {
//screen is not locked
}
Register a broadcast receiver with action android.intent.action.ACTION_SCREEN_OFF and write your code in onReceive() method of receiver.
If you are using an activity, onPause() will be called when the screen locked and onResume() will be called when the screen unlocked.
In your code you are checking some flags, i don't know where you will do that checking ? is it continuous verification ? If you are using an activity in your app, the above procedure will happen, just check it in Android Developers website.
I guess you may have already found the answer, but if not (and for other developers), you can do it like this:
PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
boolean isScreenOn = powerManager.isScreenOn();
if (!isScreenOn) {
//Screen is in OFF State
//Code to power on and release lock
KeyguardManager km = (KeyguardManager) this
.getSystemService(Context.KEYGUARD_SERVICE);
final KeyguardManager.KeyguardLock kl = km
.newKeyguardLock("MyKeyguardLock");
kl.disableKeyguard();
PowerManager pm = (PowerManager) this
.getSystemService(Context.POWER_SERVICE);
WakeLock wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK
| PowerManager.ACQUIRE_CAUSES_WAKEUP
| PowerManager.ON_AFTER_RELEASE, "MyWakeLock");
wakeLock.acquire();
}
There are broadcasted intents for screen lock & unlock.
Check it like :
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)){//LOGIC Here}
Let me know!
Here is what I did:
This handles if the user has unlocked the screen, but not yet entered the home screen or the user's screen is turned off say during a call.
if (Intent.ACTION_SCREEN_ON.equals(pIntent.getAction()) ||
Intent.ACTION_USER_PRESENT.equals(pIntent.getAction())) {
if(mListener!=null) {
KeyguardManager km = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
boolean locked = km.inKeyguardRestrictedInputMode();
Log.v(TAG, ": Phone lock state from KEYGUARD_SERVICE: Current state:" + (locked ? "LOCKED":"UNLOCKED"));
mIsPhoneLocked = locked;
}
}
I have a service which polls a server at certain intervals. I use an AlarmManager and a BroadcastReceiver to start the service. My problem is that after a certain duration, even though the Wifi is still enabled, but for some reason, my application can't contact the server. I get an "Unreachable network" error.
Note that I've already acquired a partial wake lock as well as a wifilock.
Here's my code for the BroadcastReceiver.
public class ServiceAlarmBroadcastReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
WakeLock wakeLock = null;
WifiLock wifiLock = null;
try {
PowerManager pm = (PowerManager) context
.getSystemService(Context.POWER_SERVICE);
// acquire a WakeLock to keep the CPU running
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"MyWakeLock");
if(!wakeLock.isHeld()){
wakeLock.acquire();
}
Log.i("ServiceAlarmBroadcastReceiver", "WakeLock acquired!");
WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
wifiLock = wm.createWifiLock(WifiManager.WIFI_MODE_FULL , "MyWifiLock");
if(!wifiLock.isHeld()){
wifiLock.acquire();
}
Log.i("ServiceAlarmBroadcastReceiver", "WifiLock acquired!");
context.startService(new Intent(context, ThePollerService.class));
} finally {
// release the WakeLock to allow CPU to sleep
if (wakeLock != null) {
if (wakeLock.isHeld()) {
wakeLock.release();
Log.i("ServiceAlarmBroadcastReceiver", "WakeLock released!");
}
}
// release the WifiLock
if (wifiLock != null) {
if (wifiLock.isHeld()) {
wifiLock.release();
Log.i("ServiceAlarmBroadcastReceiver", "WiFi Lock released!");
}
}
}
}
}
The problem with the code posted here is that you acquire and release the WakeLock and WifiLock from right inside of your receiver. Unless you are completing your entire task inside of the onStart of your service (which if you are, why even bother having a service???), the locks will be released before your polling task completes.
I would suggest changing your implementation to something like the following:
Have broadcast receiver start service (and that is all)
Have service acquire wake locks and kick off the thread to do your polling operation. The most appropriate spot would be your service onCreate)
After your polled operation is complete, you should stop your polling service
In the onDestroy of your service, you should release the locks you acquired in onStart
Thanks to Tom, I was able to resolve this issue. Here's the code:
Settings.System.putInt(getContentResolver(),
Settings.System.WIFI_SLEEP_POLICY,
Settings.System.WIFI_SLEEP_POLICY_NEVER);
Under the WiFi Settings, Menu Key, Advanced Options theirs the WIFI_SLEEP_POLICY option list which when set to never will keep the WiFi connection open while the phone is asleep.
You can manipulate this under Settings.System Package.
http://developer.android.com/reference/android/provider/Settings.System.html#WIFI_SLEEP_POLICY
Hope this helps,
Tom
A little edit to javauser's answer:
private void setNeverSleepPolicy() {
try {
ContentResolver cr = getContentResolver();
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.JELLY_BEAN) {
int set = android.provider.Settings.System.WIFI_SLEEP_POLICY_NEVER;
android.provider.Settings.System.putInt(cr, android.provider.Settings.System.WIFI_SLEEP_POLICY, set);
} else {
int set = android.provider.Settings.Global.WIFI_SLEEP_POLICY_NEVER;
android.provider.Settings.System.putInt(cr, android.provider.Settings.Global.WIFI_SLEEP_POLICY, set);
}
} catch (Exception e) {
e.printStackTrace();
}
}