我有一个警报管理器启动服务的代码。我必须使用第二个闹钟在指定时间取消它。我看过的解决方案没有一个有效。我的代码如下:
void startAtInterval(int fromTime, int fromTimeMinute, int toTime, int toTimeMinute, int id1, int id2) {
// start alarm
AlarmManager alarmMgr = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
PendingIntent alarmIntent = PendingIntent.getService(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, fromTime);
calendar.set(Calendar.MINUTE, fromTimeMinute);
alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, alarmIntent);
// stop alarm
AlarmManager alarmMgr1 = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
PendingIntent alarmIntent1 = PendingIntent.getService(getApplicationContext(), 1, intent, PendingIntent.FLAG_CANCEL_CURRENT);
Calendar calendar1 = Calendar.getInstance();
calendar1.setTimeInMillis(System.currentTimeMillis());
calendar1.set(Calendar.HOUR_OF_DAY, toTime);
calendar1.set(Calendar.MINUTE, toTimeMinute);
alarmMgr1.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar1.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, alarmIntent1);
stopService(intent);
alarmMgr1.cancel(alarmIntent1);
}
我使用了FLAG_UPDATE_CURRENT
和FLAG_CANCEL_CURRENT
。我还尝试停止服务,如我在代码中所示。我正在配置屏幕上打发时间。我知道它有效,因为第一个警报总是被触发。
最佳答案
您应该让第二个警报取消服务,并触发 BroadcastReceiver
,然后停止服务。这将确保警报在任何情况下(例如应用程序被关闭)都能成功停止服务。
AlarmManager alarmMgr1 = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
Intent intentCancelService= new Intent(getApplicationContext(), StopServiceReceiver.class);
PendingIntent alarmIntent1 = PendingIntent.getBroadcast(getApplicationContext(), StopServiceReceiver.REQUEST_CODE, intentCancelService, PendingIntent.GoTestAlarmReceiver);
Calendar calendar1 = Calendar.getInstance();
calendar1.setTimeInMillis(System.currentTimeMillis());
calendar1.set(Calendar.HOUR_OF_DAY, toTime);
calendar1.set(Calendar.MINUTE, toTimeMinute);
alarmMgr1.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar1.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, alarmIntent1);
然后制作您的BroadcastReceiver
:
public class GoTestAlarmReceiver extends BroadcastReceiver {
public static final int REQUEST_CODE = 123123; //whatever code just unique
@Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, YourServiceClassHere.class);
context.stopService(i);
}
}
确保在 list 中声明接收者:
<receiver
android:name=".StopServiceReceiver"
android:enabled="true"
android:process=":remote" />
关于java - 无法在 Android 中使用 AlarmManager 停止服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41560715/