How Do I Stop Playing Sound By Switching Between Toggle Button?
Solution 1:
In your toggle button off code you can add the lines:
Uri alarmUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
Ringtoneringtone= RingtoneManager.getRingtone(context, alarmUri);
ringtone.stop();
Edit:
After looking at your code, this may not work in all cases. If your activity is killed off and the alarm is fired there will be no activity open to stop the ringtone. Even starting it via the notification, the toggle button will be in the wrong state. The ringtone should probably be stopped when the notification is touched.
When the alarm fires, it calls the AlarmReceiver, which calls the AlarmService. The AlarmService is what is creating the notification. It specifies the Intent that will be called when the notification is pressed. That is your Main activity, the AlarmActivity.
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, AlarmActivity.class), 0);
You can pass extras in the intent to notify your activity that the alarm is in the ringing state and to dismiss it then, or just set your toggle to on and let the user dismiss it.
What I don't see is a call to completeWakefulIntent(intent) which will release your wake lock, but that may be an issue with the sample.
Edit
The Ringtone needs the original instance in order to stop it. The correct way would be to create a service, but that's a bit involved for this demo. I'd suggest creating a static reference and a static method to access it.
AlarmReceiver:
privatestatic Ringtone mRingtone = null;
...
mRingtone = RingtoneManager.getRingtone(context, alarmUri);
mRingtone.play();
...
}
publicstaticvoidstopRingtone() {
mRingtone.stop();
}
AlarmActivity:
AlarmReceiver.stopRingtone();
alarmManager.cancel(pendingIntent);
setAlarmText("");
Log.d("MyActivity", "Alarm Off");
Post a Comment for "How Do I Stop Playing Sound By Switching Between Toggle Button?"