【问题标题】:AsyncTask Update Progress without a loop没有循环的 AsyncTask 更新进度
【发布时间】:2018-02-23 11:40:06
【问题描述】:

我有一个异步任务,在 doInBackground 内部,我没有 for/while 循环。相反,我有一个不同的类,该类使用 for 循环生成一个列表。那么如何使用 onProgressUpdate 更新 UI?

这里是:

@Override
protected List<MyObject> doInBackground(Void... voids) {
    IAppLogic appLogic = new AppLogic(mContext);
    List<MyObject> list =  appLogic.getApps(ALL_APPS);

    return list;
}

MyObject 是一个自定义对象,而 IAppLogic 是获取已安装应用程序的类的接口。

【问题讨论】:

  • 您是否允许/能够更改AppLogic.getApps?是什么让您无法简单地将这种逻辑放入任务中?
  • 我被允许并且有能力,但我在 ui 级别执行异步任务,我还想单独保留 UI 和 Logic。

标签: android android-asynctask async-onprogressupdate


【解决方案1】:

您可以通过给getApps()-方法一个回调参数来实现这一点。伪代码:

interface AppFoundCallback {
    public onAppFound(App app, int progress);
}

// in AppLogic.getApps:
public getApps(String filter, AppFoundCallback callback)
    for (int i = 0; i < listOfApps.length; i++) {
        // Do the work you need to do here.
        int progress = (i / listOfApps.length) * 100;
        callback.onAppFound(app, progress);
    }
}

// in your Task:
class Task extends AsyncTask implements AppFoundCallback {

    // Implement the callback
    @Override
    onAppFound(App app, int progress) {
        this.publishProgress(progress);    
    }

    // Setup and register the listener
    @Override
    protected void doInBackground() {
        // Ohter stuff
        List<MyObject> list =  appLogic.getApps(ALL_APPS, this);
    }

    // Render progress updates on the UI
    @Override
    protected void onProgressUpdate(Integer... progress) {
        progressView.setProgress(progress[0]);
    }    

}

简单地说:你的代码在你每次找到东西时都会通知调用者getApps()-方法。然后,这将作为进度更新发布。 publishProgress()-方法是 AsyncTask 的一部分,将负责在 UI 线程上调用 onProgressUpdate(),以便您可以简单地更新您的视图。

【讨论】:

    猜你喜欢
    • 2019-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多