Android开发——异步网络的请求(AsyncTask)
AsyncTask的解释
- 由于目前的Android已经不允许在UI线程中进行网络请求了,所以现在进行网络请求等较为耗时的操作都需要开辟新的线程来运行。否则有可能会造成ANR错误。而Asynctask便是解决这个问题的一种方法。
- 在源码中注释对AsyncTask类进行这样的解释
* <p>AsyncTask enables proper and easy use of the UI thread. This class allows you
* to perform background operations and publish results on the UI thread without
* having to manipulate threads and/or handlers.</p>
*
* <p>AsyncTask is designed to be a helper class around {@link Thread} and {@link Handler}
* and does not constitute a generic threading framework. AsyncTasks should ideally be
* used for short operations (a few seconds at the most.) If you need to keep threads
* running for long periods of time, it is highly recommended you use the various APIs
* provided by the <code>java.util.concurrent</code> package such as {@link Executor},
* {@link ThreadPoolExecutor} and {@link FutureTask}.</p>
大致意思是说这个类能帮助你更好的处理UI线程,可以让你在UI线程上执行后台的操作进而不会阻塞UI线程,而且不需要多个线程和Handler来处理结果。
但是AsyncTask这个类更适合做短时间的请求,最多就是几秒钟,如果是长时间的操作极不建议使用这个类。
AsyncTask的使用
-
AsyncTask<Params, Progress, Result>的三个参数
- Params: 表示执行时传入的参数的类型, 而且在doInBackground方法中的参数是(Params… params),即支持多个参数。
- Progress:表示的时候进度的类型
- Result:表示的预期返回结果的类型
-
AsyncTask的状态
这里面最重要的方法是doInBackground()方法。
在UI线程中调用execute()方法进入onPre方法(在进行后台操作之前对UI线程进行操作)中,再到doInBackground方法(可以进行一些网络操作)中,在后台操作结束的时候进入onPost方法(在进行后台操作之后对UI线程进行操作)。
如果在doInBackground方法中调用了publishProgress方法那么也会吧Update方法拉起来。
图中黄色是UI线程的操作;蓝色是非UI线程的操作。 -
实例
class RequestNetworkDataTask extends AsyncTask<String, Integer, String>{
//在进行后台处理之前
@Override
protected void onPreExecute() {
super.onPreExecute();
//操作主线程
}
@Override
protected String doInBackground(String[] params) {
//requestData方法为请求的具体操作
String result = requestData(params[0]);
return result;
}
//在后台处理结束之后
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
result.setText(s);
//操作主线程
}
@Override
protected void onCancelled() {
super.onCancelled();
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
}