【问题标题】:Multithreading in Async异步中的多线程
【发布时间】:2012-05-09 08:26:55
【问题描述】:
  1. 我有一个名为“A 类”的类 a) 我有一个叫做验证的按钮 b) onClick 验证我调用 auth.authenticate() 返回布尔值 c) 在真实情况下 - 我必须调用一个意图

  2. authentication 函数在另一个类中(auth 是一个 ref)

  3. 认证函数如下()

布尔验证(){

 new AsyncTask<String, String, String>() {      

    preExecute()
    {
       --starting a progress bar--
    }
    doInBackground(String )
    {
        ----  huge authentication code-----
        ------ returns true or false -------isVerified

    }
    onPostExecute(String)
    {
            ---   dismiss progress bar-----------
    }       
    }.execute();
    }

  --------end of AsynTask block----

  synchronized (this) {

        try {
            this.wait();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

return isVerified; ---- this should return to MyClass - after async finishes

--但是这是在异步完成之前返回的。实际上它是正确的-因为这些是线程-并行运行,因此要使其工作-我一直等到异步使用该同步块完成-但这将阻塞我的主线程-(也没有进度条)

我可以在执行后成功调用我的下一个活动 - 因为我正在制作一个库类..我认为不应该......请帮助

}

【问题讨论】:

    标签: android multithreading asynchronous android-asynctask


    【解决方案1】:

    您可以覆盖onPostExecute() 并从那里返回您的值,如果任务被取消,它将不会被调用。

    【讨论】:

    • 但是Chis,同时“return isVerified”将运行,而与 onPostExecute return 无关..
    • 从 doInBackground() 返回的值被传递给 onPostExecute() 这不会直接被其余代码看到。请参阅 AsyncTask 的文档。
    【解决方案2】:

    AsyncTasks 也是线程。因此,您可以创建一个新的AuthenticateAsyncTask&lt;Void,Void,Void&gt; 类进行身份验证,并覆盖onPostExecute 方法,您可以使用参数isVerified 调用函数

    例如:

    boolean isVerified;
    
    // Async Task
    class AuthenticateAsyncTask extends AsyncTask<Void, Void, Void>{
        @Override
        protected Void doInBackground(Void... params) {
            // Authentication
            isVerified = returningValue // set your isVerified variable
            return null;
        }
    
        @Override
        protected void onPostExecute(Void result) {
            // you can here call a function that indicates the authenticaion value is returned
        }
    
        @Override
        protected void onPreExecute() {}
    
    }
    

    希望对你有帮助

    【讨论】:

    • 您好 Nafiz,感谢您查看它...而不是您编写的类,我在一个名为 authenticate 的函数中有一个匿名类 - authenticate 将返回 true 或 false 而无需等待该异步完成..这就是问题..我已经同步等待 - 这样我就可以等到异步完成..但这会阻塞我的线程。
    • 那么在 doInBackground() 函数中调用该验证函数怎么样? - 开始验证 AsyncTask - 在 doInBackground 中调用验证函数 - 当验证函数返回时,将调用 asyncTask 的 onPostExecute 方法 - 您可以等到 asyncTask 的 onPostExecute() 方法被执行。
    • 我正在寻找的是 - 如何在不阻塞 UI 线程的情况下等待另一个线程(或异步)完成.. this.wait() 将阻塞线程..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-14
    • 2015-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多