如何重用已经执行的异步任务? [英] How to reuse an already executing asynctask?

查看:52
本文介绍了如何重用已经执行的异步任务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

场景:用户在 activity1 中单击一个文件名.活动2 被调用,并下载显示进度的文件.

Scenario : In activity1 user clicks a fileName. Activity 2 is invoked and it downloads the file showing progress.

活动2 中存在一个异步任务,其工作是下载和打开文件.

An asynctask exists ,in Activity 2,whose work is to download and open file.

AsyncTask通过各种方法执行以下操作:

AsyncTask does the following things in its various methods:

  • onPreExecute :-打开进度栏.

doInbackground :-启动下载并发送进度更新

doInbackground :- Initiates download and send progress update

onPostExecute :处理 doInBackground 发送的各种返回值.

onPostExecute :-handles various return values sent by doInBackground.

正在下载它的同时也会更新进度.

While it's downloading it also updates the progress.

现在进度条 oncancelable true .因此,当用户按下时,它将返回上一个活动.

Now as the progressbar oncancelable is true .So when the user presses back it goes back to last activity.

但是,当用户在 Activity1 中再次按相同的文件时,如果下载仍在进行,则他应该再次看到进度栏,并发布应执行 onPostExecute .

But when the user presses the same file again in Activity1 either he should see the progress bar again if the download is still going and post that onPostExecute should be executed.

我该怎么办?

谢谢.

推荐答案

创建Asysnc任务的静态对象,并在恢复 Activity

Create a static object of the Asysnc task and check its status on resuming the Activity

static YourAsyncTask backgroundTask;

onCreate()/ onResume()

if(backgroundTask == null)
{
    backgroundTask = new YourAsyncTask();
    backgroundTask.execute();
}
else
{
    if(backgroundTask.getStatus() == AsyncTask.Status.PENDING){
        // AsyncTask has not started yet
    }

    if(backgroundTask.getStatus() == AsyncTask.Status.RUNNING){
        // AsyncTask is currently doing work in doInBackground()
    }

    if(backgroundTask.getStatus() == AsyncTask.Status.FINISHED){
        // AsyncTask is done and onPostExecute was called
    }
}

希望这会有所帮助:)

这篇关于如何重用已经执行的异步任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆