1

My alarm code is working fine as default ringtone is playing well on time. But not able to stop the alarm tone. In receiver class I inserted the following code.

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

I also inserted the code for cancel the alarm in main class, which is also working well with the code

alarmMgr.cancel(pendingIntent);

But once the default ringtone start playing and user want to stop this by stop button then it is not working. In main class with stopbutton.setOnClickListener I inserted the following code

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

I think it can be stop by r.stop(); but how should I use it in stop button.

Nim
  • 25
  • 1
  • 8
  • No getting exactly, If I am not wrong you put the stop button on your own UI but it's not working , Am i right ? – QuokMoon Oct 08 '17 at 04:12
  • I have three button in main layout connected with main class. start button call the alarm manager and wake up receiver class (r.play is here in this class) and working well. Cancel button cancel the alarm. now the third button is the stop button. – Nim Oct 08 '17 at 04:14

2 Answers2

0

Make a Global instance of Ringtone and on button click use r.stop() use this link to perform the operation in service. Let me know if I understood the question correctly.

Krunal Kapadiya
  • 2,853
  • 3
  • 16
  • 37
  • I did the coding as per your suggestion and it worked. Thanks a lot brother. – Nim Oct 08 '17 at 04:58
  • If it is helpful then please upvote it, it will be helpful to others also – Krunal Kapadiya Oct 08 '17 at 05:26
  • How to do it? Should I choose the upper arrow? – Nim Oct 08 '17 at 05:28
  • ok, I am doing this and it is saying "Thanks for the feedback! Votes cast by those with less than 15 reputation are recorded, but do not change the publicly displayed post score. – Nim Oct 08 '17 at 05:34
0

A broadcast intent registered while you schedule the alarm but to ensure a cancel you have to registered another intent that would boradcast cancel event to system.

Look at piece of code working fine during a cancel event.

 Intent intent = new Intent(this, YourReceiver.class);
 PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 123, intent, 0);
 AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
 alarmManager.cancel(pendingIntent);
QuokMoon
  • 4,387
  • 4
  • 26
  • 50