Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cancel notification on unexpected/force app termination

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);
    }
like image 696
reiley Avatar asked Aug 13 '12 07:08

reiley


People also ask

How do I clear all app notifications?

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.

How do I force quit notifications on Android?

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.


1 Answers

Catch the exception and in the catch clause cancel it:

mNotificationManager.cancel(MY_NOTIFICATION_ID);
like image 177
Andy Res Avatar answered Oct 01 '22 23:10

Andy Res