我想制作一个 AlarmManager,它在屏幕被唤醒并解锁并停止时启动,当 . 每次解锁后,应重置计时器。此代码工作正常,但只有一次。我可以取消它然后重新启动它,但是一旦警报管理器倒计时,它就不会再次重新启动。
public class OnOffReceiver extends Service {
PendingIntent pendingIntent;
AlarmManager alarmManager;
Intent myIntent = null;
Calendar calendar;
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.v("", "Receiver service starts now");
StartAlarmManager();
registerReceiver(new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
Log.v("", intent.getAction());
pendingIntent = PendingIntent.getService(OnOffReceiver.this, 0, myIntent, 0);
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
}
}, new IntentFilter(Intent.ACTION_SCREEN_OFF));
registerReceiver(new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
Log.v("", intent.getAction());
StartAlarmManager();
}
}, new IntentFilter(Intent.ACTION_USER_PRESENT));
return START_STICKY;
}
final void StartAlarmManager() {
try {
myIntent = new Intent(OnOffReceiver.this, SoundService.class);
Looper.prepare();
} catch (Exception e) {
}
Log.v("", "Trying to start AlarmManager");
pendingIntent = PendingIntent.getService(OnOffReceiver.this, 0, myIntent, 0);
alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 10);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.v("", "Receiver service successfully ended");
}
}