/** * Crazyandcoder * Contact: * QQ : 275137657 * Email: [Email protected] * Reprint please indicate the source! */
Asynchronous Task Asynctask Use
The implementation of the asynchronous mechanism in Android mainly has the thread plus handler and Asynctask, today the main record of asynctask learning process. For future needs.
First, the construction of Asynctask sub-class of the number of references
Asynctask<params,progress,result> is an abstract class.
Pass is often used to be inherited, inheriting asynctask need to specify such as the following three generic parameters.
- Params: Enter the type of the parameter when the task is started.
- Progress: The type of progress during a background task run.
- Result: The type of the result returned when the background run task finishes.
Second, the realization asynctask need to rewrite the method
when an asynchronous task runs, you typically need to implement 4 methods:
- Onpreexcute: It is usually the user completes some UI initialization operation. such as loading a progress bar.
- Doinbackground (Params ...) : Run this method immediately after the call Onpreexcute (), mainly in the background to do some time-consuming operation, in this method can call Publishprogress (Progress ...) To show the progress of the task already running.
- Onprogressupdate (Progress ...) : Calling the Publicprogress method in the Doinbackground () method triggers the operation of the method and is used for the UI component to show the progress of the task running in real time.
- Onpostexcute (): This method is called when the background task is finished, and the results returned by the background run task are passed to this method as a parameter, showing updates in the UI main thread.
Iii. Calling Rules
Threading rules There is a few threading rules that must being followed for this class to work properly: 1, the Async Task class must is loaded on the UI thread. This is the done automatically as of Jelly_bean. 2, the task instance must is created on the UI thread. 3. Execute (Params ...) must is invoked on the UI thread. 4. Do not call OnPreExecute (), OnPostExecute (Result), Doinbackground (Params ...), Onprogressupdate (Progress ...) manually. 5. The task can be executed only once (an exception would be thrown if a second execution is attempted.)
It's probably meant to mean:
- You must create an instance of Asynctask in the main thread of the UI.
- The Excute () method must be called in the main thread of the UI.
- There is no need to manually invoke Onpreexcute,doinbackground,onprogressupdate,onpostexcute four methods.
- A Asynctask instance can only run a task.
Iv. Examples of demoLet's look at the effect first and then explain the detailed implementation process.
This demo mainly realizes the asynchronous loading of a network picture, and in the loading process shows the load progress percentage, mainly related to some IO operations and network requests and other knowledge points.
Fig. 1 Fig. 2 Fig. 3
Figure 1 shows the feature. The main is to click on the button to enter the network image page;
Figure 2 shows the percentage of progress in the process of loading a network picture;
Figure 3 shows the network picture to load when the load progress percentage is 100%.
Let's examine the detailed implementation code below:
The layout of the main interface is not affixed, mainly a button buttons, and then in the mainactivity to achieve page jump, we mainly look at how to implement the Imagetest.class in the network image.
The first is the XML layout, which is very easy to layout. A ImageView component displays a network picture, and a ProgressBar component is used to display the progress of the run. A textview is used to display the progress percentage of the load. The layout is implemented with Relativelayout.
<?XML version= "1.0" encoding= "Utf-8"?
><relativelayout xmlns:android= "http://schemas.android.com/apk/res/android" android:layout_width= " Match_parent " android:layout_height=" match_parent "> <imageview android:id=" @+id/imageview1 " android:layout_width= "match_parent" android:layout_height= "match_parent" /> < ProgressBar android:id= "@+id/progress" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" android:layout_centerinparent= "true" android:visibility= "Gone" /> < TextView android:id= "@+id/mtextprogress" android:layout_width= "wrap_content" android:layout_ height= "Wrap_content" android:text= "15%" android:layout_centerinparent= "true" android:textsize= "13sp" /></relativelayout>
Then there is the Imagetest.class, which is mainly the subject code that loads the network picture. Everything in the code is clearly written. directly on the code.
Package Com.example.asynctaskdemo;import Java.io.bufferedinputstream;import Java.io.ioexception;import Java.io.inputstream;import Java.io.outputstream;import Java.net.httpurlconnection;import Java.net.malformedurlexception;import Java.net.url;import Android.app.activity;import Android.graphics.Bitmap; Import Android.graphics.bitmapfactory;import android.nfc.tag;import android.os.asynctask;import android.os.Bundle; Import Android.util.log;import android.view.view;import Android.widget.imageview;import Android.widget.ProgressBar Import Android.widget.textview;import android.widget.toast;/** * Display a picture of the web * * @author crazyandcoder * @date [2015-8-9 pm 4:11:27] */public class Imagetest extends Activity {private String TAG = "Imagetest.class";p rivate ImageView MIMAGEVIEW;PR Ivate ProgressBar mprogressbar;private TextView mtextprogress;private myasynctaskshowimg mtask;private static String Mimgurl = "Http://h.hiphotos.baidu.com/image/pic/item/9922720e0cf3d7ca14dcc750f71fbe096b63a9ea.jpg"; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.image); Initview (); mtask = new Myasynctaskshowimg (); Mtask.execute (Mimgurl);} private void Initview () {mtextprogress = (TextView) Findviewbyid (r.id.mtextprogress); Mimageview = (ImageView) Findviewbyid (r.id.imageview1); Mprogressbar = (ProgressBar) Findviewbyid (r.id.progress);} Class Myasynctaskshowimg extends Asynctask<string, Integer, bitmap> {/** * Initialize UI control * * @see Android.os.asynctask#on PreExecute () */@Overrideprotected void OnPreExecute () {super.onpreexecute (); Mprogressbar.setvisibility ( view.visible); Mtextprogress.settext ("0%");} /** * Run complex time-consuming tasks * * @param params * @return * @see android.os.asynctask#doinbackground (params[]) */@Overrideprotected Bit Map Doinbackground (String ... params) {//The address of the picture in the network string mimgurl = Params[0]; String mfilename = "Temp_pic"; LOG.D (TAG, "Mimgurl is" + mimgurl);//The image in the network is finally converted to the bitmap type returned to ImageView display bitmap Mbitmap = null;//The input stream to get the data InputStream is = Null;outputstream out = null; HttpURLConnection Connection;try {//Converts the network picture address stream to the bitmap type connection = (httpurlconnection) new URL (Mimgurl). OpenConnection (); Connection.setdoinput (true); Connection.setdooutput (false);// Set Link Timeout time connection.setconnecttimeout (+); is = Connection.getinputstream (); out = Openfileoutput (Mfilename, MODE _private); byte[] data = new byte[1024];//The length of each read int seg = 0;//data size Long totalsize = Connection.getcontentlength (); LOG.D (TAG, "total size is" + totalsize);//Today's progress long current = 0;//while (! Mtask.iscancelled ()) && (seg = is.read (data))! =-1) {//The current total progress is now + = SEG; LOG.D (TAG, "current size was" + current);//download percent int progress = (int) ((float) current/totalsize * 100); LOG.D (TAG, "Progress size is" + progress);//Notification Update Progress publishprogress (progress); Out.write (data, 0, SEG);} Mbitmap = Bitmapfactory.decodefile (Getfilestreampath (mfilename). GetAbsolutePath ()); LOG.D (TAG, "file is" + Getfilestreampath (mfilename). GetAbsolutePath ()); Connection.disconneCT (); is.close (); Out.close ();} catch (Malformedurlexception e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ();} return mbitmap;} /** * shows the progress of loading pictures from the network * * @param values * @see android.os.asynctask#onprogressupdate (progress[]) */@Overrideprotected void Onprogressupdate (Integer ... values) {super.onprogressupdate (values); Mtextprogress.settext (Values[0] + "%");} /** * Returns the result of running in Doinbackground to the method for updating the UI control * @param result * @see Android.os.asynctask#onpostexecute (java.lang.Object ) */@Overrideprotected void OnPostExecute (Bitmap result) {Super.onpostexecute (result); Mprogressbar.setvisibility ( View.gone); Mtextprogress.setvisibility (View.gone); Mimageview.setimagebitmap (result); Toast.maketext (imagetest.this, "Picture loading complete.", Toast.length_long). Show ();}} @Overrideprotected void OnPause () {super.onpause (); if (mtask! = null && mtask.getstatus () = = AsyncTask.Status.RUNNING) {The//cancel method simply marks the corresponding state of Asynctask as the cancel state, not the true cancel Mtask.cancel (true);}}}
The code is very easy. Look at the gaze and it should be clear.
Finally attach the source code:
Android Asynctask use