"Android Basics" Asynctask Basics

Source: Internet
Author: User

Android Single threading model

When a program starts for the first time, Android launches a main thread, which is primarily responsible for handling UI-related events such as user keystroke events, user-clicked button events, User touch screen events, and screen drawing events, and The main thread distributes the related events to the corresponding components for processing. So the main thread is often called the UI thread.
The principle of single-threaded models must be adhered to when developing Android apps:
Android UI operations are not thread-safe and must be executed in the UI thread.
In non-UI threads (child threads), the UI thread cannot be manipulated directly, that is, the UI cannot be set, otherwise it throws: Android.view.viewroot$calledfromwrongthreadexception exception.
Single-threaded model benefits:
1. Ensure the accuracy of the UI
2. Ensure the stability of the UI and avoid the confusion caused by multi-threading and UI operation.

Asynctask Overview

Although Android is a single-threaded model, this single thread is limited to the UI. Other time-consuming operations, such as network connections, reading files, and so on, can be placed in sub-threads. But multithreaded programming implementation is more cumbersome, so, Android provides a well-packaged component--asynctask.
Asynctask is a component of an asynchronous task in Android that was created to:
-Implement update UI in child threads
-Encapsulate, simplify asynchronous tasks

ASYNCTASK Basic Structure

Asynctask<params,progress,result> is an abstract class that needs to be inherited when used, and its basic structure is described below.

Three generic parameters to be specified when inheriting
    • Params: Type of input parameters when starting a task
    • Progress: Type of progress value returned in background task execution
    • Result: The type of the result returned after the background execution task finishes
      So, these three parameters are data types, which are called generic parameters.
      Cases:
publicclass AsyncTaskTest extends AsyncTask<Void,Void,Void>{    @Override    protected Void doInBackground(Void... params) {        // TODO Auto-generated method stub        returnnull;    }}

In the example above, asynctask three generic parameters are void.

callback method to be overridden
    • Doinbackground: The method that must be overridden, which is the task that the background execution thread will complete
    • OnPreExecute: Runs in the UI thread, runs before the background execution thread, and is used for some initialization operations
    • The method that is called after the Onpostexecute:doinbackground method is executed, and the value returned by the Doinbaskground method is also passed to the method
    • The method that is called in the Onprogressupdate:doinbackground method execution to update the execution progress of the task
      These four methods can be seen by viewing the source code of the Asynctask class in Eclipse.
      Here's an example:
 PackageCom.asynctasktest;ImportAndroid.os.AsyncTask; Public class asynctasktest extends asynctask<void,void, Void>{  @Override  protectedvoid Doinbackground (void ... params) {//TODO auto-generated method stub  return NULL; }@Override  protectedvoid OnPreExecute () {}@Override  protectedvoid OnPostExecute (void result) {}@Override  protectedvoid Onprogressupdate (void ... values) {}}

Doinbackground can be generated automatically, and three additional methods need to be added yourself.

Using Asynctask

First of all, add the above four methods of execution content:

 PackageCom.asynctasktest;ImportAndroid.os.AsyncTask;ImportAndroid.util.log;public class asynctasktest extends asynctask<void,void,  Void>{ @Override protectedvoid Doinbackground (void ... params) {//TODO auto-generated method stubLOG.D ("Asynctasktest","Doinbackground");//Update progress, execute this method to execute Onpregressupdate   This. publishprogress ();return NULL; }@Override protectedvoid OnPreExecute () {LOG.D ("Asynctasktest","OnPreExecute"); }@Override protectedvoid OnPostExecute (void result) {LOG.D ("Asynctasktest","OnPostExecute"); }@Override protectedvoid Onprogressupdate (void ... values) {LOG.D ("Asynctasktest","Onprogressupdate"); }}

The task performed is to only output four method names in the Android log.

The following is a call to Asynctasktest in the main thread that executes this asynchronous task:

public   class  mainactivity  extends  actionbaractivity  {  @Override  protected  void  oncreate  (Bundle savedinstancestate) {super . OnCreate (savedinstancestate);  Setcontentview (R.layout.activity_main);  //instantiation asynctask   Asynctasktest test = new  asynctasktest ();  //start background thread  test.execute ();  //main thread perform task: Output Hello,world  in log LOG.D ( "mainactivity" ,  "Hello, World" ); }}

The output in the log after execution is:

The first thing to do is onpreexecute, which is responsible for initializing the parameters and executing them in the UI thread, and then outputting the "Hello, World" output from the main thread, indicating that Asynctask does not block the main thread , then executes the background task execution method Doinbackground and the progress Update method Onprogressupdate method, finally executes the OnPostExecute method after the Doinbackground method executes, indicates the background thread runs the end.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

"Android Basics" Asynctask Basics

Related Article

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.