I have tried till now - start sticky - alarm to restart service - on task removed start the service - use job service (has latency and executes task slow)
Is there a proper method to make an infallible background service like the popular apps?
2014–2015. On February 19, 2014, one year after a venture capital financing round at a $1.5 billion valuation, Facebook, Inc. (now Meta Platforms) announced it was acquiring WhatsApp for US$19 billion, its largest acquisition to date.
Jan Koum and Brian Acton are the founders of WhatsApp. The headquarters of WhatsApp is in Mountain View, California, US.
Creating a background service that "does not die" is not possible in android.
You can create a service and take certain measures to have it running as much as possible, but the OS will kill it at times and your service will not be running until the OS decides to restart it (in case it is a sticky service).
Things you can do:
MY_PACKAGE_REPLACED
broadcast.BOOT_COMPLETED
and REBOOT
broadcasts.onTaskRemoved
in the service, to schedule a restart of the service in case the user swipes away your app from the list of recent apps.You can never have a 100% uptime, but this will get you close.
A background service, if not visible by the user will always be killed earlier or later by the Android system. It is the way memory management work.
If you really need to make a service continously run, you need to show a permanent notification to the user (like when you are using a radio app or a music player app).
What whatsapp and facebook probably do is to wake up the app remotely with any sort of messaging such as Firebase Cloud Messaging (ex-Google Cloud Messaging) or using Broadcast Receiver on certains events... But it surely isn't en ever going on service.
Read this part of Android documentation to better understand this: Service Process Lifecycle.
As you can see, to give priority to your service process you will need to start it in foreground and pass it an Ongoing Notification using startForeground(int id, Notification notification). Use setOngoing(true) in your NotificationBuilder to set a Notification as an Ongoing one: setOngoing(boolean b) doc.
Finally you usually want to add action in your Ongoing Notification (such as Player controls or the possibility to close the notification and hence your service when memory will be collected)
Here a full sample code:
Notification notification = new NotificationCompat.Builder(this)
.setContentTitle(getString(R.string.notification_title))
.setContentText(getString(R.string.notification_text))
.setSmallIcon(R.drawable.ic_small_icon)
.setColor(getResources().getColor(R.color.colorAccent))
.setContentIntent(pendingIntent)
.setOngoing(true)
//.addAction(android.R.drawable.close_service,"Close", closeServiceIntent)
.build();
startForeground(Constants.NOTIFICATION_ID, notification);
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