Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid cancelation of Notification on removing app from recent apps list

I'm using below snippet to show a notification from a service inside my app:

NotificationCompat.Builder mBuilder =
        new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_launcher)
                .setContentTitle(currentNotificaion.getMessageTitle())
                .setContentIntent(contentIntent)
                .setContentText(currentNotificaion.getMessageText())
                .setAutoCancel(true);
int mNotificationId = (int) currentNotificaion.getMessageServerID();
// Gets an instance of the NotificationManager service
NotificationManager mNotifyMgr =
        (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Builds the notification and issues it.
mNotifyMgr.notify(mNotificationId, mBuilder.build());

My service is declared like this in manifest:

<service
android:name="com.myapp.services.NotificationService"
android:stopWithTask="false">
</service>

But when closing my app from recent apps list, notification is disappear and removed from notification bar. Another things is I'm not going to use stick notifications which are never removed from notification bar.

How can I avoid this?

like image 814
VSB Avatar asked Oct 21 '16 09:10

VSB


2 Answers

Inside your Manifest file, keep flag stopWithTask as true for Service. Like:

<service
    android:name="com.myapp.MyService"
    android:stopWithTask="true" />

I just resolved a similar kind of issue.

Here is what you can do if its just about stopping service when application is killed by swiping from Recent app list.

  1. Inside your Manifest file, keep flag stopWithTask as true for Service. Like:

But as you say you want to unregister listeners and stop notification etc, I would suggest this approach:

Inside your Manifest file, keep flag stopWithTask as false for Service. Like:

    <service
        android:name="com.myapp.MyService"
        android:stopWithTask="false" />
  1. Now in your MyService service, override method onTaskRemoved. (This will be fired only if stopWithTask is set to false).

    public void onTaskRemoved(Intent rootIntent) {
    
    //unregister listeners
    //do any other cleanup if required
    
    //stop service
        stopSelf();  
    }
    

Hope it will help you.

like image 73
Jamil Hasnine Tamim Avatar answered Sep 28 '22 06:09

Jamil Hasnine Tamim


If you want a background service running with a foreground notification, the best way is to use startForeground() function. You can check Android docs here and there are some answers about it in SO also like this from @CommonsWare with example included.

Hope it helps!

like image 26
Hugo Avatar answered Sep 28 '22 08:09

Hugo