我正在使用闹钟管理器在特定时间触发广播。但是在多次测试后,我发现有时广播接收较晚。有时候是5秒,10秒,15秒甚至更久。特别是当设备被锁定时。我已经进行了各种实验。这里是我最不问题的代码。
即使使用唤醒锁,我也不知道我缺少什么。
触发意图
Intent intent = new Intent(this.getApplicationContext(), BroadCastReceiver.class);
//..... some extras
PendingIntent pi = PendingIntent.getBroadcast(getApplicationContext(), code, intent, 0);
manager.setRepeating(AlarmManager.RTC_WAKEUP, time, 1000 * 120 , pi);
Receiving broadcast
public void onReceive(Context context, Intent intent)
{
WakeLocker.acquire(context);
.......
Intent alarm = new Intent(context, xyz.class);
alarm.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(alarm);
}
在xyz活动的destroy()中释放Wakelock。
自定义WakeLocker类 public abstract class WakeLocker {
private static PowerManager.WakeLock wakeLock;
public static void acquire(Context ctx) {
if (wakeLock != null) wakeLock.release();
PowerManager pm = (PowerManager) ctx.getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK |
PowerManager.ACQUIRE_CAUSES_WAKEUP |
PowerManager.ON_AFTER_RELEASE, "haris");
wakeLock.acquire();
}
public static void release() {
if (wakeLock != null) wakeLock.release(); wakeLock = null;
}
}