【问题标题】:Android: What happens to Async Task return valueAndroid:异步任务返回值会发生什么
【发布时间】:2014-07-10 04:58:43
【问题描述】:

如果已调用的应用程序已完成,返回值或对 Aysnc 任务的调用会发生什么情况。

假设我在 Aysnc 任务中调用了一个网络操作,而我调用它的 UI 线程已经完成了该操作。

我的目标是保存 N/W 通话中收到的数据,以便下次我需要重新通话?

下面是代码 sn-p,在 doInBackground() 中我发出 SOAP 请求,当请求打开时,调用 Aync 任务的主 UI 不知何故死亡/完成。我的回复会怎样?如何保存响应以供将来使用。

    Code:

        class SOAPCallAyncTask1 extends AsyncTask<String, String, String> {

    ProgressDialog pd = null;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pd = new ProgressDialog(SoapMainActivity.this);
        pd.setMessage("Please wait...");
        pd.setCancelable(false);
        pd.show();

    }

    @Override
    protected String doInBackground(String... params) {

        String theResult = "";
        byte[] result = null;

        try {
            result = callSOAPServer();
            theResult = new String(result);
            Log.d("R-Doit in backgound", theResult);
        }

        catch (Exception e) {
            e.printStackTrace();
        }

        return theResult;
    }

    @Override
    protected void onPostExecute(String theResult) {
        super.onPostExecute(theResult);
        pd.dismiss();
        Log.d("R-Result", theResult);
    }

}

【问题讨论】:

  • 你可以在异步任务的后期执行中保存数据
  • 你能分享一些你的 AsyncTask 代码吗?
  • 我不完全确定你的意思。但是如果你取消 AsyncTask,它会完成它的后台工作,尽管onPostExecute 不会发生。
  • 您可以根据需要将数据保存在任何变量、共享首选项或数据库中,以及在 doInBackground 或 onPostExecute 中的大小
  • @Marius:如果调用者死了,后执行还会被调用吗?

标签: android android-asynctask android-async-http


【解决方案1】:

即使应用程序关闭/销毁,AsyncTask 也会完成执行,除非系统要求它停止执行(通常情况并非如此)。

您可以将在网络调用中收到的数据保存在 SharedPreferences 中,然后通过从SharedPreferences。如果您发现在上次执行 AsyncTask 期间未获取任何数据,您可以相应地发出新的执行请求。

【讨论】:

  • 你说,如果我在 PostExecute() 方法中处理我的数据,无论应用程序的状态如何,都会调用 postExecute()。让我试试然后回复你
  • @Learner 是的。它仍然会被调用。
猜你喜欢
  • 2015-07-10
  • 2019-04-29
  • 2013-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-14
  • 1970-01-01
相关资源
最近更新 更多