前言
在安卓中,UI线程就是程序的主线程,是用来控制程序图形界面的操作的,对图形界面的操作必须在主线程中进行,而网络相关的操作是不允许在安卓主线程中进行的,因此我们需要异步的进行网络操作。实现异步操作有不少办法,下面介绍一种常见的办法:AsyncTask。
AsyncTask是安卓中常用来执行需要与UI进行交互的异步任务的类,它可以在后台处理一些简单的异步任务,并且能够在不使用Thread或Handlers的情况下将异步操作的结果传递给UI。它是被设计用来处理一些耗时相对比较短的任务的,通常处理的操作都是能在几秒内完成的。如果需要处理更长的耗时操作,建议去使用Executor, ThreadPoolExecutor 或者 FutureTask这样的类。
类型
AsyncTask是一个模板类,有三个基本类型:AsyncTask<Params,Progress,Result>
。
Params
: execute
方法传入doInBackground
的参数类型.
Progress
: publishProgress
方法传入onProgressUpdate
的参数类型
Result
: doInBackground
方法的返回值类型,然后将这个返回值作为参数传入onPostExecute
或者onCanceled
这三个类型不是必须的,可以用AsyncTask<Params,Void,Void>
表示只需要第一个类型
用法
AsyncTask是一个抽象类,因此必须通过子类来使用它,可以是建立一个AsyncTask的子类,也可以是建立它的匿名内部类,然后执行execute
方法以启动或者执行cancel
方法来取消已经启动的任务。
AsyncTask提供了五个可以被覆盖的方法:
onPreExecute()
: 调用execute
方法首先在主线程中执行该方法
doInBackground(Params... params)
: 执行完onPreExecute
后在后台线程中执行该异步任务
onProgressUpdate(Progess... progess)
: 通过调用publishProgress
方法后立即在主线程中执行该方法
onPostExecute(Result result)
: doInBackground
方法执行完毕后在主线程中执行该方法
onCanceled(Result result)
: 如果在主线程中执行了cancel()
方法,那么在执行完doInBackground
后就会在主线程中执行该方法,而不会去执行onPostExecute
其中的doInBackground
是必须覆盖的方法,且是唯一一个异步方法。
演示代码:
下面给出一个通过AsyncTask实现自动加载进度条的demo
AndroidManifest.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="org.iflab.www.asynctaskdemo" >
<application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application>
</manifest>
|
MainActivity.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
| package org.iflab.www.asynctaskdemo;
import android.app.Activity; import android.os.AsyncTask; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast;
public class MainActivity extends Activity { private MyAsyncTask myAsyncTask; private TextView textView; private ProgressBar progressBar; private Button startButton, finishButton; private String[] characters = new String[]{"加", "载", "完", "成"};
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); startButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { myAsyncTask.execute(characters);//点击按钮后执行异步任务 } });
finishButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { myAsyncTask.cancel(true);//点击按钮后打断正在进行的异步任务 } }); }
/** * 初始化 */ private void init() { textView = (TextView) findViewById(R.id.progress_text); progressBar = (ProgressBar) findViewById(R.id.progress_bar); startButton = (Button) findViewById(R.id.start_button); finishButton = (Button) findViewById(R.id.finish_button); myAsyncTask=new MyAsyncTask(); }
/** * 自定义的AsyncTask的子类 */ private class MyAsyncTask extends AsyncTask<String, Integer, String> {
/** * 执行异步任务之前在主线程中执行该方法 */ @Override protected void onPreExecute() { textView.setVisibility(View.VISIBLE); textView.setText("0%"); }
/** * 后台线程中执行该异步任务 * * @param params 从execute()中传进来的参数,可以是一组数据也可以是单个数据 * @return 异步任务执行完毕后返回的结果 */ @Override protected String doInBackground(String... params) { String result = ""; int progress; int count = params.length; for (int i = 0; i < count; i++) { try { Thread.sleep(1000);//模拟耗时操作,延时一秒 } catch (InterruptedException e) { e.printStackTrace(); } result = result + params[i]; progress = (int) (((i + 1) / (float) count) * 100);//进度算法 publishProgress(progress);//更新进度 if (isCancelled()) {//如果已经点击了取消,就跳出循环 break; } } return result; }
/** * doInBackground方法执行完毕后在主线程中执行该方法 * * @param result doInBackground()返回的结果 */ @Override protected void onPostExecute(String result) { textView.setText(result); }
/** * 当publishProgress方法被执行后立即在主线程中执行该方法 * * @param values publishProgress方法传进来的参数,一般为进度信息 */ @Override protected void onProgressUpdate(Integer... values) { for (int progress : values) { progressBar.setProgress(progress); textView.setText(progress + "%"); } }
/** * 如果执行了cancel()方法,那么在执行完doInBackground后就会在主线程中执行该方法, * 而不会去执行onPostExecute * * @param result 从doInBackground中返回的result */ @Override protected void onCancelled(String result) { Toast.makeText(getApplicationContext(), "result:" + result, Toast.LENGTH_SHORT).show(); } } }
|
activity_main.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity">
<ProgressBar style="?android:attr/progressBarStyleHorizontal" android:layout_width="match_parent" android:layout_height="50dp" android:id="@+id/progress_bar" android:indeterminate="false" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="139dp" /> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" android:layout_below="@+id/progress_text" android:layout_centerHorizontal="true" android:layout_centerVertical="true" > <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="开始" android:textSize="40sp" android:id="@+id/start_button" />
<Button android:id="@+id/finish_button" android:text="取消" android:textSize="40sp" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>
<TextView android:visibility="gone" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/progress_text" android:textSize="30sp" android:layout_below="@+id/progress_bar" android:layout_centerHorizontal="true" />
</RelativeLayout>
|
注意事项:
- AsyncTask的类必须在主线程中加载,它的对象也只能在主线程中创建,
execute
或cancel
方法也只能在主线程中调用。
- 同一个AsyncTask只能被执行一次,不能取消后再执行它。
参考资料:
http://www.android-doc.com/reference/android/os/AsyncTask.html
(本文系作者原创,转载请注明出处)