【问题标题】:Passing parameters with AsyncTask使用 AsyncTask 传递参数
【发布时间】:2014-05-23 20:04:34
【问题描述】:

关于主题,正如 google/android 文档所说:

// Params, the type of the parameters sent to the task upon execution.
// Progress, the type of the progress units published during the background
// computation.
// Result, the type of the result of the background computation.

我已经使用过几次 AsyncTask 但总是对如何使用它传递/返回参数有一些疑问(通常使用多线程:)。我熟悉 AsyncTask 文档,但想知道我传递上下文/意图参数的方式是否正确,或者我应该使用<Params, Progress, Result>.. 进行此操作:

class CameraStarterTask extends AsyncTask<Void, Void, Void> {

    private Context context;
    private Intent intent;

    public void CameraStarter(Context context, Intent intent) {
        this.context = context;
        this.intent = intent;
    }

    @Override
    protected Void doInBackground(Void... params) {
        // TODO Auto-generated method stub
        return null;
    }

}

【问题讨论】:

  • 都是一样的。您甚至不能同时多次执行同一个 AsyncTask 实例,因此使用哪种方法来传递参数实际上并没有区别。
  • 好的,我为此使用了另一种方法:mHandler.postDelayed(new CameraStarter(context, intent), 7000);

标签: java android multithreading android-asynctask


【解决方案1】:

这是您的决定。 AsyncTask 只是为您提供了一种通过不同线程实例(一个后台线程和 UI 线程)传递参数的通用方式。如果您认为它更适合您,您甚至可以自己做这些事情。

就像启动一个后台新线程并在其 Runnable 中在 UI 元素/您的 Activity/Handler 等上发布另一个 Runnable。

您知道按照自己的方式使用它是可以的。只要确保你在配置更改发生时考虑过所有事情,但你可能知道这些东西或找到足够的教程。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-29
    • 2012-05-29
    • 2020-08-18
    • 2011-08-28
    • 2011-05-10
    • 2011-03-05
    • 1970-01-01
    相关资源
    最近更新 更多