警报不会停止响起 - 取消按钮不起作用

Alarm would not stop ringing - cancel button not working

即使我按下了停止警报按钮,我仍然无法阻止闹钟响起。谢谢

这是我在MainActivity中的启动闹钟开关javaclass.

public void switchClicked (View view) {
        if (((Switch) view).isChecked()) {
            Log.d("MainActivity", "Alarm On");
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.HOUR_OF_DAY, alarmTimePicker.getHour());
            calendar.set(Calendar.MINUTE, alarmTimePicker.getMinute());
            Intent myIntent = new Intent(MainActivity.this, AlarmReceiver.class);
            pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent, 0);
            alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
            setAlarmText("ON");
        } else {
            alarmManager.cancel(pendingIntent);
            setAlarmText("OFF");
            Log.d("MainActivity", "Alarm Off");
        }
    }
    public void setAlarmText(String alarmText) {
        alarmTextView.setText(alarmText);
    }

这是我在 MainActivity 中的 StopAlarm 按钮 java class。

public void stopAlarm(View view) {
        setAlarmText("Alarm stopped");
        Intent myIntent = new Intent(MainActivity.this, AlarmReceiver.class);
        pendingIntent = PendingIntent.getService(MainActivity.this, 0, myIntent, 0);
        alarmManager.cancel(pendingIntent);



            }

这是 AlarmReciver java class。

public class AlarmReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(final Context context, Intent intent) {

        MainActivity inst = MainActivity.instance();
        inst.setAlarmText("Alarm! Wake up! Wake up!");
        Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
        if (alarmUri == null) {
            alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        }
        Ringtone ringtone = RingtoneManager.getRingtone(context, alarmUri);
        ringtone.play();
    }
}

stopAlarm 方法应该用 PendingIntent.FLAG_UPDATE_CURRENT 创建 PendingIntent 来覆盖以前的 Intent,你试过这个吗?

pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);