我正在尝试使用AlarmManager每10分钟唤醒一次我的服务以完成一些工作。我创建了一个BroadcastReceiver,重复警报并注册它(我服务中的所有三个)。但我没有收到广播。
public class MainService extends Service implements ... {
public static final String BROADCAST_ALARM = "broadcast_alarm";
//60 seconds
private final int activityCheckingTimeIntervalInMilisec = 60*1000;
AlarmManager alarmManager;
private final BroadcastReceiver alarmReceiver = new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "NEW ALARM");
}
};
...
@Override
public void onCreate() {
super.onCreate();
PendingIntent alarmIntent = PendingIntent.getBroadcast(this,0, new Intent(BROADCAST_ALARM),PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime()+100, activityCheckingTimeIntervalInMilisec, alarmIntent);
LocalBroadcastManager.getInstance(getBaseContext()).registerReceiver(alarmReceiver, new IntentFilter(BROADCAST_ALARM));
//if I comment out the line below, the alarmReceiver receives the brodcast and prints "NEW ALARM"
//LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(BROADCAST_ALARM));
...
}
}
如果我发送广播:
LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(BROADCAST_ALARM));
(参见代码中的注释)日志打印“NEW ALARM”(仅一次)。所以代码的BroadcastReceiver部分似乎有效。
我还试图获取所有警报的转储,以查看alarmManager是否与
配合使用adb shell dumpsys alarm > dump.txt.
dump.txt(相关行):
Current Alarm Manager state:
nowRTC=1526118229704=2018-05-12 09:43:49 nowELAPSED=+2h25m50s271ms
Next non-wakeup alarm: +10s296ms = 2018-05-12 09:44:00
Next wakeup: +59s73ms = 2018-05-12 09:44:48
Num time change events: 0
Pending alarm batches: 17
...
Batch{23bf2d95 num=1 start=8809344 end=-8854344}:
ELAPSED_WAKEUP #0: Alarm{e87feaa type 2 when 8809344 com.example.example.example}
tag=*walarm*:broadcast_alarm
type=2 whenElapsed=+59s73ms when=+59s73ms
window=-1 repeatInterval=60000 count=0
operation=PendingIntent{1681173c: PendingIntentRecord{36219342 com.example.example.example broadcastIntent}}
com.google.android.finsky.services.DailyHygiene
u0a63:com.jx.shealth +2s308ms running, 4 wakeups:
+2s308ms 4 wakes 4 alarms: *walarm*:com.jx.shealth.action.CHECK_TARGET
u0a72:com.example.example.example +131ms running, 24 wakeups:
+131ms 24 wakes 24 alarms: *walarm*:broadcast_alarm
我也尝试使用它代替getBaseContext()。