A detailed explanation of Asynctask classes in multithreaded programming in Android
1.Android Single Thread model
2. Time-consuming operations are performed in a non-main thread
communication encapsulation class between Android main thread and sub-thread: Asynctask class
1. Updating the UI in a child thread
2. Encapsulate and simplify asynchronous operations.
3.AsyncTask mechanism: The bottom is the line pool work, when a thread is not completed, the following thread is not executed. You must wait for the thread in front of it to finish before the thread executes.
Precautions for using the Asynctask class:
1. Create an instance of Asynctask in the UI thread
2. The Execute () method of Asynctask must be called in the UI thread
3. The four overridden methods are automatically called by the system and should not be called manually.
4. Each asynctask can only be executed once. Multiple calls will throw an exception.
Comparison of Asynctask classes and handler classes in asynchronous tasks:
(1). Asynctask:
Advantages: Simple and quick. Process is controllable.
Cons: When multiple asynchronous task processing makes UI updates, it becomes complex.
(2). Handler class:
Advantages: Clear structure and clear function definition. For multiple background tasks, simple and clear.
Disadvantage: In a single background asynchronous processing, the code is relatively too much.
Here's an example of getting pictures from the web and showing them:
(1). Mainactivity.java class:
PackageCom.chengdong.su.asynctaskdemo;Importandroid.app.Activity;ImportAndroid.os.AsyncTask;ImportAndroid.os.Bundle;ImportAndroid.widget.ImageView;ImportAndroid.widget.ProgressBar;ImportCom.chengdong.su.asynctaskdemo.interfaces.AsyncT;ImportCOM.CHENGDONG.SU.ASYNCTASKDEMO1.R; Public class mainactivity extends Activity { PrivateImageView MView =NULL;PrivateProgressBar Mprogressbar =NULL;PrivateString URL ="Http://pic.nipic.com/2007-11-09/2007119122519868_2.jpg";PrivateAsynct MT =NULL;@Override protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.activity_main); Init (); MT =NewAsynct ( This); Mt.execute (URL); }/** * When the activity exits, task's tasks also exit * / @Override protected void OnPause() {Super. OnPause ();if(MT! =NULL&& mt.getstatus ()! = AsyncTask.Status.FINISHED) {Mt.cancel (true); } }Private void Init() {MView = (ImageView) Findviewbyid (r.id.iv_show); Mprogressbar = (ProgressBar) Findviewbyid (r.id.pb_show); } PublicImageViewGetView() {returnMView; } PublicProgressBarGetprogressbar() {returnMprogressbar; }}
(2). Asynct.java class:
PackageCom.chengdong.su.asynctaskdemo.interfaces;ImportJava.io.BufferedInputStream;ImportJava.io.ByteArrayInputStream;ImportJava.io.IOException;ImportJava.io.InputStream;ImportJava.net.HttpURLConnection;ImportJava.net.MalformedURLException;ImportJava.net.URL;ImportJava.net.URLConnection;Importcom.chengdong.su.asynctaskdemo.MainActivity;ImportAndroid.content.Context;ImportAndroid.graphics.Bitmap;ImportAndroid.graphics.BitmapFactory;ImportAndroid.os.AsyncTask;ImportAndroid.text.TextUtils;ImportAndroid.util.Log;ImportAndroid.view.View;/** * * @author SCD * */Public class asynct extends asynctask<String, Void, Bitmap> { PrivateString TAG ="Asynct";PrivateMainactivity Mcontext;/** * Construction Method * * @param mcontext * *Public asynct (mainactivity mcontext) {Super(); This. Mcontext = Mcontext; }/** * Run in the main thread * / @Override protectedvoid OnPreExecute () {Super. OnPreExecute ();//DisplayMcontext.getprogressbar (). setvisibility (view.visible); }/** * Run in child threads * / @Override protectedBitmap doinbackground (String ... params) {/** * * To implement a page exit, the asynchronous task will also stop, then this needs to be handled according to the business to determine if (iscancelled ()) {} Omitted here is not implemented. **/String URL = params[0]; HttpURLConnection connection =NULL; InputStream in =NULL; Bitmap Bitmap =NULL;//Get pictures from the network Try{//Network connectionConnection = (httpurlconnection)NewURL (URL). OpenConnection ();//Get input streamin = Connection.getinputstream ();//store in the cacheBufferedinputstream bin =NewBufferedinputstream (in);//HibernateThread.Sleep ( the);//parsing the input stream in the cacheBitmap = Bitmapfactory.decodestream (bin);//Turn off Data flowIn.close (); Bin.close ();returnBitmap }Catch(Malformedurlexception e) {E.printstacktrace (); }Catch(IOException e) {E.printstacktrace (); }Catch(Interruptedexception e) {E.printstacktrace (); }return NULL; }/** * Run in UI thread * / @Override protectedvoid OnPostExecute (Bitmap result) {Super. OnPostExecute (Result); Mcontext.getprogressbar (). setvisibility (View.gone); Mcontext.getview (). Setimagebitmap (result); }/** * Run in UI thread * / @Override protectedvoid Onprogressupdate (void ... values) {Super. onprogressupdate (values); }}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Multithreaded Programming in Android (iv) a detailed explanation of the Asynctask class (attached source)