首页 > 解决方案 > 每当应用程序打开时重新启动 AlarmManager

问题描述

我正在后台服务上调用此警报管理器。它正在特定时间工作,例如如果我将其设置为在 11:44 触发,它将触发但问题是每当我打开应用程序时,警报管理器就会再次开始执行该功能。

public class BackgroundService extends Service {

private static final String TAG = "BackgroundService";
public BackgroundService() {
}

@Override
public IBinder onBind(Intent intent) {
    // TODO: Return the communication channel to the service.
    throw new UnsupportedOperationException("Not yet implemented");
}



@Override
public int onStartCommand(Intent intent, int flags, int startId) {

   // siteInAutomate();

    Log.e(TAG, "Background Activity");

    AlarmManager alarmMgr1 = 
   (AlarmManager)getSystemService(Context.ALARM_SERVICE);

    Intent intent1 = new Intent(this,schedule1.class);
    PendingIntent pendingIntent1 = PendingIntent.getBroadcast(this, 
    0,intent1, 0);

    // Intent intent0 = new Intent(this, OldEntryRemover.class);
    Log.e(TAG, "SiteOutCalled");
    Calendar calendar1 = Calendar.getInstance();
    calendar1.setTimeInMillis(System.currentTimeMillis());
    calendar1.set(Calendar.HOUR_OF_DAY,10 );
    calendar1.set(Calendar.MINUTE, 52);
    calendar1.set(Calendar.SECOND, 0);

    //set that timer as a RTC Wakeup to alarm manager object
    alarmMgr1.set(AlarmManager.RTC_WAKEUP, calendar1.getTimeInMillis(), 
    pendingIntent1);

    return super.onStartCommand(intent, flags, startId);
    }

标签: javaandroidalarmmanager

解决方案


在这里,您已将闹钟设置为 10:52。因此,如果您在那之后打开应用程序,它会立即重新创建并触发 AlarmManager。

如果规定的触发时间是过去的,将立即触发警报

您可以查看当前时间。如果超过预定时间,则在Calendar(此处为日历 1)的实例中,添加一天

calendar1.add(Calendar.DATE,1)

推荐阅读