【问题标题】:Getting the return as an int from this AsyncTask从此 AsyncTask 获取作为 int 的返回
【发布时间】:2014-06-08 05:55:16
【问题描述】:

在我的 android 应用程序中,我正在以不同的方式创建 AsyncTask,我想访问返回的整数,以便以后可以使用它。如何获取返回值,因为当我尝试将 myBPM 作为变量调用时,它要求的是 AsyncTask 而不是 int。我将如何获取返回值并将其存储为 int?谢谢

 AsyncTask myBPM = new AsyncTask<Void, Void, Integer>(){

            ...

                return BPM;  //integer value

            }



        }.execute();

【问题讨论】:

    标签: java android android-asynctask return


    【解决方案1】:
    AsyncTask<String, String, Integer> integervalue= new Download().execute("");
    

    和类声明

    public class Download extends AsyncTask<String, String, Integer>{
    
    @Override
    protected Integer doInBackground(String... params) {
        // TODO Auto-generated method stub
    
        int s = 0;
        return s;
    }
    
    }
    

    【讨论】:

      【解决方案2】:

      我不确定我是否明白你的意思,但你可以像这样使用onPostExecute() from AsyncTask

      private class AsyncTaskBPM extends AsyncTask<Void, Void, Integer> {
       protected Integer doInBackground() {
      
           // ...do your stuff
      
           return result
       }
      
       protected void onPostExecute(Integer result) {
           // ...here you can access your result passed as an integer
           // You don't need to return this. You can just proceed in this method.
       }
      

      }

      ps.:代码未经测试。就直接在这里输入了。

      【讨论】:

        【解决方案3】:
        class MyAsync extends AsyncTask<String, String, String>
        {
                @Override
                public String doInBackground(String... params)
                {
                           String str = "4";
                           return str;
                }
        }
        

        无论您在何处调用此异步任务,请遵循以下代码:

        AsyncTask<String, String, String> execute = new MyAsync().execute();
        try
        {
            String string = execute.get();
            System.out.println("Resulted Int :: " +Integer.valueOf(string));
        }
        catch (Exception e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        

        【讨论】:

        • -1,对不起。 .get() 实际上会阻止你的主 UI Thread,它永远不应该被使用。
        • 还没有遇到任何 UI 阻塞问题,执行速度非常快。
        • 也许你没有体验过,但只要onPostExecute() 方法有点复杂,你就会注意到它。面对这种情况,这仍然是一种糟糕的方式。
        猜你喜欢
        • 2012-05-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-09
        • 1970-01-01
        • 2017-06-04
        相关资源
        最近更新 更多