Android Asynchronous Programming

Source: Internet
Author: User

Android's threading and memory model
The Android operating system starts a zygote (fertilized egg) process after boot, and the zygote process is responsible for creating most of the application processes. The zygote process initiates the loading of core libraries and data structures into memory and creates a Dalvik virtual machine (DVM) process--systemserver, which contains most of the system services, including management Activity service Activitymanagerservice), after Systemserver is initialized, the zygote process listens to the local socket port and waits for further instructions. When the new app is launched, Zygote will create a dvm--for the app that directly fork out a subprocess, which has the advantage that multiple app processes can access shared memory when launching multiple apps at the same time.

The Android app process is also a DVM, with many threads executing inside, such as the main UI thread (main thread), garbage collection thread, and so on. Where the main UI thread is responsible for executing the application code we write. For apps that do very little I/O operations or time-consuming operations, a single-thread development pattern is not a problem, but if there is a lot of Io or CPU-based tasks, we have to do it in other threads.

Because the main UI thread needs to synchronize the redraw of the user interface based on the hardware refresh rate [^3]. Mobile app experience fluency requires the interface frame rate [^3] to reach 60 per second, that is, every 16.67 milliseconds will need to redraw a frame, which means that if we perform the task on the main thread more than 16 milliseconds, there will be dropped frame phenomenon, that is, the interface will begin to change the card ...

There are several ways that Android performs tasks asynchronously:

Asynctask
Asynctask is the most commonly used asynchronous method, the functional structure of the design is also very rich, give the user sufficient control, the use of the main is the asynchronous execution of the task in the following method.

1
Protected Result doinbackground (params ... params)
You can then call the. Execute (params) method. http://www.huiyi8.com/moban/templates

Asynctask's execution logic can only be executed serially at API Level 3, the API level 4 is changed to a maximum of 128 thread pool execution, and API level 11 is changed to the default all asynctask are executed sequentially in one thread, This ensures that execution and commit are in the same order, and if you want to be able to execute concurrently, you can do it in the thread pool using the following method:

1
Task.executeonexecutor (Asynctask.thread_pool_executor, params);
Asynctask.thread_pool_executor is an instance of Threadpoolexecutor with a minimum of 5 threads and a maximum of 128. If you need to configure the thread pool size yourself, you can pass one instance of your configuration to the above method.

Several issues to be aware of when using Asynctask:

Fragmentation issues
Because different versions of Android Asynctask do not have the same default execution logic, they may behave inconsistently on different models. If you want to control the concurrency of Asynctask, the suggestion to solve this problem is to copy the Android SDK Asynctask Source to implement a asynctask.

Activity life cycle Issues
Activity may be destroyed earlier than asynctask execution, and if Asynctask continues to execute, resources may be wasted and if the activity or part of the view Hierarchy is referenced in Asynctask, It also causes the referenced object not to be garbage collected, causing a memory leak. Typically asynctask is defined as an anonymous inner class for activity, which creates an implicit reference to the activity.

The workaround is to:

In the activity of the OnPause method in time to cancel the Asynctask do not need to execute (this method will restart the asynchronous task when switching to a horizontal screen, a bit wasteful)
It is better to use retained headless fragment to solve the life cycle problem, the specific demo code see the reference link
Async is more suitable for blocking IO operations such as short (1, 2 seconds), CPU-intensive computing, or read-write files. Long-time network calls with Async are not the most appropriate.

Handler & Handlerthread
Asynchronous programming for handler is based on the Message Queuing model. The thread that executes the task is called the Looper thread, and the other thread sends the task that needs to be executed asynchronously to the Looper thread – inserting its message queue by: Post (which is more convenient to use, but each time a new object needs to be created) or SendMessage (a more efficient, reusable message instance, Suitable for performing a large number of similar asynchronous tasks)

Looper
Looper and its name mean that the Looper thread will loop forever, and when there is no message, the Looper thread (the consumer) uses the (object.wait) method to wait for another thread (producer) to insert a new task message, while the other threads ( object.notify)

The main thread of Android is actually a looper.

It is important to note that, as with handler and Asynctask, it is important to note that anonymous inner class has a memory leak due to an implicit reference to activity, so remember to clean up when you use it;

The workaround is to use weak Reference with the view object in the activity being used, and to handle cases where the view object is null.

The handler is suitable for longer asynchronous task processing (>2 seconds).

Loader
Loader is widely used in the Android programming framework to load data in the background (from files, databases and even networks).

Asynctaskloader
The specific loader implementation.

Cursorloader
Background loading of user database data.

The advantage of loader in use is that it is decoupled from the activity part and the life cycle management is more seen.

Intentservice
Intentservice is an implementation class for a service. Its internal implementation contains a handlerthread that is added to the queue and processed sequentially when the task is submitted to intentservice.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.