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?
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.
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" />
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.
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!
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