如何在Android中取消正在执行的AsyncTask?
在进入示例之前,我们应该了解Android中的AsyncTask是什么。AsyncTask将在后台线程中执行操作/动作并在主线程上更新。在后台线程上执行后台操作时,用户可以使用以下代码取消操作 -
AsynTaskExample mAsyncTask = new AsyncTaskExample(); mAsyncTask.cancel(true);
此示例演示了如何在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>
在上面的代码中,当您单击按钮时,它将从互联网源下载图像并追加到ImageView。
步骤 3 − 将以下代码添加到src/MainActivity.java
package com.example.andy.myapplication;
import android.app.ProgressDialog;
import android.content.DialogInterface;
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 android.widget.Toast;
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;
AsyncTaskExample asyncTask = 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) {
asyncTask = new AsyncTaskExample();
asyncTask.execute("https://tutorialspoint.com/images/tp-logo-diamond.png");
}
});
}
private class AsyncTaskExample extends AsyncTask {
@Override
protected void onPreExecute() {
super.onPreExecute();
p = new ProgressDialog(MainActivity.this);
p.setMessage("Please wait...It is downloading");
p.setIndeterminate(true);
p.setCancelable(true);
p.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
asyncTask.cancel(true);
Toast.makeText(MainActivity.this,"AsyncTask is stopped",Toast.LENGTH_LONG).show();
}
});
p.show();
}
@Override
protected Bitmap doInBackground(String... strings) {
try {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
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();
}
}
}
}步骤 4− 将以下代码添加到manifest.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>
在上面的代码中,我们已授予互联网权限以从互联网源获取图像。
让我们尝试运行您的应用程序。我假设您已将您的实际Android移动设备连接到您的计算机。要从Android Studio运行应用程序,请打开您的一个项目活动文件,然后单击运行
工具栏中的图标。选择您的移动设备作为选项,然后检查您的移动设备,它将显示您的默认屏幕 -

当您单击上面的按钮时,它将启动一个进度条,单击进度条以外的任何位置,它将显示以下屏幕。

上面的屏幕清楚地显示了异步任务已停止,并且图像现在已从互联网源下载。

如果您不停止异步任务,它将下载如上所示的图像
点击 这里 下载项目代码
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP