I'm creating an application which displays the notification
of current playing song.
The song is being played via Service
& the initiation & cancellation of notification is done in the service itself.
But If the app is terminated by some exception or if I force close it via task manager, the notification remains on the top on taskbar.
How can I remove this.
Below is the code:
//In Service onStartCommand(), there is a call to initiatePlayback()
private void initiatePlayback() {
try {
if (mPlayer.isPlaying()) {
mPlayer.stop();
}
mPlayer.reset();
mPlayer.setDataSource(currentData);
mPlayer.prepare();
if (reqAudioFocus()) {
mPlayer.start();
}
if (mPlayer.isPlaying()) {
initNotification();
}
} catch (Exception e) {
Toast.makeText(this,
"PlayTrack->initiatePlayback(): " + e.toString(),
Toast.LENGTH_SHORT).show();
}
}
@Override
public void onDestroy() {
stopPlayback();
mPlayer.release();
mPlayer = null;
super.onDestroy();
}
private void stopPlayback() {
if (mPlayer.isPlaying()) {
mPlayer.stop();
mPlayer.reset();
cancelNotification();
}
}
private void cancelNotification() {
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
mNotificationManager.cancel(NOTIFICATION_ID);
}
Use notifications To clear one notification, swipe it left or right. To clear all notifications, scroll to the bottom of your notifications and tap Clear all.
First, press-and-hold on the persistent notification you want to remove. Another option is to swipe the notification left or right, and then tap on the cogwheel icon shown next to it. Next, tap on the switch next to Permanent to disable it, and then press Save.
Catch the exception and in the catch
clause cancel it:
mNotificationManager.cancel(MY_NOTIFICATION_ID);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With