i am a beginner with studying android, and really enjoy this book.
today i find a strange thing, when we use Alarm Manager to call poll Service periodically, if we kill the app( i swipe it on the overview screen), i find the poll service’s “onHandleIntent” method can’t callback anymore(no log information for test). when i start the photo gallery app again, i find Alarm Manager can recall the poll service’s “onHandleIntent” method again( because the log information comes again)。this phenomenon tells me the Alarm Manager is ok, but poll service can’t be callback when the app is killed.
but when i change to receiver, it works well. it will be very thankful if you can tell me the reason.
Thanks a lot.
below is my code
public static void setServiceAlarm(Context context, boolean isOn) {
// Intent intent = new Intent(context, MyReceiver.class);
// PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
Intent intent = newIntent(context, DETECT_NEW, “test”);
PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
if (isOn) {
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(), POLL_INTERVAL_MS, pendingIntent);
} else {
alarmManager.cancel(pendingIntent);
pendingIntent.cancel();
}
QueryPreferences.setIsAlarmed(context,isOn);
}
public static boolean isAlarmOn(Context context) {
// Intent intent = new Intent(context, MyReceiver.class);
// PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_NO_CREATE);
Intent intent = newIntent(context, DETECT_NEW, "test");
// 没有匹配的pendingintent,说明alarm没有创建。因为setServiceAlarm把alarm和pendingintent绑定了
PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_NO_CREATE);
return pendingIntent != null;
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
Log.i("TAG", "onHandleIntent1111: ");
}