running a service infinitely in android

2019-07-27 02:20发布

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.

1条回答
ら.Afraid
2楼-- · 2019-07-27 03:06

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.

That technique definitely will not work on Android 8.0+.

running a service infinitely in android

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 a Notification) and return START_STICKY or START_REDELIVER_INTENT from onStartCommand(). 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.

how does whatsapp or other messaging applications always work in background.

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.

查看更多
登录 后发表回答