Thread communication ----- AsynTask

Source: Internet
Author: User

AsynTask is a lightweight form of Handler, which can be used for processing time-consuming operations. Sometimes we will find that when the main thread is sleeping, you will encounter a "card screen" status when performing other operations. This effect is extremely bad. However, we can solve this problem through AsynTask.

◆ "Card screen" Phenomenon

1) create a custom class object to simulate time-consuming operations

Public class Mythread {// custom class public static void sleepy () {try {Thread. sleep (5000); // simulate time-consuming operations} catch (InterruptedException e) {// TODO Auto-generated catch block e. printStackTrace ();}}}

2) It is called when the start button is clicked in the main thread, and hello is output to the console when the print button is clicked.

Public class MainActivity extends Activity implements OnClickListener {private Button startBtn, printbtn; // declaration Button @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); // search for the resource startBtn = (Button) findViewById (R. id. start); printbtn = (Button) findViewById (R. id. printBtn); // Add the listener startBtn for the button. setOnClickListener (this); printbtn. setOnClickListener (this) ;}@ Override public void onClick (View arg0) {switch (arg0.getId () {case R. id. start: // call Mythread for a custom thread-type sleep method. sleepy (); // In this case, the status of the card screen will be break; case R. id. printBtn: System. out. println ("hello"); break ;}}}

3) Result:

◆ If the print method is clicked directly, the background output is normal.

◆ However, if you click the start button and click the print button of any number of times, you will not see the effect immediately. Instead, you will wait for 5 seconds to get the output together.

How can we solve the problem of "card screen? Let's take a look at AsynTast.

I. Principle

In fact, the startup of AsynTask is equivalent to opening up another thread to handle time-consuming operations in this thread, so as not to delay other operations on the user's main UI and improve the user experience.

Ii. Creation and common methods

1: Create

It is inherited from the AsynTask class, but there are three generic types. Note that all generic types Use the packaging class.

Class MyAsynTask extends AsyncTask <generic 1, generic 2, generic 3>

2: common methods and parameters

1) Generic 3 doInBackground generic 1): core processing time-consuming. Method return value type: Generic 3; parameter type: Generic 1. The parameter value comes from the value passed when AsynTask is started on the main interface.

2) onPostExecute generic 3): method executed at the end of asynchronous processing. The value of the parameter comes from the doInBackground returned value. Therefore, the parameter type is generic 3.

3) onPreExecute): the method that will be executed at the Asynchronous Start, that is, it will be executed before the doInBackground method is executed.

4) onProgressUpdate generic 2): interaction with the main thread UI. Parameter type: Generic 2. The value of the parameter comes from the value passed through publishProgress in the doInBackground method.

3. How to solve the "card screen phenomenon "?

1) create a class inherited from AsynTask and override the doInBackground method.

2) call time-consuming operations in the doInBackground Method

Public class MyAsynTask extends AsyncTask <Void, Void, String >{@ Override protected String doInVoid... params) {Mythread. sleepy (); // return null for processing time-consuming operations ;}}

3) In the listener of the start button of the main thread, the time-consuming operation is not directly called, but the AsynTask object is created to start the thread through execute.

Case R. id. start: // MyAsynTask myAsynTask = new MyAsynTask (); // myAsynTask.exe cute (); // start AsynTask, so that break is not displayed on the screen;

4) Result: No matter how you click it, the "card screen" phenomenon does not appear in any sequence of clicks.

Iv. Application of AsynTask

Implemented function: it is still the synchronous use of the progress bar and TextView control in the previous blog.

1) create a class inherited from AsynTask. Pay attention to adding a generic type.

2) provide the control to be synchronized on the main interface of member properties) and add the constructor.

Private TextView TV; // member variable private ProgressBar bar; // member variable public MyAsynTask (TextView TV, ProgressBar bar) {super (); this. TV = TV; this. bar = bar ;}

3) override the onPreExecute () method: Let him prompt "Asynchronous Start"

// The method that will be executed at the Asynchronous Start, that is, the method that will be executed before the doInBackground method is executed @ Override protected void onPreExecute () {TV. setText ("Asynchronous starts"); super. onPreExecute ();}

4) override doInBackground) method: update the value.

/*** Core processing method. Its parameters are passed in at startup of the main interface * return type: Generic 3 * parameter type: generic 1 * // @ Override protected String doInString... params) {int count = 0; // initialization variable for (count = 0; count <= 100; count ++) {try {Thread. sleep (100); // Add 1} catch (InterruptedException e) {e. printStackTrace () ;}// the onProgressUpdate method publishProgress (count); // This count will be passed to the onProgressUpdate parameter} return count + "; // return value to onPostExecute method, to facilitate end judgment}

5) override onPostExecute) method: a prompt is displayed at the end.

// Method executed at asynchronous end. The parameter is returned from doInBackground, that is, vcount; @ Overrideprotected void onPostExecute (String result) {if (result! = Null) {TV. setText ("Asynchronous end, current I value:" + result + "") ;}super. onPostExecute (result );}

6) override onProgressUpdate) method: update the main UI

// Interaction with the UI of the main thread. The parameter value is from the publishProgress parameter value in the doInBackground method @ Overrideprotected void onProgressUpdate (Integer... values) {bar. setProgress (values [0]); // update the progress bar TV in the main Ui. setText (values [0] + ""); // update the text box super. onProgressUpdate (values );}

7) Add a listener for the button in the main UI and start AsynTask

Btn. setOnClickListener (new OnClickListener () {@ Override public void onClick (View v) {// instantiate AsynTask object MyAsynTask myAsynTask = new MyAsynTask (TV, bar ); // start AsynTask myAsynTask.exe cute ();}

8) Result

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/102919E11-0.png "title =" 1.PNG"/>


The returned values and parameter types of several AsynTask methods must be further studied .. A little blind .. 650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/1029191F8-1.gif "/>


This article is from the "Schindler" blog, please be sure to keep this source http://cinderella7.blog.51cto.com/7607653/1288784

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.