按下按钮时如何停止闹钟?

时间:2017-09-27 10:03:53

标签: android

我明白这个问题很可能是基本的,但我自己也想不到。 我做了一个简单的闹钟,但我无法弄清楚如何点击button制作一个闹钟。 这是带广播的课程:

public void onReceive(Context context, Intent intent) { 
   Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM); 
   Ringtone ringtone = RingtoneManager.getRingtone(context.getApplicationContext(),notification); 
   ringtone.play();

按钮在主类中。

1 个答案:

答案 0 :(得分:0)

1. define a interface in your Utility class.
2. implement this interface inside your Receiver.
3. stop alarm via calling method of interface.

private interface RingtoneHelper {
        void stopRingtone();
    }

    class Utility {

        public static RingtoneHelper ringtoneHelper;


    }

    public class YourReceiver extends BroadcastReceiver {
        public void onReceive(Context context, Intent intent) {
            Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
            final Ringtone ringtone = RingtoneManager.getRingtone(context.getApplicationContext(),notification);
            ringtone.play();

            Utility.ringtoneHelper = new RingtoneHelper() {
                @Override
                public void stopRingtone() {
                    if(ringtone.isPlaying()) {
                        ringtone.stop();
                    }
                }
            };

        }
    }

// todo add click action for your button
if(Utility.ringtoneHelper != null) {
Utility.ringtoneHelper.stopRingtone();
}