好的,它是这样的; DeviceListActivity启动警报。然后,AlarmReceiver创建一个称为AlarmActivity的活动,以执行一些工作并停止警报并自行终止。但是我无法停止警报。我的代码如下。
DeviceListActivity:
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);
}
AlarmReceiver:
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);
}
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();
}
答案 0 :(得分:0)
在“警报活动”中,尝试以下代码:
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();
}