Android AsyncTask 示例与讲解
Android AsyncTask 用于在后台线程执行后台操作并在主线程更新UI。在 Android 开发中,我们不能直接从后台线程访问主线程。AsyncTask 帮助我们在后台线程和主线程之间进行通信。
AsyncTask 的方法
onPreExecute() − 在执行后台操作之前,我们应该在屏幕上显示一些内容,例如进度条或动画。我们可以直接使用 doInBackground() 方法进行后台操作,但最佳实践是调用所有 AsyncTask 方法。
doInBackground(Params) − 在此方法中,我们必须在后台线程执行后台操作。此方法中的操作不应访问任何主线程活动或片段。
onProgressUpdate(Progress…) − 在执行后台操作时,如果要更新UI上的某些信息,可以使用此方法。
onPostExecute(Result) − 在此方法中,我们可以更新后台操作结果的UI。
AsyncTask 中的泛型
TypeOfVarArgParams − 它包含有关用于执行的参数类型的信息。
ProgressValue − 它包含有关进度单元的信息。在执行后台操作时,我们可以使用 onProgressUpdate() 方法更新UI上的信息。
ResultValue − 它包含有关结果类型的信息。
此示例演示如何在 Android 中使用 AsyncTask。
步骤 1 − 在 Android Studio 中创建一个新项目,转到文件 ⇒ 新建项目,然后填写所有必需的详细信息以创建一个新项目。
步骤 2 − 将以下代码添加到 res/layout/activity_main.xml。
<?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:tools = "http://schemas.android.com/tools" android:id = "@+id/rootview" android:layout_width = "match_parent" android:layout_height = "match_parent" android:orientation = "vertical" android:background = "#c1c1c1" android:gravity = "center_horizontal" tools:context = ".MainActivity"> <Button android:id = "@+id/asyncTask" android:text = "Download" android:layout_width = "wrap_content" android:layout_height = "wrap_content" /> <ImageView android:id = "@+id/image" android:layout_width = "300dp" android:layout_height = "300dp" /> </LinearLayout>
在上面的 xml 中,我们创建了一个按钮,当用户单击该按钮时,它将下载图像并将图像添加到 ImageView。
步骤 3 − 将以下代码添加到 src/MainActivity.java
package com.example.andy.myapplication;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
URL ImageUrl = null;
InputStream is = null;
Bitmap bmImg = null;
ImageView imageView= null;
ProgressDialog p;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button=findViewById(R.id.asyncTask);
imageView=findViewById(R.id.image);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AsyncTaskExample asyncTask=new AsyncTaskExample();
asyncTask.execute("https://tutorialspoint.com/images/tp-logo-diamond.png");
}
});
}
private class AsyncTaskExample extends AsyncTask<String, String, Bitmap> {
@Override
protected void onPreExecute() {
super.onPreExecute();
p = new ProgressDialog(MainActivity.this);
p.setMessage("Please wait...It is downloading");
p.setIndeterminate(false);
p.setCancelable(false);
p.show();
}
@Override
protected Bitmap doInBackground(String... strings) {
try {
ImageUrl = new URL(strings[0]);
HttpURLConnection conn = (HttpURLConnection) ImageUrl.openConnection();
conn.setDoInput(true);
conn.connect();
is = conn.getInputStream();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.RGB_565;
bmImg = BitmapFactory.decodeStream(is, null, options);
} catch (IOException e) {
e.printStackTrace();
}
return bmImg;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
if(imageView!=null) {
p.hide();
imageView.setImageBitmap(bitmap);
}else {
p.show();
}
}
}
}在上面的代码中,我们使用 AsyncTask 下载图像并将图像添加到 ImageView。
步骤 4 − 将以下代码添加到 AndroidManifest.xml
<?xml version = "1.0" encoding = "utf-8"?> <manifest xmlns:android = "http://schemas.android.com/apk/res/android" package = "com.example.andy.myapplication"> <uses-permission android:name = "android.permission.INTERNET"/> <application android:allowBackup = "true" android:icon = "@mipmap/ic_launcher" android:label = "@string/app_name" android:roundIcon = "@mipmap/ic_launcher_round" android:supportsRtl = "true" android:theme = "@style/AppTheme"> <activity android:name = ".MainActivity"> <intent-filter> <action android:name = "android.intent.action.MAIN" /> <category android:name = "android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
在上面的 AndroidManifest.xml 文件中,我们添加了 internet 权限以访问互联网以下载图像。
让我们尝试运行您的应用程序。我假设您已将您的实际 Android 移动设备连接到您的计算机。要从 Android Studio 运行应用程序,请打开您的一个项目活动文件,然后单击工具栏中的运行 Eclipse 运行图标。选择您的移动设备作为选项,然后检查您的移动设备,它将显示您的默认屏幕。

现在单击下载按钮,它将在 UI 上显示进度并在后台下载图像,如下所示

下载图像后,它将在 UI 上更新,如下所示

点击这里下载项目代码
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP