Should I use AsyncTask or IntentService for my application?

前端 未结 8 639
陌清茗
陌清茗 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:33

    AsyncTask doesn't play well with configuration changes or other things that restart the Activity.

    IntentService is good for a something that should always be available, regardless of how long it takes to do its work. I prefer IntentService in most cases because AsyncTask is so much more dependent on Activity state.

    Some notes:

    • AsyncTask is best for quick tasks that should go right back to the UI, but it can be used in a variety of situations.
    • The statement "periodically perform operations on the main thread" is vague. AsyncTask spawns a new background thread that is different from the main thread, and does its work on the new thread. Thus the name AsyncTask.
    • An IntentService doesn't require "manipulating" the BroadcastReceiver framework. All you need to do is send a local broadcast Intent, and detect it in your Activity. Whether this is harder to do than an AsyncTask, I don't know.
    • IntentService is meant to do long-running tasks, which it does in the background.
    • AsyncTaskLoader is OK to use, but it's meant to be the base class for CursorLoader, etc. If you want to refresh "nearby" trails when users move to a new location, an IntentService is probably better.

    Don't forget to check for connectivity before trying to update location.

提交回复
热议问题