我正在研究一款必须以指定间隔重复执行任务的应用程序。如果需要,我希望它可以唤醒设备。但是不知道为什么,WakefulBroadcastReceiver 永远不会执行其通过 AlarmManager 触发的 onReceive 方法。即使使用普通的 BroadcastReceiver 也无法解决该问题。我正在使用 Lollipop 5.0.1 Nexus5,时间间隔为 5-20 秒。
以下是代码:
class mypackage.MainActivity
[...]
private void startRepeatingAlarm(){
this.wbr = new SimpleWakefulBroadcastReceiver();
this.registerReceiver(wbr, new IntentFilter("mypackage.FOO_ACTION"));
Intent i = new Intent("mypackage.FOO_ACTION");
i.setClass(this, SimpleWakefulBroadcastReceiver.class);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 1234, i, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
manager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), timeInterval, pendingIntent);
Toast.makeText(this, "Alarm set", Toast.LENGTH_SHORT).show();
}
class mypackage.SimpleWakefulBroadcastReceiver
public class SimpleWakefulBroadcastReceiver extends WakefulBroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
// This method gets NEVER called
Intent service = new Intent(context, SimpleWakefulService.class);
startWakefulService(context, service);
}}
AlarmManager
触发接收器(而AlarmManager
是外部组件),因此需要在清单中声明接收器。 - David Wasser