Android asynchronous Asynctask and Handler everything you should know, androidasynctask

Source: Internet
Author: User

Android asynchronous Asynctask and Handler everything you should know, androidasynctask
Raise questions:

1. What is the asynchronous Processing Method in Android?

2. How to Use Handler and how to avoid Memory leakage caused by Handler during use?

3. analyze the relationship between MessageQueue, Message, handler, logoff, main thread, and sub-thread from the source code perspective.

4. What are the differences between Handler's sendMessage and post Runnable objects?

5. How to Create a message loop for a thread, that is, how to build a logoff thread?

6. What are the methods in Asynctask, how to use them separately, which are executed in the main thread, which are executed in the subthread, and the parameter relationship in Asynctask?

7. Comparison between Asynctask and Handler + thread (difference)


Solution:

Question 1 is the asynchronous Processing Method in Android?

The asynchronous Processing Method in Android can be used

A: Handler + Thread

B: Asynctask

C: Thread + callback

D: a + c

Question 2: How to Use Handler and how to avoid Memory leakage caused by Handler during use?

Question 4: What is the difference between Handler's sendMessage and post Runable object?

Public class ThreadHandlerActivity extends Activity {private static final int MSG_SUCCESS = 0; // ID of the image obtaining success: private static final int MSG_FAILURE = 1; // ID of the image obtaining failure: private ImageView mImageView; private Button mButton; private Thread mThread; private Handler mHandler; @ Overridepublic void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. thread_layout); mHandler = New MyHandler (this); mImageView = (ImageView) findViewById (R. id. imageView); // display the image's ImageViewmButton = (Button) findViewById (R. id. button); mButton. setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View v) {if (mThread = null) {mThread = new Thread (runnable); mThread. start (); // thread start} else {Toast. makeText (getApplication (), getApplication (). getString (R. string. thread_started), Toast. L ENGTH_LONG ). show () ;}}) ;}runnable Runnable = new runnable () {@ Overridepublic void run () {// run () run HttpClient hc = new DefaultHttpClient (); HttpGet hg = new HttpGet ("http://csdnimg.cn/www/images/csdnindex_logo.gif"); // get the logofinal Bitmap bm of csdn in the new thread; try {HttpResponse hr = hc.exe cute (hg); bm = BitmapFactory. decodeStream (hr. getEntity (). getContent ();} catch (Exception e) {mHandler. obtainMessage (MSG _ FAILURE ). sendToTarget (); // return;} mHandler failed to get the image. obtainMessage (MSG_SUCCESS, bm ). sendToTarget (); // The image is obtained successfully. Send the MSG_SUCCESS identifier and bitmap object to the ui thread. // mImageView. setImageBitmap (bm); // error! You cannot operate on the ui element in a non-ui thread. *** another method that sends messages to the ui thread is more concise. MHandler. post (new Runnable () {// In fact, this Runnable does not create any threads, instead, a message is sent. * The Source Code shows that the post-generated runnable object is eventually converted into a message and added to the queue @ Overridepublic void run () {// run () method will execute mImageView In the ui thread. setImageBitmap (bm) ;}}); **/}};/*** @ author ss * problem: how to avoid Memory leakage caused by Handler * 1. Do not use non-static internal classes. When inheriting Handler, they are either stored in a separate class file, either use static internal class * why -----> in java, non-static internal classes and anonymous internal classes both implicitly hold references to their external classes, the static internal class * does not hold the reference of the external class. * Assume that the following method is executed in the thread: mHandler. postDelayed (new Runnable () {if the runnable here is declared outside rather than using an anonymous internal class, it should also be set to static @ Override public void run () {...}}, 1000*60*10); external call to finish () destroy Activity * If we use non-static MyHandler, when our code executes the finish method, delayed messages exist in * main thread message queue for 10 minutes before being processed. When we send a message whose target is the Handler to The logoff message queue, in fact, * the sent Message already contains a reference of a Handler instance. Only in this way can logoff call Handler # handleMessage (Message) to complete correct Message processing when processing the Message. * But non-static MyHandler holds external ThreadHandlerActivity references. * This causes ThreadHandlerActivity to fail to be recycled. As a result, many resources held by ThreadHandlerActivity * cannot be recycled, this is what we often call Memory leakage. **/Private static class MyHandler extends Handler {// 2. When you need to call an external Activity in a static internal class, we can use weak references for processing. WeakReference <ThreadHandlerActivity> thisLayout; MyHandler (ThreadHandlerActivity layout) {thisLayout = new WeakReference <ThreadHandlerActivity> (layout);} public void handleMessage (Message msg) {// This method runs final ThreadHandlerActivity theLayout = thisLayout In the ui thread. get (); if (theLayout = null) {return;} switch (msg. what) {case MSG_SUCCESS: theLayout. mImageView. setImageBitmap (Bitmap) msg. obj); // imageview displays the logoToast obtained from the network. makeText (theLayout, theLayout. getString (R. string. get_pic_success), Toast. LENGTH_LONG ). show (); break; case MSG_FAILURE: Toast. makeText (theLayout, theLayout. getString (R. string. get_pic_failure), Toast. LENGTH_LONG ). show (); break ;}}}}

Problem 3 analyze the relationship between MessageQueue, Message, handler, logoff, main thread, and sub-thread from the source code perspective

Question 5: How to Create a message loop for a thread, that is, how to build a logoff thread?

Public class LooperThreadActivity extends Activity {/*** relationship among MessageQueue, Message, handler, logoff, main thread, and sub-thread ** MessageQueue: Message Queue, each thread can have at most one ** Message object ** Logoff: it is bound to the current thread to ensure that only one logoff instance exists in one thread, at the same time, there is only one logoff * MessageQueue that constantly retrieves messages from MessageQueue and delivers them to the dispatchMessage * processing of the Handler corresponding to the target attribute of the message. ** logoff is the manager of MessageQueue. Every MessageQueue cannot be separated from the logoff. The creation of the loggerx object is implemented through the prepare function. At the same time, each logoff object is associated with a thread. You can call * lorule. mylorule () to obtain the lorule object of the current thread. When creating a loose object, a * MessageQueue object is created at the same time. Except for the default Logoff of the main thread, other threads do not have the MessageQueue object * by default. Therefore, messages cannot be accepted. If you need to accept it, define a logoff object (through the prepare function) by yourself. * In this way, the thread has its own logoff object and MessageQueue data structure. Logoff extracts the Message from MessageQueue and submits it to handleMessage of Handler for processing. After processing, call * Message. recycle () to put it into the Message Pool. **/Private final int MSG_HELLO = 0; private Handler mHandler; @ Override public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); new CustomThread (). start (); // create and start the finmthread instance findViewById (R. id. send_btn ). setOnClickListener (new OnClickListener () {@ Override public void onClick (View v) {// send the message String str = "hello"; Log when you click the interface. d ("Test", "M AinThread is ready to send msg: "+ str); mHandler. obtainMessage (MSG_HELLO, str ). sendToTarget (); // send a message to the CustomThread instance});} class CustomThread extends Thread {@ Override public void run () {// create a message loop. prepare (); // 1. initialize the logoff // Handler constructor to obtain the logoff instance saved in the current thread, // and associate it with MessageQueue In The logoff instance. MHandler = new Handler () {// 2. Bind handler to The logoff object public void handleMessage (Message msg) {// 3. Define the Message Processing Method switch (msg. what) {case MSG_HELLO: Log. d ("Test", "CustomThread receive msg:" + (String) msg. obj) ;}}; logoff. loop (); // 4. Start the message loop }}}

Question 6: What methods are available in Asynctask? How are they used? What methods are executed in the main thread? What methods are executed in the subthread? The parameter relationship in Asynctask

Lightweight asynchronous abstract class
Three generic types are defined: Params, SS, and Result. They are all Object types.
OnPreExecute () when this method is called before the task is executed, the Progress dialog box is displayed here.
DoInBackground (Params...) This method is executed in the background thread to complete the main work of the task, usually takes a long time. During execution, you can call publicProgress (Progress...) to update the task Progress.
OnProgressUpdate (Progress...) is executed in the main thread to display the task execution Progress.
OnPostExecute (Result) This method is executed in the main thread, and the Result of task execution is returned as a parameter of this method.
OnCancelled () calls the cancellation method and calls back this function.

The instance must be created in the main UI thread
The execute method must be called in the main thread
Never manually call
OnPreExecute (),
OnPostExecute (Result ),
DoInBackground (Params ...),
OnProgressUpdate (Progress...) Methods
An AsyncTask instance can only be executed once by Execute. Otherwise, exceptions may occur when multiple Execute operations.
Five available threads are configured,
Executor (Executors. newCachedThreadPool ())

/*** Generate the object of this class and call the execute Method * First executes the onProExecute Method * And then executes the doInBackgroup Method */public class ProgressBarAsyncTask extends AsyncTask <Integer, Integer, string> {private TextView textView; private ProgressBar progressBar; public ProgressBarAsyncTask (TextView textView, ProgressBar progressBar) {super (); this. textView = textView; this. progressBar = progressBar;}/*** the Integer parameter here corresponds to the first parameter in AsyncTask * the String return value corresponds to the third parameter in AsyncTask * this method is not running in the UI thread, it is mainly used for asynchronous operations, all spaces in the UI cannot be set or modified in this method * But the publishProgress method can be called to trigger onProgressUpdate to operate the UI */@ Override protected String doInBackground (Integer... params) {// Integer... params indicates 0 or N Integer-type values NetOperator netOperator = new NetOperator (); int I = 0; for (I = 10; I <= 100; I + = 10) {netOperator. operator (); publishProgress (I);} // params [0] indicates 1000 return I + params [0] In execute (1000). intValue () + "";}/*** here, the String parameter corresponds to the third parameter in AsyncTask (that is, receiving the doInBackground return value) * running after the doInBackground method is executed, you can also set the UI space when running in the UI thread */@ Override protected void onPostExecute (String result) {textView. setText ("Asynchronous Operation execution ended" + result);} // This method runs in the UI thread, in addition, you can set the UI space in the UI thread @ Override protected void onPreExecute () {textView. setText ("START asynchronous thread execution");}/*** the Intege parameter corresponds to the second parameter in AsyncTask * in the doInBackground method ,, every time publishProgress method is called, onProgressUpdate will be triggered to execute * onProgressUpdate is executed in the UI thread, and all operations can be performed on the UI space */@ Override protected void onProgressUpdate (Integer... values) {int vlaue = values [0]; progressBar. setProgress (vlaue) ;}}/*** simulate network elapsed time **/class NetOperator {public void operator () {try {// sleep Thread for 1 second. sleep (1000);} catch (InterruptedException e) {// TODO Auto-generated catch block e. printStackTrace ();}}}
public class AsyncTaskActivity extends Activity { private Button startTaskBtn;      private ProgressBar progressBar;      private TextView progress_info;            @Override      public void onCreate(Bundle savedInstanceState) {          super.onCreate(savedInstanceState);          setContentView(R.layout.asyntask_layout);                    startTaskBtn = (Button)findViewById(R.id.startTaskBtn);          progressBar = (ProgressBar)findViewById(R.id.progressBar);                progress_info = (TextView)findViewById(R.id.progress_info);                startTaskBtn.setOnClickListener(new OnClickListener() {            @Override              public void onClick(View v) {                  ProgressBarAsyncTask asyncTask = new ProgressBarAsyncTask(progress_info, progressBar);                  asyncTask.execute(1000);              }          });      }  }  

Question 7 Comparison of advantages and disadvantages between Asynctask and Handler + thread)

When thread + Handler is used for asynchronous processing, when a new thread is created for processing each time the time-consuming operation is executed, the performance overhead will be relatively large. If the time-consuming operation is executed for a long time, it is possible that many threads are running at the same time, and the system will be overwhelmed. to improve the performance, we use AsyncTask to Implement Asynchronous processing. In fact, thread + handler is used internally to Implement Asynchronous processing. it only uses the thread pool technology provided by jdk5. it effectively reduces the number of threads created and limits the number of threads running at the same time. There are also some targeted optimization operations on the pool.

AsyncTask requires five threads to run at the same time, and the total thread pool size is 128. That is to say, when we start 10 tasks, only five tasks can be executed immediately, and the other five tasks need to wait. When one task is completed, 6th tasks are started, and so on. The maximum number of threads in the thread pool is 128. When we try to add 129th tasks, the program will crash.

Therefore, in version 3.0, the AsyncTask changes a lot. In AsyncTask before version 3.0, five tasks can be executed at the same time, while in AsyncTask after version 3.0, only one task can be executed at the same time. Why is the number of tasks that can be executed at the same time reduced after the upgrade? This is because the updated AsyncTask has become more flexible. If you do not want to use the default thread pool, you can configure it freely.


AsyncTask
Advantages:
1. simple and fast. You only need to process the business in doInBackground () and update the UI in the onPostExecute () method. The Code hierarchy is simple.
2. When the data of the same asynchronous task is extremely large, the advantages of the thread pool structure such as AsyncTask will be fully reflected.
Disadvantages:
1. The AsyncTask class contains a Global static thread pool. Five available threads are configured by default. If more than five threads exist, they enter the Buffer Queue and wait. A Buffer Queue can contain up to 128 threads.
2. AsyncTask may have the risk of a large number of new threads consuming system resources and causing the application FC (Force Close ).
3. AsyncTask is not suitable for processing a large number of different asynchronous tasks.

Handler
Advantages:
The Handler principle is to simply send a message queue without the resource consumption caused by new threads. It is relatively easy to process complicated asynchronous tasks.
Disadvantages:
Compared with AsyncTask, it seems that there are too many codes, too bloated, too complicated structures, and unclear layers.


Demo: https://github.com/feifei003603/CustomAsyncTask.git
Finally, I have finished sorting out. I am so sleepy. I think some useful friends will give me a comment. If anything is wrong, please make a brick. Please add it!

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.