I have a scheduled Service (for scheduling I use a bundle of BroadcastReceiver and AlarmManager). Service does some long running operations using AsyncTask.
- Connect to the server
- Check for some updates
- Load updates if they exists
- Perform data update operations
I call the task from onStart method like this:
onStart(...){
...
new AsyncUpdate(...).execute(...);
}
User can perform update o开发者_如何学Cperations manually (he presses the button that runs the Service). So what if he presses the button during executing of AsyncUpdate task? According to the reference new worker thread will be created so I need to synchronize them. I use a static param from my Service class for it:
synchronized(MyService.runLock){//public static Object runLock = new Object();
...perform download and update operations
}
Is that correct?
I used :remote service before, so the Service executed in a separate thread and I didn't need synchronization between these because I knew I had just one thread.
You could use the getStatus() method.
Keep a reference of your AsyncUpdate
and see if it returns RUNNING or not.
If you don't mind the actions being queued then it's possible IntentService might be of use to you. It handles its own queue and executes each request in turn on a worker thread. When it runs out of work it will stop itself.
精彩评论