简体   繁体   中英

Android Service for uploading data for x minute in every x minute

I have 2 service running in background. One that will constantly collect location data and another to send data to server that will be start by AlarmManager every 10 minutes.

In the service that send data to server, I have a method that will post data (50 rows from database) in onStartCommand() . I'd like to have the service execute the the post data method continuously for up to 5 minutes.

I have tried to use a while loop to execute the method continuously but it will show message that app is not responding. I think that the while loop is executing the method in service non-stop in Main thread causing the activity to crash.

Is there any better way to execute a method continuously in a service while to crashing activity on the main thread?

I have 2 service running in background. One that will constantly collect location data and another to send data to server that will be start by AlarmManager every 10 minutes.

This will be terrible for battery life, as you will need to keep the CPU constantly powered on via a WakeLock to "constantly collect location data".

In the service that send data to server, I have a method that will post data (50 rows from database) in onStartCommand(). I'd like to have the service execute the the post data method continuously for up to 5 minutes.

This will be even worse for battery life, as now you will keep the WiFi or mobile radios in a high-power state continuously for up to 5 minutes.

Is there any better way to execute a method continuously in a service while to crashing activity on the main thread?

Fork a background thread.

You need to do your work on another thread.

The service helps control the lifecycle outside of the UI, but it is still on the MainThread.

It is called a "background service" as it has a background lifecycle which is different to you Activity lifecycle.

Simplest example is spawn an ASyncTask from your background Service or better use an IntentService . An IntentService will automatically control your use of threads.

Here is the official documentation for Intent Service thread work:

http://developer.android.com/training/run-background-service/send-request.html

And here are the API docs for what I discussed http://developer.android.com/reference/android/os/AsyncTask.html http://developer.android.com/reference/android/app/IntentService.html

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