Android asynchronous service calls strategy

2019-04-02 06:09发布

Here's scenario:

  1. Client makes remote call to the service (returns void) and provides a callback object
  2. Service executes some long running logic on the background thread and then uses callback object to trigger ether success or failure which (since these manipulate visual elements) execute in Activity#runOnUiThread block

The scenario runs fine. The question is - can I use AsyncTask to make code less verbose (how?) and would be there any advantages in doing it that way?

Or should I just get away from client callbacks alltogether and execute remote service calls retrofitted to return some value within AsyncTask#doInBackground?

2条回答
forever°为你锁心
2楼-- · 2019-04-02 06:26

It is difficult to say whether AsyncTask will make things less verbose, since we don't know the verbosity of your current implementation.

For me, AsyncTask means I don't have to worry about cleaning up threads myself (e.g., post some sort of kill job to a LinkedBlockingQueue my background thread is waiting on). It also eliminates the custom Job classes I used to create for using with LinkedBlockingQueues. And, it simplifies a bit doing final work back on the UI thread.

In your case, with a remote service, the UI thread issue is less critical, since the activity needs to handle that itself.

I don't see what the difference is between your #2 and your last paragraph. In both cases, your service will call the callback object, which will use something like runOnUiThread() to arrange for the work to be done on the UI thread.

AFAIK, the only two ways to have a service doing any sort of asynchronous work let the client know that work is done is by a broadcast Intent or a callback object. Broadcast Intents are convenient but public (i.e., other code can watch for them).

I suspect I probably have not helped much here, but I just don't know enough of your scenario to provide greater detail.

查看更多
等我变得足够好
3楼-- · 2019-04-02 06:31

I'm having quite the same question : i'm developping a map activity, with a 'lazy-loading' functionnality (xml from Network, parsing it, then updating my map with the 'items' created from that parsing...)

i wondered what would be 'the best' way to implement it...

  • async service launched from a thread, an update notification via Intent?
  • just a thread (no service, since i don't need to expose it to other applications) w/ callback
  • asyncTask with callback i'm comparingthese in terms of speed, using the Android SDK performance analysis Tool traceview

I guess a more precise answer might be found from Android contributors on the Android-developper-group...

查看更多
登录 后发表回答