好的,它是这样的;设备列表活动启动警报。然后,AlarmReceiver 创建一个称为 AlarmActivity 的活动来执行一些工作并停止警报并自行终止。但我无法阻止警报。我的代码如下。
设备列表活动:
public void startAlarm(View view) {
Calendar calNow = Calendar.getInstance();
calNow.set(Calendar.SECOND, calNow.get(Calendar.SECOND) + 1);
Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, calNow.getTimeInMillis(), pendingIntent);
}
报警接收器:
public void onReceive(Context context, Intent intent) {
Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
if (alarmUri == null) {
alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
}
Ringtone ringtone = RingtoneManager.getRingtone(context, alarmUri);
ringtone.play();
Intent alarmActivity = new Intent();
alarmActivity.setClassName(context.getPackageName(),AlarmActivity.class.getName());
alarmActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(alarmActivity);
}
警报活动:
public void stopAlarm(View view) {
Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
finish();
}
在警报活动中,尝试以下代码:
public void stopAlarm(View view) {
Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), 1, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
// add this if condition to check and cancel the alarm if AlarmManager is not null
if (alarmManager!= null) {
alarmManager.cancel(pendingIntent);
finish();
}