Use of asynctask asynchronous tasks in Android

There was a problem downloading files from the asynchronous task during the interview yesterday. Today, I sorted it out and interested people can have a look. There are two ways about Android's asynchronous mechanism, handler and asynctask. They have their own advantages and disadvantages. Asynctask: directly inherits asynctask, implements asynchronous operations in classes, and provides interface feedback. The current asynchronously executed program becomes complex when multiple asynchronous operations are used and UI changes are required. Handler: for multiple background tasks, it is simple and clear. In a single background asynchronous processing, there is too much code and the structure is relatively complex. No more about handler. Let's take a closer look at asynctask.

Asynctask defines three generic types params, progress and result. Params input parameters for starting task execution, such as the URL of HTTP request. Progress percentage of background task execution. Result the final result returned by the background execution task, such as string.

The execution of an asynchronous task generally includes the following steps: 1.excute (Params....params) performs an asynchronous task, which requires us to call this method in the UI thread and trigger the execution of the asynchronous task. 2. Onpreexcute() this method is called before performing background time-consuming operations to complete initialization preparations. 3. Dioinbackground() is executed immediately after the onpreexcute() method is completed. It is used to perform time-consuming background operations. This method will receive input parameters and return calculation results. During execution, you can call publishprogress (Progress... Values) to update progress information. Onpostexecute (result) 4. Onprogressupdate (Progress... Values) when calling publishprogress (Progress... Values), this method is executed to directly update the progress information to the UI component. 5. Onpostexecute (result) when the background operation ends, this method will be called, and the calculation result will be passed to this method as a parameter to directly display the result on the UI component.

Using the asynctask class, we need to note that the task instance must be created in the UI thread; The execute method must be invoked in UI thread. Do not manually call onpreexecute(), onpostexecute (result), doinbackground (params...), onprogressupdate (Progress...) methods; The task can only be executed once, otherwise an exception will occur when calling multiple times; Here is a simple example of 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         // UI线程中创建AsyncTask的实例
 15         DownTask task = new DownTask(this);
 16         // UI线程中调用execute()方法,这里的URL设置的是打开图片,如果大家想打开网页,会出现无法获得
 17         //总长度,因此无法更新进度条的进度,只能用模拟进度
 18         task.execute(new URL("http://www.baidu.com/img/bdlogo.gif"));
 19     }
 20 
 21     class DownTask extends AsyncTask<URL, Integer, String> {
 22 
 23         // 定义一个Dialog用于显示下载任务
 24         ProgressDialog pDialog;
 25         // 定义记录读取的行数
 26         int hasRead = 0;
 27         Context mContext;
 28         private int totalCount;
 29 
 30         public DownTask(Context ctx) {
 31             mContext = ctx;
 32         }
 33 
 34         @Override
 35         // 后台线程将要完成的任务
 36         protected String doInBackground(URL... params) {
 37             Log.d("TAG", "doInBackground 1");
 38             StringBuffer sb = new StringBuffer();
 39             try {
 40                 URLConnection conn = params[0].openConnection();
 41                 conn.connect();
 42                 totalCount =  conn.getContentLength();
 43                 Log.d("TAG", "doInBackground totalCount:" + totalCount);
 44                 // 打开连接对应的输入流,并将他包装成BufferReader
 45                 BufferedReader bf = new BufferedReader(new InputStreamReader(
 46                         conn.getInputStream(), "utf-8"));
 47                 String line = null;
 48                 while ((line = bf.readLine()) != null) {
 49                     sb.append(line + "\n");
 50                     hasRead++;
 51                     // 用于更新任务的执行
 52                     Log.d("TAG", "doInBackground sb.length():" + sb.length());
 53                     publishProgress(sb.length());
 54                 }
 55             } catch (IOException e) {
 56                 e.printStackTrace();
 57             }
 58             return sb.toString();
 59         }
 60 
 61         @Override
 62         // 在doInBackground()方法执行完后自动执行
 63         protected void onPostExecute(String result) {
 64             Log.d("TAG", "onPostExecute 1");
 65             // 返回html页面内容
 66             show.setText(result);
 67             // 移除对话框
 68             pDialog.dismiss();
 69         }
 70 
 71         @Override
 72         // 在执行后台才做之前调用完成一些初始化的准备
 73         protected void onPreExecute() {
 74             Log.d("TAG", "onPreExecute 1");
 75 
 76             pDialog = new ProgressDialog(mContext);
 77             // 设置对话框的标题
 78             pDialog.setTitle("任务正在执行中");
 79             // 设置对话框的显示内容
 80             pDialog.setMessage("任务正在执行中,请等待");
 81             // 设置对话框不能用“取消”进行关闭
 82             pDialog.setCancelable(false);
 83             // 设置对话框的最大显示进度
 84             pDialog.setMax(100);
 85             // 设置对话框的显示风格
 86             pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
 87             // 设置对话框的进度条是否显示进度
 88             pDialog.setIndeterminate(false);
 89             // 显示对话框
 90             pDialog.show();
 91 
 92         }
 93 
 94         @Override
 95         // 在doInBackground()调用publishProgress()方法后,触发该方法
 96         protected void onProgressUpdate(Integer... values) {
 97             Log.d("TAG", "onProgressUpdate 2");
 98 
 99             // 更新进度
100             show.setText("你已经读取了【" + values[0] + "】行!");
101             pDialog.setProgress((int)(values[0] / (float)totalCount * 100));
102 
103         }
104 
105     }
106 
107 }

Code in XML:

 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 at: https://www.cnblogs.com/hule/p/3458017.html

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>