13. Multi-Threading and asynchronous tasks for Android

Source: Internet
Author: User

Course Objectives: Three ways to learn asynchronous operations in Android

Key difficulties: The relationship between Handler and threads Implementation of Handler Message Queuing

Assessment objectives:

using Handler is asynchronous, does it create a new thread? No

Handler is it in the mainline range?

Handler The Post and Sentmessage method, using a queue or two?

create a handler in a child thread , and then SendMessage What will happen?

the child thread establishes the handler,  when constructing the main thread, Looper? Yes

First, review the Java Multithreading Foundation

Runnable

Thread

ThreadPool

Scheduleexecutor

Thread synchronization: Synchronized\lock\semaphore.

second, on Android using multithreading in

1 > Why use multithreading

For time-consuming operations, we should run in a non-main thread to avoid blocking the main thread.

To ensure a good user experience, it is recommended to exceed 50ms operations, all using threading.

AIO operations (file operations, network operations, database operations ...) ).

B Complex operations.

C timed operation.

2 > How to use multi-threaded or asynchronous operations

3 > Multithreading and interface interaction

on Android in the source code, we can see the android UI the code is not synchronized, that is, they are not thread-safe.

So, Android is how to ensure that the UI the normal operation of the?

when we operate the UI in a non-main thread when the Android throws an exception, so we should make sure that the UI the operation should be run on the main thread.

A>activity.runonuithread (Runnable)

B>view.post (Runnable); View.postdelay (Runnable, long)

C>handler

D>asynctask .

4 >android UI simple principle of main thread

do not block UI Thread ;

do not in the UI directly manipulating the UI outside of the thread ;

Iii. using handler-asynchronous or indispensable components

Problem: A problem that is encountered when using multi-threading.

I want to interact with the UI, but it seems awkward to create runnable every time, and the code is difficult to manage.

I need to constantly load the updated data in my program, how can I ensure the correctness of the data?

The user quickly click the button, my program can not respond quickly enough, what should I do?

question: What is handler and its role.

Hanlder function:

1 perform scheduled tasks, you can perform certain tasks on scheduled implementations, and you can simulate timers

2 ) inter-thread communication. when Android apps start, a main thread is created, and the main thread creates a message queue to handle various messages. When you create a child thread, you can then get the handler object created in the parent thread from your child thread , and you can send a message to the parent thread's message queue through that object. Because Android requires the interface to be updated in the UI thread, you can update the interface in other threads with this method.

3) Ensure that the operation always runs in a particular thread. For example, when we load data from a database, we need to reload it whenever we receive a notification of changes in the program, in addition to loading when it starts. To ensure the validity of the data (always using the data from the last query) and to reduce unnecessary query operations, we should ensure that they are running in the same thread.

Role Description

1.Looper: ( equivalent to a tunnel) A thread can produce a looper The thread object, which manages this line of message Queue ( convoy, message tunnel) .

2.Handler: you can construct handler . objects to be associated with Looper communication so that the push new messages to message Queue or receive Looper ( removed from message Queue ) The message that was sent.

3. message queue: used to hold messages placed by the thread.

4 . Thread: The UI thread is usually the main thread , and the Android Launcher will create a message Queue for it .

Each thread can contain a single looper. object and a MessageQueue data structures. In your application, you can define handler subcategories to receive messages sent by Looper.

thread must call Looper.loop () Let it begin the message processing process, and the thread cannot execute other code at this time.

"Myth: Handler must be in the main thread? "

question: Let's get through the code to understand the problem.

1>handler instances are associated with message processing, sending and receiving to match

2> can only be attached to Handlerthread.

3> can select its attached thread by setting the Looper

4> all operations are in one thread

5>removemessage can only remove message from the queue

iv. use of Asynctask quickly implement asynchronous tasks

1> What is Asynctask

Android in order to reduce the development difficulty of asynchronous operation, combined with handler and the thread pool, provides the Asynctask . Asynctask is a packaged background task class, as its name implies, an asynchronous task. He has the advantage of being able to perform time-consuming operations in the background while simultaneously talking about the progress of the execution and synchronizing with the UI.

2> How to use Asynctask

Asynctask three types of generic type Params are defined , Progress and result .

Params start the input parameters for task execution, such as HTTP the requested URL .

Progress Percentage of background task execution.

Result The result that the background performs the final return of the task, such as String .

Asynctask Method

doinbackground (Params...) background execution, more time-consuming operations can be placed here. Note that it is not possible to manipulate the UI directly. This method is performed on a background thread, and it usually takes a long time to complete the task's main work. You can call Publicprogress (Progress...) during execution. to update the progress of the task.

OnPostExecute (Result) equivalent to Handler working with the UI the way in which the face can be used in Doinbackground the resulting processing action UI . This method is executed on the main thread, and the result of the task execution is returned as a parameter to this method

Optional methods:

onprogressupdate (Progress...) You can use the progress bar to increase user experience. This method executes on the main thread and is used to show the progress of the task execution.

OnPreExecute () here is the end user call Excute When the task executes before it starts calling this method, you can display the progress dialog box here.

oncancelled () action to be made when the user calls cancel

Asynctask three states: Pending, running, finished

Rules

Asynctask must be created in the main thread;

Execute () can only be called once;

Execute () must be executed on the main thread;

Do not call OnPreExecute (), OnPostExecute (), Doinbackground (), onprogressupdate ();

3> The realization principle of analysis Asynctask

4> analyze Asynctask and handler who consume more resources

How to analyze the size of a process that consumes memory.

5> Explore what to use when using Asynctask, when to use handler

Tasks can be aborted and need to be constantly and asynctask when used;

Tasks need to be repeated repeatedly, and UI interaction with handler;

V. whether there is a need to use multithreading in the test procedure

1>strictmode.threadpolicy

Detectdiskreads ()

Detectdiskwrites ()

Detectnetwork ()

The processing method after 2> detection

Penaltylog ()

Penaltydeath ()

Penaltydialog ()

Penaltydropbox ()

Penaltyflashscreen ()

13. Multi-Threading and asynchronous tasks for Android

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.