Should I use AsyncTask or IntentService for my application?

前端 未结 8 661
陌清茗
陌清茗 2020-12-12 21:48

I have been reading around on internet connectivity with Android and noticed there are different ways to handle this i.e. AsyncTask and IntentService. However, I\'m still no

8条回答
  •  一向
    一向 (楼主)
    2020-12-12 22:23

    AsyncTask and IntentService have many same

    • Can execute task in worker thread
    • Can run in background
    • Keep running till task finished event the activity which started it is destroyed
    • Can notify to update UI during task running or after task finish
      • For AsyncTask we often use onProgressUpdate, onPostExecute or if you want you can use BroadcastReceiver
      • For IntentService we use BroadcastReceiver

    Different

    1) Send task while running or after running finish

    Example we have a task is: download file from server base on fileName.

    Using AsyncTask

    If we one instance of AsyncTask, during execute downloading file A we cannot execute download file B AsyncTask (since we get java.lang.IllegalStateException: Cannot execute task: the task is already running.). Also after downloading file A finished, we can not execute download file B (since we get java.lang.IllegalStateException: Cannot execute task: the task has already been executed (a task can be executed only once).
    To download file B during or after download file A, we need to create new instance of AsyncTask.
    => To download file A and file B, we need 2 instance of AsyncTask => 2 worker thread created

    Using IntentService

    During download file A, we can sent intent to download file B => after download file A finished it will auto start download file B => don't need new instance, don't need new worker thread.

    If we sent intent to download file B after download file A finished? After download file A finished, IntentSevice will destroyed (because there is no more task). Therefore, when start download file B, new instance of Service is created however no new thread created (service keep using only 1 worker thread which name is defined in IntentSevice constructor

    2) Implement AsyncTask is easier than IntentService

    USING
    We will see that AsyncTask and IntentService have many same so in most case we can use AsyncTask or IntentService. However

    • I often use AsyncTask for some task that start, finish, interact with UI in 1 Activity
    • I often use IntentService for some task that can start/finish and interact or don't interact with UI from any Activity

    This answer is base on my test. Please correct me if I am wrong. Hope it help.

提交回复
热议问题