AsyncTask的使用总结

    xiaoxiao2021-03-25  98

    在开发Android移动客户端的时候往往要使用多线程来进行操作,我们通常会将耗时的操作放在单独的线程执行,避免其占用主线程而给用户带来不好的用户体验。但是在子线程中无法去操作主线程(UI 线程),在子线程中操作UI线程会出现错误。因此android提供了一个类Handler来在子线程中来更新UI线程,用发消息的机制更新UI界面,呈现给用户。这样就解决了子线程更新UI的问题。但是费时的任务操作总会启动一些匿名的子线程,太多的子线程给系统带来巨大的负担,随之带来一些性能问题。因此android提供了一个工具类AsyncTask,顾名思义异步执行任务。这个AsyncTask生来就是处理一些后台的比较耗时的任务,给用户带来良好用户体验的,从编程的语法上显得优雅了许多,不再需要子线程和Handler就可以完成异步操作并且刷新用户界面。         先大概认识下Android.os.AsyncTask类:        * android的类AsyncTask对线程间通讯进行了包装,提供了简易的编程方式来使后台线程和UI线程进行通讯:后台线程执行异步任务,并把操作结果通知UI线程。        * AsyncTask是抽象类.AsyncTask定义了三种泛型类型 Params,Progress和Result。    * Params 启动任务执行的输入参数,比如HTTP请求的URL。    * Progress 后台任务执行的百分比。     * Result 后台执行任务最终返回的结果,比如String,Integer等。        * AsyncTask的执行分为四个步骤,每一步都对应一个回调方法,开发者需要实现这些方法。    * 1) 继承AsyncTask     * 2) 实现AsyncTask中定义的下面一个或几个方法        * onPreExecute(), 该方法将在执行实际的后台操作前被UI 线程调用。可以在该方法中做一些准备工作,如在界面上显示一个进度条,或者一些控件的实例化,这个方法可以不用实现。        * doInBackground(Params...), 将在onPreExecute 方法执行后马上执行,该方法运行在后台线程中。这里将主要负责执行那些很耗时的后台处理工作。可以调用 publishProgress方法来更新实时的任务进度。该方法是抽象方法,子类必须实现。       * onProgressUpdate(Progress...),在publishProgress方法被调用后,UI 线程将调用这个方法从而在界面上展示任务的进展情况,例如通过一个进度条进行展示。       * onPostExecute(Result), 在doInBackground 执行完成后,onPostExecute 方法将被UI 线程调用,后台的计算结果将通过该方法传递到UI 线程,并且在界面上展示给用户.       * onCancelled(),在用户取消线程操作的时候调用。在主线程中调用onCancelled()的时候调用。 为了正确的使用AsyncTask类,以下是几条必须遵守的准则:       1) Task的实例必须在UI 线程中创建       2) execute方法必须在UI 线程中调用       3) 不要手动的调用onPreExecute(), onPostExecute(Result),doInBackground(Params...), onProgressUpdate(Progress...)这几个方法,需要在UI线程中实例化这个task来调用。       4) 该task只能被执行一次,否则多次调用时将会出现异常       doInBackground方法和onPostExecute的参数必须对应,这两个参数在AsyncTask声明的泛型参数列表中指定,第一个为doInBackground接受的参数,第二个为显示进度的参数,第第三个为doInBackground返回和onPostExecute传入的参数。 下面通过一个Demo来说明如何使用Android.os.AsyncTask类,通过进度条来显示进行的进度,然后用TextView来显示进度值。 main.xml:     android:layout_width="fill_parent"     android:layout_height="fill_parent"     android:orientation="vertical" >             android:id="@+id/textView"         android:layout_width="fill_parent"         android:layout_height="wrap_content"         android:text="@string/hello" />             android:id="@+id/progressBar"         android:layout_width="fill_parent"         android:layout_height="wrap_content"         style="?android:attr/progressBarStyleHorizontal"         /> acitivity代码: package yt.hy.activity; import android.app.Activity; import android.os.AsyncTask; import android.os.Bundle; import android.widget.ProgressBar; import android.widget.TextView; public class AsyncTastActivity extends Activity { ProgressBar progress; TextView textView;     @Override     public void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.main);         progress = (ProgressBar) findViewById(R.id.progressBar);         textView = (TextView) findViewById(R.id.textView);         MyAsyncTask myTask = new MyAsyncTask();         myTask.execute(100);     }          private class MyAsyncTask extends AsyncTask { @Override protected String doInBackground(Integer... params) { for (int i=0; i<=100; i++) { progress.setProgress(i); publishProgress(i, 5); try { Thread.sleep(params[0]); } catch (InterruptedException e) { e.printStackTrace(); } } return "finished"; } //doInBackground返回时触发,换句话说,就是doInBackground执行完后触发 //这里的result就是上面doInBackground执行后的返回值,所以这里是"执行完毕" @Override protected void onPostExecute(String result) { setTitle(result); super.onPostExecute(result); } //这个函数在doInBackground调用publishProgress时触发,虽然调用时只有一个参数 @Override protected void onProgressUpdate(Integer... progress) { textView.setText(String.valueOf(progress[0])); super.onProgressUpdate(progress); }     }      } 网上有人测试过,同种类型的 AsyncTask 实例,最大数量为 20 个。 如果超过,则会引发 RejectExcuteException,并 crash 因此,要考虑到用户的操作是否会引发频繁的 AsyncTask 实例化,若存在,则从 UI 上进行改进,比如: 分页机制; 线程池; 生产者-消费者模型。 2.取消AsyncTask任务 文档已经说明,cancel()方法不一定能成功,所以 onCancel() 回调方法不一定被调用。 但若一个 AsyncTask 结束,则一定会调用 onPostExcute() 方法。 对于一个 doInBackground()方法中含有 while/for 循环时,最好配置 isCancel标置来 break 循环。 这里有一个其他的例子,也挺好的,简单易懂。 package test.list; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.util.ArrayList; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class NetworkActivity extends Activity{     private TextView message;     private Button open;     private EditText url;     @Override     public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.network);        message= (TextView) findViewById(R.id.message);        url= (EditText) findViewById(R.id.url);        open= (Button) findViewById(R.id.open);        open.setOnClickListener(new View.OnClickListener() {            public void onClick(View arg0) {               connect();            }        });     }     private void connect() {         PageTask task = new PageTask(this);         task.execute(url.getText().toString());     }     class PageTask extends AsyncTask{         // 可变长的输入参数,与AsyncTask.exucute()对应         ProgressDialog pdialog;         public PageTask(Context context){             pdialog = new ProgressDialog(context, 0);                pdialog.setButton("cancel", new DialogInterface.OnClickListener() {              public void onClick(DialogInterface dialog, int i) {               dialog.cancel();              }             });             pdialog.setOnCancelListener(new DialogInterface.OnCancelListener() {              public void onCancel(DialogInterface dialog) {               finish();              }             });             pdialog.setCancelable(true);             pdialog.setMax(100);             pdialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);             pdialog.show();         }         @Override         protected String doInBackground(String... params) {             try{                HttpClient client = new DefaultHttpClient();                // params[0]代表连接的url                HttpGet get = new HttpGet(params[0]);                HttpResponse response = client.execute(get);                HttpEntity entity = response.getEntity();                long length = entity.getContentLength();                InputStream is = entity.getContent();                String s = null;                if(is != null) {                    ByteArrayOutputStream baos = new ByteArrayOutputStream();                    byte[] buf = new byte[128];                    int ch = -1;                    int count = 0;                    while((ch = is.read(buf)) != -1) {                       baos.write(buf, 0, ch);                       count += ch;                       if(length > 0) {                           // 如果知道响应的长度,调用publishProgress()更新进度                           publishProgress((int) ((count / (float) length) * 100));                       }                       // 让线程休眠100ms                       Thread.sleep(100);                    }                    s = new String(baos.toByteArray());              }                // 返回结果                return s;             } catch(Exception e) {                e.printStackTrace();             }             return null;         }         @Override         protected void onCancelled() {             super.onCancelled();         }         @Override         protected void onPostExecute(String result) {             // 返回HTML页面的内容             message.setText(result);             pdialog.dismiss();          }         @Override         protected void onPreExecute() {             // 任务启动,可以在这里显示一个对话框,这里简单处理             message.setText(R.string.task_started);         }         @Override         protected void onProgressUpdate(Integer... values) {             // 更新进度               System.out.println(""+values[0]);               message.setText(""+values[0]);               pdialog.setProgress(values[0]);         }      } }
    转载请注明原文地址: https://ju.6miu.com/read-21828.html

    最新回复(0)