Yesterday, the interview appeared a little problem when asynchronous tasks (AsyncTask) download the file, give it good today sorted out, those who are interested can look at.
About Android asynchronous mechanism, there are two ways, Handler and AsyncTask. They each have their own advantages and disadvantages, AsyncTask: direct successor AsyncTask, asynchronous operation in a class, and provides an interface feedback current asynchronous execution of the program when using multiple asynchronous operations and Ui and the need for change, it becomes complicated . Handler: For a plurality of background tasks, simple, clear, single background when asynchronous processing, it is too much code structure is relatively complicated. About Handler said no, we take a closer look AsyncTask below.
AsyncTask defines three generic types Params, Progress and Result.
Params start input parameters of task execution, such as the HTTP request URL.
Percentage Progress background tasks to perform.
The results Result eventual return of the background tasks, such as String.
Asynchronous execution of a task generally includes the following steps:
1.excute (Params .... params) to perform an asynchronous task, we need to call this method on the UI thread, triggering the execution of asynchronous tasks.
2.onPreExcute () method is called before performing a background time-consuming operation for initialization to complete preparations.
3.dioInbackground () is executed after onPreExcute () method is completed immediately, for performing background operations more time-consuming, this method receives input parameters and returns the results. During execution can call to publishProgress (Progress ... values) update progress information. onPostExecute (the Result the Result)
4.onProgressUpdate (Progress ... values) when calling publishProgress (Progress ... values), this method is executed, will update the progress information directly to the UI components.
5.onPostExecute (Result result) When the background operation, this method will be called, as a result of the calculation of the parameters passed to this method, the results are displayed directly on the UI components.
Use AsyncTask class, we need to note that:
Examples Task must be created in the UI thread;
the Execute method must be called the UI thread;
do not manually call onPreExecute (), onPostExecute (Result) , doInBackground (Params ...), onProgressUpdate (Progress ...) these methods;
this task can only be executed once, otherwise there will be an exception when multiple calls;
Let's look at a simple example AsyncTask:
1 public class AsyncTaskDemo extends Activity { 2 3 private TextView show; 4 5 @Override 6 protected void onCreate(Bundle savedInstanceState) { 7 super.onCreate(savedInstanceState); 8 setContentView(R.layout.activity_main); 9 show = (TextView) findViewById(R.id.show); 10 } 11 12 // 为界面按钮提供响应的方法 13 public void download(View source) throws{MalformedURLException 14 // create an instance of the UI thread AsyncTask 15 DownTask Task = new new DownTask ( the this ); 16 // UI thread calls execute () method, URL here is to open the picture, if you want to open a Web page, will there can not get 17 // total length, and therefore can not update the progress of the progress bar, progress can only simulate 18 task.execute ( new new the URL of ( "http://www.baidu.com/img/bdlogo.gif" )); . 19 } 20 is 21 is class DownTask the extends the AsyncTask <the URL, Integer, String> { 22 is 23 is // define Dialog displays a download task 24 PDialog a ProgressDialog will be; 25 // Number of rows define records read 26 is int hasRead = 0 ; 27 the Context mContext; 28 Private int The totalCount; 29 30 public DownTask (the Context CTX) { 31 is mContext = CTX; 32 } 33 is 34 is @Override 35 / / background thread to be task 36 protected String the doInBackground (the URL ... the params) { 37 [ Log.d ( "the TAG", "the doInBackground. 1" ); 38 is SB = the StringBuffer new new the StringBuffer (); 39 the try { 40 the URLConnection Conn the params = [0 ] .OpenConnection (); 41 is conn.connect (); 42 is The totalCount = conn.getContentLength (); 43 is Log.d ( "the TAG", " the totalCount the doInBackground: "+ the totalCount); 44 is // opening connected to the corresponding input stream, and he packaged into BufferedReader 45 the BufferedReader BF = new new the BufferedReader ( new new the InputStreamReader ( 46 is conn.getInputStream ()," UTF-. 8 " )); 47 String Line = null ; 48 the while ((Line = bf.readLine ()) =! Null ) { 49 sb.append (Line + "\ n-" ); 50 hasRead ++ ; 51 is // perform a task for updating the 52 is the Log 2.d ( "the TAG", "the doInBackground sb.length ():" + sb.length ()); 53 is publishProgress (sb.length ()); 54 is } 55 } the catch (IOException E) { 56 is e.printStackTrace () ; 57 } 58 return sb.toString (); 59 } 60 61 is @Override 62 is // performed automatically performed after the doInBackground () Method 63 is protected void onPostExecute (String Result) { 64 Log.d ( "the TAG", "onPostExecute. 1" ); 65 // returns html page content 66 show.setText (the Result); 67 // remove the box 68 pDialog.dismiss (); 69 } 70 71 @Override 72 // called before the execution was done to complete some background initialization of preparation 73 is protected void onPreExecute () { 74 Log.d ( "the TAG", "onPreExecute. 1" ); 75 76 pDialog = new new a ProgressDialog will be (mContext); 77 // setup dialog header 78 pDialog.setTitle ( "task is executed " ); 79 // Setup dialog box displays the contents of 80 pDialog.setMessage (" the task being performed, wait " ); 81 // Setup dialog box can not be used" in close cancel " 82 pDialog.setCancelable ( false ); 83 // Setup dialog box displays the progress of the maximum 84 pDialog.setMax (100); 85 // setup dialog display style 86 pDialog.setProgressStyle (ProgressDialog.STYLE_HORIZONTAL); 87 // progress bar is displayed progress dialog provided 88 pDialog.setIndeterminate ( to false ); 89 // display the dialog box 90 pDialog. Show (); 91 is 92 } 93 94 @Override 95 // call publishProgress in the doInBackground () () after the process which triggers 96 protected void onProgressUpdate (Integer values ...) { 97 Log.d ( "the TAG", " 2 onProgressUpdate " ); 98 99 // update progress 100 show.setText ( "You've read [" + values [0] + "] line!" ); 101 pDialog.setProgress (( int ) (values [0] / ( float ) totalCount * 100 )); 102 103 } 104 105 } 106 107 }
xml code:
1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 xmlns:tools="http://schemas.android.com/tools" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" 5 android:orientation="vertical" 6 tools:context=".AsyncTaskDemo" > 7 8 <Button 9 android:id="@+id/download" 10 android:layout_width="match_parent" 11 android:layout_height="wrap_content" 12 android:onClick="download" 13 android:text="开始下载" /> 14 15 <TextView 16 android:id="@+id/show" 17 android:layout_width="match_parent" 18 android:layout_height="wrap_content" 19 android:text="获取资源" /> 20 </LinearLayout>
Here are the results:
Reproduced in: https: //www.cnblogs.com/hule/p/3458017.html