问题
I have a problem with acquiring a WakeLock. It seems not to work. I am trying to acquire a FULL_WAKE_LOCK but neither the display gets enabled nor is my app able to perform tasks.
I am using the following permission: android.permission.WAKE_LOCK
My acquire code looks like this:
PowerManager pm = (PowerManager) getBaseContext().getSystemService(Context.POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK|PowerManager.ACQUIRE_CAUSES_WAKEUP, "My Tag");
wl.acquire();
What am i doing wrong?
Edit: Added another flag ACQUIRE_CAUSES_WAKEUP ... but no changes in behavior
Edit2: All i am trying to do is, to play music and to wake my device up upon a certain event. The music is working perfectrly but the device stays black.
回答1:
WakeLock is an Inefficient way of keeping the screen on. Instead use the WindowManager to do the magic. The following one line will suffice the WakeLock. The WakeLock Permission is also needed for this to work. Also this code is efficient than the wakeLock.
getWindow().addFlags(LayoutParams.FLAG_KEEP_SCREEN_ON);
You need not relase the WakeLock Manually. This code will allow the Android System to handle the Lock Automatically. When your application is in the Foreground then WakeLock is held and else android System releases the Lock automatically.
But if you do want to release the flag, you can do it with:
getWindow().clearFlags(LayoutParams.FLAG_KEEP_SCREEN_ON);
回答2:
private static PowerManager.WakeLock lockStatic = null;
private static String LOCK_NAME_STATIC = "MyWakeLock";
public static void acquireStaticLock(Context context) {
getLock(context).acquire();
}
synchronized private static PowerManager.WakeLock getLock(Context context) {
if (lockStatic == null) {
PowerManager mgr = (PowerManager) context
.getSystemService(Context.POWER_SERVICE);
lockStatic = mgr.newWakeLock(PowerManager.FULL_WAKE_LOCK,
LOCK_NAME_STATIC);
lockStatic.setReferenceCounted(true);
}
return (lockStatic);
}
Usage:
Call acquireStaticLock()
when you need to acuire the lock
Call getLock(this).release();
inside activity when you need to release the lock
Also add permission in minifest file:
<uses-permission android:name="android.permission.WAKE_LOCK" />
回答3:
Where are you acquiring the wake lock? You will need to acquire it in the receiver of the intent, not in the service/activity that your intent starts.
来源:https://stackoverflow.com/questions/3615405/android-wakelock