如何在android studio中实用地停止报警音

时间:2017-10-08 04:01:04

标签: java android

我的闹钟代码工作正常,因为默认铃声按时播放效果很好。但是无法停止警报音。在接收器类中,我插入了以下代码。

try {
        Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
        Ringtone r = RingtoneManager.getRingtone(context, notification);
        r.play();
    } catch (Exception e) {
        e.printStackTrace();
    }

我还在主类中插入了取消闹钟的代码,这也适用于代码

alarmMgr.cancel(pendingIntent);

但是一旦默认铃声开始播放并且用户希望通过停止按钮停止播放,那么它就无法正常工作。 在使用stopbutton.setOnClickListener的主类中,我插入了以下代码

Intent intent = new Intent(getBaseContext(), Reciver.class);
stopService(intent);

我认为它可以通过r.stop()停止; 但我应该如何在停止按钮中使用它。

2 个答案:

答案 0 :(得分:0)

创建Ringtone的全局实例,然后在按钮上单击使用r.stop(),使用此the docs执行服务中的操作。如果我正确理解了这个问题,请告诉我。

答案 1 :(得分:0)

在您安排闹钟时注册的广播意图,但为了确保取消,您必须注册另一个将广播取消事件发送到系统的意图。

查看在取消活动期间工作正常的代码段。

 Intent intent = new Intent(this, YourReceiver.class);
 PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 123, intent, 0);
 AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
 alarmManager.cancel(pendingIntent);