简体   繁体   中英

Android long time running service

I am working on an Android project and I need the app to work even when the device is locked.

The idea is to open the app that will start the (Intent)Service , the service processes the data all the time. The device can be locked/put away and after some time when the app is opened the service is manually stopped. The service should be running all the time in the background .

I have found information online, but I am not sure what to use and in which way..

I have found that the IntentService can be used. Also the service should run in a new thread . I need to process the data from gps all the time, should I use WakefulBroadcastReceiver ?

Thank you.

IntentService is not necessarily what you want to use. It will automatically spawn a new thread just to handle an incoming Intent . Once all incoming Intent s have been handled it will stop the Service . To have a long running Service , you would need to derive from Service and when it is started return START_STICKY from the onStartCommand() method, plus spawn your own thread to handle your background work.

If you need to monitor GPS, you'll have to manage that along with keeping the device awake using a WakeLock . Note that in Marshmallow, this gets more complicated because of the new Doze mode where even wakelocks are ignored.

Also, note that the way Android is architected there is still a chance that your application running the background Service may be killed. Android uses a unique process management technique based on memory pressure and user perceived priority to determine how long a process should stick around. I recommend reading up on the Service lifecycle in the documentation.

In android their is no fool proof way to ensure that your service runs forever because the LMK(low memory killer) when the system needs resources (based on a certain memory threshold) , kills the service then if it can restarts it. If you handle the restart properly the service will continue to run.

Services that are given foreground priority are significantly less likely to be killed off, so this might be your best bet. However their will be a notification of your service running the in the background on the menu bar up top. Foreground Service

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM