开发者

Android AsyncTask Synchronization

开发者 https://www.devze.com 2023-03-08 20:46 出处:网络
I have a scheduled Service (for scheduling I use a bundle of BroadcastReceiver and AlarmManager). Service does some long running operations using AsyncTask.

I have a scheduled Service (for scheduling I use a bundle of BroadcastReceiver and AlarmManager). Service does some long running operations using AsyncTask.

  1. Connect to the server
  2. Check for some updates
  3. Load updates if they exists
  4. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消