android design considerations: AsyncTask vs Service (IntentService?)

后端 未结 5 1603
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-29 16:49

I\'m designing an android app which will need to do the following steps:

  1. user pushes a button or otherwise indicates to \"sync data\".
  2. sync process wi
5条回答
  •  清酒与你
    2020-11-29 17:16

    I tend to prefer the IntentService + BroadcastReceiver combo because they give you a really strong degree of control

    You definitely have to make sure the UI is running if you are updating something on the screen. ASyncTask crashes were at once reported to be one of the top causes of Android crashes. This can be avoided by keeping some sort of "activityIsAlive" variable and skipping or delaying a UI update if the activity is dead.

    The IntentService + BroadcastReceiver combo is a little more resistant to the crash because most tutorials tell you to shut off the BroadcastReceiver onPause or onStop. If you do not do this, again you'll have to turn off the UI update. There's a runOnUiThread command somewhere that will help you do UI updates.

    The IntentService + BroadcastReceiver combo is also more extensible. You can create functions and extend BroadcastReceiver to make a more elegant REST processing solution. However, it does require more plumbing vs an ASyncTask

    If you do delay the UI update, you may be able to rig it on OnWindowFocusChangedListener. When that function receives true, it means that the UI is alive.

    tldr; Make sure the Activity and/or Fragment is alive before updating the UI if you are running something in the background

    2015 Edit: check out Loaders as well. A little harder to grasp because there's a lot going on behind the scenes

提交回复
热议问题