如何在Android中取消AsyncTask



在我的应用程序中,我有两个AsyncTask方法,当activity转到onPause时,我希望取消此AsyncTask,在onResume中从头开始
我写了下面的代码,我按下主页按钮,应用程序转到onPause,并从最近的应用程序中再次打开此应用程序
我的意思是调用onPauseonResume

但当应用程序再次运行时(来自最近的应用程序(,请调用onResume,但不要从头启动AsyncTask

我的代码:

@Override
protected void onResume() {
super.onResume();
new Handler(getMainLooper()).postDelayed(() -> {
//Get compress or upload
if (bundle == null) {
//Get video from file
getLoadOriginalVideos();
testIsSendPlans = testId;
}
}, 500);
}
@Override
protected void onPause() {
super.onPause();
new GetOriginalVideosAsync().cancel(true);
new GetCompressedVideosAsync().cancel(true);
}
private void getLoadOriginalVideos() {
if (videoList.isEmpty()) {
File directory = new File(Environment.getExternalStorageDirectory() + File.separator + APPDIR);
ArrayList<File> filesList = new ArrayList<File>();
if (directory.isDirectory() && directory.exists()) {
filesList.addAll(Arrays.asList(getOriginalVideos(directory.listFiles())));
}
new GetOriginalVideosAsync().execute(filesList.toArray(new File[filesList.size()]));
}
}
@SuppressLint("StaticFieldLeak")
class GetOriginalVideosAsync extends AsyncTask<File[], Integer, ArrayList<Video>> {
File[] files;
ContentResolver resolver;
GetOriginalVideosAsync() {
resolver = context.getContentResolver();
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onPostExecute(ArrayList<Video> videos) {
Collections.sort(videos, Collections.reverseOrder());
getLastOriginalVideo(addVideos(videos));
}
private ArrayList<Video> addVideos(ArrayList<Video> videos) {
return new ArrayList<>(videos);
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
@Override
protected ArrayList<Video> doInBackground(File[]... arg) {
files = arg[0];
for (File file : files) {
if (!file.isDirectory() && isVideoFile(file.getPath())) {
videoList.add(new Video(file.getName(), file, new Date(file.lastModified())));
}
}
return videoList;
}
}
@SuppressLint("StaticFieldLeak")
class GetCompressedVideosAsync extends AsyncTask<File[], Integer, ArrayList<Video>> {
File[] files;
ContentResolver resolver;
GetCompressedVideosAsync() {
resolver = context.getContentResolver();
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onPostExecute(ArrayList<Video> videos) {
Collections.sort(videos, Collections.reverseOrder());
getLastCompressedVideo(addVideos(videos));
}
private ArrayList<Video> addVideos(ArrayList<Video> videos) {
return new ArrayList<>(videos);
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
@Override
protected ArrayList<Video> doInBackground(File[]... arg) {
files = arg[0];
for (File file : files) {
if (!file.isDirectory() && isVideoFile(file.getPath())) {
videoListCompressed.add(new Video(file.getName(), file, new Date(file.lastModified())));
}
}
return videoListCompressed;
}
}

如何修复它,并且在onResume中从头开始AsyncTasks?

当您取消异步任务时,尽管它被取消了。asyncTask将一直运行,直到doInBackGround((完成其工作。

因此,对于您的GetOriginalVideosAsync,请在doInBackground:中执行此操作

@Override
protected ArrayList<Video> doInBackground(File[]... arg) {
files = arg[0];
for (File file : files) {
//add this
if(isCancelled){
return null;
}
if (!file.isDirectory() && isVideoFile(file.getPath())) {
videoList.add(new Video(file.getName(), file, new Date(file.lastModified())));
}
}
return videoList;
}

对于您的GetCompressedVideosAsync,请在doInBackground:中执行此操作

@Override
protected ArrayList<Video> doInBackground(File[]... arg) {
files = arg[0];
for (File file : files) {
//add this    
if(isCancelled){
return null;
}
if (!file.isDirectory() && isVideoFile(file.getPath())) {
videoListCompressed.add(new Video(file.getName(), file, new Date(file.lastModified())));
}
}
return videoListCompressed;
}

更新

在我告诉你的同一个地方尝试这两项任务:

if(isCancelled){
break;
}

更新2

看你的asyncTaks必须是活动的成员变量

class MyActivity extends ........{
private GetOriginalVideosAsync orginalTask;
private GetCompressedVideosAsync compressedTask;
.......

}

暂停呼叫如下:

@Override
protected void onPause() {
orginalTask.cancel(true);
compressedTask.cancel(true);
super.onPause();
}

private void getLoadOriginalVideos() {
if (videoList.isEmpty()) {
File directory = new File(Environment.getExternalStorageDirectory() + File.separator + APPDIR);
ArrayList<File> filesList = new ArrayList<File>();
if (directory.isDirectory() && directory.exists()) {
filesList.addAll(Arrays.asList(getOriginalVideos(directory.listFiles())));
}
orginalTask =   new GetOriginalVideosAsync();
orginalTask.execute(filesList.toArray(new File[filesList.size()]));
}
}

可以通过调用cancel(布尔值(随时取消任务。调用此方法将导致后续对isCancelled((的调用返回true。调用此方法后,doInBackground(java.lang.Object[](返回后,将调用onCancelled(java.lang.Object(,而不是onPostExecute(java.lang_Object(。为了确保任务尽快取消,如果可能的话(例如在循环中(,您应该始终定期从doInBackground(java.lang.Object[](检查isCancelled((的返回值

来源:https://developer.android.com/reference/android/os/AsyncTask

您在代码中遇到的问题是您正在创建一个新实例,而不是使用您创建的同一实例,您可以通过在类级别而不是方法/块级别声明实例,使实例全局可访问来实现这一点。

问题

...
new GetOriginalVideosAsync().execute(...) 
new GetCompressedVideosAsync().execute(...)
...
super.onPause();
new GetOriginalVideosAsync().cancel(true);
new GetCompressedVideosAsync().cancel(true);
...

正确的方式

...        
getOriginalVideosAsync = new GetOriginalVideosAsync(); // Declare this in class level
getOriginalVideosAsync.execute(...) // replace old execute code with the instance
getCompressedVideosAsync = new GetCompressedVideosAsync(); // Declare this in class level
getCompressedVideoAsync.execute(...) // replace old execute code with the instance
...
super.onPause();
getOriginalVideosAsync().cancel(true);
getCompressedVideosAsync().cancel(true);
...

看看"java全局变量vs局部变量">有更多的理解,希望解释有帮助,干杯。

相关内容

  • 没有找到相关文章

最新更新