java - 每当应用程序打开时重新启动 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);
}
解决方案
在这里,您已将闹钟设置为 10:52。因此,如果您在那之后打开应用程序,它会立即重新创建并触发 AlarmManager。
如果规定的触发时间是过去的,将立即触发警报
您可以查看当前时间。如果超过预定时间,则在Calendar
(此处为日历 1)的实例中,添加一天
calendar1.add(Calendar.DATE,1)
推荐阅读
- smartcard - 读取德国 EC 卡的 IBAN/BIC 时出现问题
- php - 对多颗星使用 preg_match (*)
- c - SO_SNDTIMEO 和 SO_RCVTIMEO 的意外行为
- c++ - 我正在尝试理解这两个代码块,有人可以帮忙吗?
- serverless - 关于 Azure Synapse Analytics 无服务器池连接和查询的 ADLS 的访问控制问题
- django - 在 Django 中批准付款后从 Paypal 脚本提交表单
- spring-boot - spring cloud stream kafka binder enableDlq 没有按我预期的那样工作
- swift - 只允许某些应用程序使用我的 VPN - Swift
- python - 如何使用 django 在网络浏览器上推送通知
- python - 统计模型列联表nd数组2 x 2 xk,无法重塑