1

我想制作一个 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");
}   
}
4

1 回答 1

0

You'll want to use the setRepeating function that's part of the AlarmManager class:

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);

where PERIOD is the interval between alarm instances. For more information see this question.

于 2012-12-02T18:07:37.960 回答