2

我的应用程序中有两个活动。第一个活动获取一个唤醒锁,即使该活动被销毁,该唤醒锁仍然存在。此活动还设置了一个警报,该警报将启动第二个活动。我希望第二个活动释放第一个活动获得的唤醒锁。

所以基本上:

第一个活动获得唤醒锁>>第一个活动被销毁>>唤醒锁仍然获得>> canender(警报)打开一个新活动(第二个活动)>>第二个活动释放唤醒锁??

问题是如何在与获取唤醒锁的位置不同的活动中释放唤醒锁?

这是我在第一个活动中用于获取唤醒锁的代码:

    WakeLock wl;
    PowerManager pM = (PowerManager)getSystemService(Context.POWER_SERVICE);
    wl = pM.newWakeLock(PowerManager.FULL_WAKE_LOCK, "wakeLock");
   wl.acquire();

有什么代码可以用来在第二个活动中释放唤醒锁吗?

4

2 回答 2

11

将唤醒锁存储在两个活动都可以访问的静态变量中。像这样:

class Globals {
    public static WakeLock wakelock;
}

在您的第一个活动中:

PowerManager pM = (PowerManager)getSystemService(Context.POWER_SERVICE);
WakeLock wl = pM.newWakeLock(PowerManager.FULL_WAKE_LOCK, "wakeLock");
wl.acquire();
Globals.wakelock = wl; // Save in a place where it won't go

  // 当这个 Activity 完成时离开

在您的第二个活动中:

if (Globals.wakelock != null) {
    Globals.wakelock.release();
    Globals.wakelock = null; // We don't have a wake lock any more
}
于 2012-06-30T14:55:54.887 回答
1
public class WakeLockManager extends BroadcastReceiver {

    private static WakeLock mWakeLock;
    private String LCLT;

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Consts.WAKELOCK_INTENT)) {
            Log.v("wakelock", "GOT THE wakelock INTENT");
            boolean on = intent.getExtras().getBoolean("on");
            if (mWakeLock == null) {
                PowerManager pm = (PowerManager) context
                        .getSystemService(Context.POWER_SERVICE);
                mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                        "Breeze WakeLock");
            }
            if (on) {
                if (!mWakeLock.isHeld()) {
                    mWakeLock.acquire();
                    Log.v("wakelock", "acquiring wakelock");
                }
            } else {
                if (mWakeLock.isHeld()) {
                    Log.v("wakelock", "releasing wakelock");
                    mWakeLock.release();
                }
                mWakeLock = null;
            }
        }
    }
}

look at the above code ..put it in a separate class file and and in your manifest define it for some custom intent .... now this class will respond to a custom intent ...just broadcast that intent and you can turn the wakelock on or off in your entire app since the wakelock is static..like this :

public static void setWakeup(boolean status) {
    Intent wakelock_Intent = new Intent(CUSTOM_INTENT);
    wakelock_Intent.putExtra("on", status);
    getActivityReference().sendBroadcast(wakelock_Intent);
}

the above would be defined in a service ..
then we can call this method from anywhere since its static to alter the cpu wakelock

于 2012-08-10T13:11:07.297 回答