Search code examples
androidservicenotificationsswipe

Removing notification bar when the application is closed through swipe action


When i open the app, i press the home button and it still plays in background (it shows a notification bar with play and stop), after a while i want it to close it so i'm pressing home button until it shows me the active applications and then swipe it to close, so if i close it like this i want the notification for my app to disappear

How can i remove my notification bar that is related to the application if it's closed with the swipe action through the 'list of active applications when keep pressing home (when you are in the home screen of the device) ?

** Realized the onDestroy() method from my class isn't called when i swipe to close the application

** Second realize that i have to call the Service in order to get to the onTaskRemoved() to which in this method i can implement the notificationManager to close


Solution

  • Ok, so i have figured it out.


    First i will make a Service Class

    public class MyService extends Service {
    
    @Override
    public void onCreate()
    {   
        super.onCreate();
    }
    
    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }
    

    }

    now Im going to start the service in the onPause()

      startService(new Intent(this, MyService.class));
    

    and then the onDestroy() method (it is called with the help of Service)

    @Override
    protected void onDestroy()
    {           
        super.onDestroy();              
    
        String ns = Context.NOTIFICATION_SERVICE;
        NotificationManager nMgr = (NotificationManager) this.getSystemService(ns);
        nMgr.cancel(1);     
    }   
    

    and don't forget to add in Manifest

     <service android:name="this.MyPackage.MyService" 
                 android:stopWithTask="false"   >            
        </service>
     </application>