Android Background Service That Runs Forever

2019-09-07 04:47发布

问题:

I need to make an app that will run forever at the background and if needed it opens activity for user UI. I made an Activity that is the main activity which all it does at it's onCreate is to call to startService(new Intent(this, MainService.class)); The problem is that after the onStart command of the service is being called the MainService class becomes null and it is stops running.

Do I need to start the service in a different way? Should I start a new thread for the service?

Thanks, Nahum

回答1:

if your want to continue your service running though app gt close.then you need to return STICKY like that. and also need to use BroadcastReciever.and your service will not run continuesly because if system need to release memory then it will kill but yes you can restart your service for sure. So i will suggest you to go through whole documentation and stuff of service Service and Broadcast it may helpful for you. and one thing there are preferences which process will kill first by system and so on..check it out.



回答2:

You need to make a new thread in your service and start this service using command startForeground.



回答3:

If you want your service to run forever, your code needs to be able to run forever too

onStartCommand {
     while (1) {
         ..
         ..
             //call your activity?
         ..
         ..
    }
}