即使按下停止按钮也无法使闹钟响起

时间:2019-03-07 19:11:27

标签: java android android-intent alarmmanager android-alarms

即使按了stopAlarm按钮,也无法阻止警报响起。谢谢您的帮助。

这是MainActivity java类中的启动警报开关。

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 java类中的StopAlarm按钮。

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

这是AlarmReciver Java类。

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();
    }
}

1 个答案:

答案 0 :(得分:0)

问题出在这行

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

您使用的是getService(),但是您应该使用getBroadcast()

为什么?

getService()检索将启动服务的PendingIntent,但是由于使用的是BroadcastReceiver,因此应使用getBroadcast()检索将执行广播的PendingIntent。