1

I am developing an app for radio streaming using exoplayer library. So, I want to clear(delete) exoplayer notification bar (with play/stop buttons) when I close the app. Now, I close the app but the notification bar still appears and doesn/t close with a swipe left/right.

I try the following source code but it doesn't work.

protected void onDestroy() {
        super.onDestroy();
        NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.cancel(NOTIFICATION_ID); 
}

I tried it with the method cancelAll() etc but it doesn't work too.

It works on onPause() and onStop() methods but I want to do this onDestroy() only.

Thanks in advance.

Dmitrii Leonov
  • 1,331
  • 1
  • 15
  • 25
St.
  • 33
  • 4

2 Answers2

0

You can try to place the code of dismissing the notification before the super.onDestroy() if it's still not working there is another solution, you basically need to create a service which will "listen" when your application is closing and you can put your own custom logic in to it. See here link. It might be an overkill but I used this solution for my application and it's working.

DemoDemo
  • 372
  • 1
  • 12
  • How does service know when application is closing? – IgorGanapolsky Jun 16 '20 at 16:45
  • 1
    You are basically registering your service to an event when the application is being closed. An intent will be sent to your service and you can react to it. Check for more details in the link I provided in my post. – DemoDemo Jun 17 '20 at 17:54
0

If you are using AndroidX (if you are not, it might be good to migrate too), you can use the LifecycleObserver, which will be called whenever the app is closed regardless of which screen you are on. You can implement it in your Application class like this:

public class YourApp extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        // ...
        ProcessLifecycleOwner.get().getLifecycle().addObserver(new AppLifeCycleListener());
        // ...
    }

    // ...

    public class AppLifeCycleListener implements LifecycleObserver {
        @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
        public void onAppLaunched() {
            // ...
        }

        @OnLifecycleEvent(Lifecycle.Event.ON_START)
        public void onMoveToForeground() {
            // ...
        }

        @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
        public void onMoveToBackground() {
            // Dismiss notifications here
        }
    }
}

Note, you will need the androidx.lifecycle dependency in your app build.gradle

omz1990
  • 557
  • 4
  • 10