从广播接收器获取唤醒锁时出现问题
我有一个问题。我正在尝试让广播接收器获取唤醒锁,以便我的闹钟将手机从睡眠模式唤醒。
在下面的广播接收器中,当 AlarmReceiver 调用“AlarmAlertWakeLock”类时,程序崩溃,并在“sCpuWakeLock.acquire();”行上出现“找不到源”。 知道发生了什么事吗?有更好的方法来做我想做的事情吗?
在一个文件中:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, Intent intent) {
AlarmAlertWakeLock.acquireCpuWakeLock(context);
}
}
在单独的文件中:
import android.content.Context;
import android.os.PowerManager;
public class AlarmAlertWakeLock {
private static PowerManager.WakeLock sCpuWakeLock;
static void acquireCpuWakeLock(Context context) {
if (sCpuWakeLock != null) {
return;
}
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
sCpuWakeLock = pm.newWakeLock(
PowerManager.PARTIAL_WAKE_LOCK |
PowerManager.ACQUIRE_CAUSES_WAKEUP,"okTag");
sCpuWakeLock.acquire();
}
static void releaseCpuLock() {
if (sCpuWakeLock != null) {
sCpuWakeLock.release();
sCpuWakeLock = null;
}
}
}
I have a problem. I am trying to make a broadcast receiver acquire a wake lock so my alarm will wake the phone from sleep mode.
In the broadcast receiver below, the program crashes with "source not found" on line "sCpuWakeLock.acquire(); when the class "AlarmAlertWakeLock" is called by AlarmReceiver.
Any idea what's going on? Is there a better way to do what I'm trying to do?
In one file:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, Intent intent) {
AlarmAlertWakeLock.acquireCpuWakeLock(context);
}
}
In a separate file:
import android.content.Context;
import android.os.PowerManager;
public class AlarmAlertWakeLock {
private static PowerManager.WakeLock sCpuWakeLock;
static void acquireCpuWakeLock(Context context) {
if (sCpuWakeLock != null) {
return;
}
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
sCpuWakeLock = pm.newWakeLock(
PowerManager.PARTIAL_WAKE_LOCK |
PowerManager.ACQUIRE_CAUSES_WAKEUP,"okTag");
sCpuWakeLock.acquire();
}
static void releaseCpuLock() {
if (sCpuWakeLock != null) {
sCpuWakeLock.release();
sCpuWakeLock = null;
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
没关系,我想通了 - 我需要在清单中添加唤醒锁权限:
uses-permission android:name="android.permission.WAKE_LOCK"
现在工作正常!
Never mind, I figured it out - I needed to add wake lock permission to the manifest:
uses-permission android:name="android.permission.WAKE_LOCK"
Works fine now!