我正在尝试在Android中安排重复闹钟。第一个警报工作正常,但第二个警报从未被解雇。我知道我的错误在于服务类。我试图在Wakeful接收器中重新安排它并且工作正常,但我需要在服务停止之前完成它。
// Alarm fired from the activity and works!
private void startPingRepeatingAlarm() {
Intent intent = new Intent(this, PingReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
Log.i("Ping WakefulReceiver", "Starting alarm @ " + new Date().toString());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
am.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 1000, pendingIntent);
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
am.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 1000, pendingIntent);
} else {
am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 1000, pendingIntent);
}
}
}
接收者:
public class enter code herePingReceiver extends WakefulBroadcastReceiver {
public PingReceiver() {
}
@Oventer code hereerride
public void onReceive(Context context, Intent intent) {
Log.i("Ping WakefulReceiver", "Received alarm intent @ " + new Date().toString());
startWakefulService(context,new Intent(context, PingService1.class));
}
}
服务内码:
@Override
public int onStartCommand(final Intent intent, int flags, int startId) {
final Intent in = intent;
new AsyncTask<Void,Void,Void>(){
@Override
protected Void doInBackground(Void... params) {
Log.i("Ping WakefulReceiver", "Rescheduling alarm @ " + new Date().toString());
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(getBaseContext(), PingService1.class);
pendingIntent = PendingIntent.getBroadcast(getBaseContext(), 0, intent, 0);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
alarmMgr.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 1000, pendingIntent);
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
alarmMgr.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 1000, pendingIntent);
} else {
alarmMgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 1000, pendingIntent);
}
}
PingReceiver.completeWakefulIntent(in);
stopSelf();
}
}.execute();
return START_STICKY;
}
有什么想法吗?