如何停止闹铃

时间:2019-06-21 15:12:11

标签: java

这是一个闹钟应用程序。 当警报声响起时,我无法停止。我要单击按钮停止铃声。

我使用的代码如下:

MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    alarmTimePicker = (TimePicker) findViewById(R.id.timePicker);
    alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);


}

public void OnToggleClicked(View view)
{
    long time;
    if (((ToggleButton) view).isChecked())
    {
        Toast.makeText(MainActivity.this, "ALARM ON", Toast.LENGTH_SHORT).show();
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, alarmTimePicker.getCurrentHour());
        calendar.set(Calendar.MINUTE, alarmTimePicker.getCurrentMinute());
        Intent intent = new Intent(this, AlarmReceiver.class);
        pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);

        time=(calendar.getTimeInMillis()-(calendar.getTimeInMillis()%60000));
        if(System.currentTimeMillis()>time)
        {
            if (calendar.AM_PM == 0)
                time = time + (1000*60*60*12);
            else
                time = time + (1000*60*60*24);
        }
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, time, 10000, pendingIntent);
    }
    else
    {
        alarmManager.cancel(pendingIntent);
        Toast.makeText(MainActivity.this, "ALARM OFF", Toast.LENGTH_SHORT).show();
    }

AlarmReceiver.java

public class AlarmReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        Toast.makeText(context, "Alarm! Wake up! Wake up!", Toast.LENGTH_LONG).show();
        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 :(得分:1)

RingtoneManager.stopPreviousRingtone()

甚至更好。存储原始铃声并呼叫stop

Ringtone ringtone = RingtoneManager.getRingtone(getActivity());
ringtone.play();
...
ringtone.stop();