I have been trying to create a service in android so that it infintely listens to a websocket and then when message received puts up a notification.The most common tutorial that i encountered is the one in which i create a service and onDestroy of that service a broadcast is triggered and then from the broadcast the service is started again. But none of these techniques seems to be keeping my service alive when my application is killed.
Some of the answers that i received is that services cannot work indefinitely, then how does whatsapp or other messaging applications always work in background.
That technique definitely will not work on Android 8.0+.
That is not possible in general, and definitely is not possible on Android 8.0+. The closest thing that you can do is run a foreground service (via
startForeground()
and aNotification
) and returnSTART_STICKY
orSTART_REDELIVER_INTENT
fromonStartCommand()
. Android should restart your service if your process is terminated.I would expect that your code will not work when the device enters Doze mode or app standby on Android 6.0+, unless the user adds your app to the battery optimization whitelist.
Most likely, they don't. Most likely, they are using Firebase Cloud Messaging (FCM). Brands like WhatsApp also are able to strike deals with device manufacturers to get preferential treatment, if both parties feel that such a deal would be a good idea.