My question in general is - how to make a background service run every "INTERVAL" and not get the ANR message(Tried making a service called from alarmManager which initiate a thread to do its job)? Thanks for any help!
More specific:
I am making an application which is kind of DropBox - make a local folder be shared with other Android phones.
This application should run in the background.
It also should run in some time intervals in order to check if any new data created in the local directory in order to upload it to some server.
My application in general does the next sequence in PsudoCode :
1) Alarm开发者_如何学GoManager.setInexactRepeating(MySerVice)
2) (when the service is being called) DecideWhichFileToUploadOrDownload()
3) UploadNewFiles() DownloadNewFiles()
I know that the problem is with stage 3, after a upload/download that takes more than 10 seconds i get the ANR message (or my application is being killed), if the upload/download is shorter than 10 seconds than all works just fine. I tried to make a thread that will do the upload/download but once the Service is finished Android kill my Thread.
how to make a background service run every "INTERVAL" and not get the ANR message
Use an IntentService
, so that the work is done on a background thread.
I tried to make a thread that will do the upload/download but once the Service is finished Android kill my Thread.
Which is why you should use an IntentService
, as Android manages both the background thread and stopping the Service
for you. You just send it work via startService()
and do the work in onHandleIntent()
.
Do not forget that when your service (invoked by Alarm service) do thing that may required long run execution and/or asynchronous youve to think to use IntentService or you own thread messaging service
and WakeLock (see PowerManager)
otherwise the device may return/go to "deep sleep" state.. Then CPU state is fronzen until next "event"
Acquire WakeLock ASAP in your service and be sure to release it at the end of your background work...
精彩评论