我想创建一个AlarmManager,它在屏幕被唤醒并解锁时启动,并在何时停止。每次解锁后,应重置Timer。这段代码工作正常,但只有一次。我可以取消它然后重新启动它,但是一旦闹钟管理器倒计时它就不会再次重启。
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");
}
}
答案 0 :(得分:0)
您需要使用属于setRepeating
类的AlarmManager
函数:
AlarmManager mgr=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i=new Intent(context, OnAlarmReceiver.class);
PendingIntent pi=PendingIntent.getBroadcast(context, 0, i, 0);
mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), PERIOD, pi);
其中PERIOD
是警报实例之间的间隔。有关详细信息,请参阅this问题。