When to use AsyncTask and When to use Thread in Android

后端 未结 3 1468
后悔当初
后悔当初 2021-01-13 06:43

When to use AsyncTask and When to use Thread as both do work in background and both can manipulate controls in UI Thread by some mecha

3条回答
  •  梦毁少年i
    2021-01-13 07:21

    May this help you:

    For long-running tasks, we use Java threads, and Android's native AsyncTask.

    Basically Use AsyncTask for:

    • Simple network operations which do not require downloading a lot of data
    • Disk-bound tasks that might take more than a few milliseconds

    And Use Java threads for:

    • Network operations which involve moderate to large amounts of data (either uploading or downloading)
    • High-CPU tasks which need to be run in the background
    • Any task where you want to control the CPU usage relative to the GUI thread

    For more information refer Mohit's answer Click Here

    Edit:

    Service is like an Activity but has no interface. Probably if you want to fetch the weather for example you won't create a blank activity for it, for this you will use a Service. Service is access to a Context object which has an independent life cycle. This allows for reuse of common code by many activities and, in the case of public or exposed services in many applications.
    A Service runs on the main thread of the calling Component’s process by default (and hence can degrade responsiveness and cause ANRs), hence you should create a new Thread to perform long running operations.

    A Thread is a Thread, probably you already know it from other part. You need to know that you cannot update UI from a Thread. You need to use a Handler for this and stopping a thread sometime become problematic also. A thread is a mechanism for doing work without blocking other work...

    A service does not imply a thread and a thread does not imply a service. Both are different from eachother..

    An AsyncTask is an intelligent Thread that is advised to be used. Intelligent as it can help with it's methods, and there are two methods that run on UI thread, which is good to update UI components.

提交回复
热议问题