警报不会在不杀死应用程序的情况下停止响铃

时间:2016-06-29 09:46:22

标签: android broadcastreceiver alarmmanager alarm

我正在尝试为我正在处理的应用添加闹钟,但出于某些愚蠢的原因,一旦闹铃响起,我无法在不杀死应用的情况下将其关闭。< / p>

警报由ToggleButton激活。如果它打开,闹钟将在预定的时间响铃,当它关闭时,它不会...或至少,它不应该。

这里是ToggleButton的OnClick代码:

@OnClick(R.id.alarmToggle2)
protected void onAlarmToggleClicked(){
    if(alarmToggle.isChecked()){
        alarmTimeText.setTextColor(Color.GREEN);
        alarmTimeText.setVisibility(View.VISIBLE);
        //Switch on the alarm
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(Calendar.HOUR_OF_DAY, alarmHour);
        calendar.set(Calendar.MINUTE, alarmMinute);

        //It's now time to set off the alarm
        Log.d(TAG, "ALARM");
        alarmReceiverIntent = new Intent(RemindersActivity.instance(),
                AlarmReceiver.class);
        broadcastIntent = PendingIntent.getBroadcast(getContext(), alarmId,
                alarmReceiverIntent, 0);
        //RTC means that the alarm won't be used if the device is asleep, RTC_WAKEUP means
        //that it will.
        alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), broadcastIntent);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
                AlarmManager.INTERVAL_DAY, broadcastIntent);
    } else {
        Log.d(TAG, "Cancel alarm");
        alarmTimeText.setVisibility(View.INVISIBLE);
        alarmManager.cancel(broadcastIntent);
        alarmText.setText("");
    }
}

这里是AlarmReceiver类的onReceive()方法的代码:

    public void onReceive(Context context, Intent intent) {
        //this will update the UI with message
        RemindersActivity inst = RemindersActivity.instance();
        //Sets the content of AlarmText in RemindersFragment
        inst.setAlarmText("Alarm! Wake up! Wake up!");

        //this will sound the alarm tone
        //this will sound the alarm once, if you wish to
        //raise alarm in loop continuously then use MediaPlayer and setLooping(true)
        Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
        if (alarmUri == null) {
            alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        }
        Ringtone ringtone = RingtoneManager.getRingtone(context, alarmUri);
        ringtone.play();

        ComponentName comp = new ComponentName(context.getPackageName(),
            AlarmService.class.getName());
        startWakefulService(context, (intent.setComponent(comp)));
        setResultCode(Activity.RESULT_OK);
    }

1 个答案:

答案 0 :(得分:0)

我已经提出了一个解决方案:铃声现在是AlarmReceiver的静态变量,这就是我停止闹钟铃声的方式:

if(!alarmToggle.isChecked()) {
    //Stop the alarm from ringing
    if(AlarmReceiver.ringtone.isPlaying())
        AlarmReceiver.ringtone.stop();
    alarmTimeText.setVisibility(View.INVISIBLE);
    alarmManager.cancel(broadcastIntent);
    alarmText.setText("");
}