java - 从位于异步任务 doInBackGround 中的回调返回一个值

标签 java android android-asynctask callback

我有以下代码:

这里是 asyncHttp 文档的链接: Link

这就是调用登录任务:

mAuthTask = new UserLoginTask();
mAuthTask.execute((Void) null);

这里是 android 模板 Activity 提供的异步任务:

    public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
    @Override
    protected Boolean doInBackground(Void... params) {
        // TODO: attempt authentication against a network service.

        Network.login(mEmail, mPassword, new AsyncHttpResponseHandler() {

            @Override
            public void onSuccess(int statusCode, Header[] headers,
                    byte[] responseBody) {

                if (statusCode == 200) {
                    // Successfully got a response
                    for (int i = 0; i < headers.length; i++) {
                        if (headers[i].getName().equalsIgnoreCase("token")) {
                            // Set the token to the received value
                            Network.SetToken(headers[i].getValue());
                    // >>>>>>>      return true;   <<<<<<<<<
                        }
                    }
                }
                // >>>>> return false  <<<<<<<<<<<<

            }

            @Override
            public void onFailure(int statusCode, Header[] headers,
                    byte[] responseBody, Throwable error) {
                // Response failed :(
                  //     >>>>>>>>>>>>>>>>>> return false <<<<<<<<<<<<<
            }           
        });

        // TODO: register the new account here.
        return true;
    }

    @Override
    protected void onPostExecute(final Boolean success) {
        mAuthTask = null;
        showProgress(false);

        if (success) {
            finish();
        } else {
            mPasswordView
                    .setError(getString(R.string.error_incorrect_password));
            mPasswordView.requestFocus();
        }
    }

如何从我的 AsyncHttpResponseHandler 中返回 true 或 false,然后将该值返回给异步任务?这样它就可以成功执行它的 on post 方法。

我只能想到设置变量然后阻塞它。但是那个失败主义者认为它是异步的,我宁愿远离它。

最佳答案

来自开发者文档

AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few seconds at the most.)

现在说如果你真的想在 onPostExecute 中完成,你可以这样做

public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
    @Override
    protected Boolean doInBackground(Void... params) {
        // TODO: attempt authentication against a network service.

        final ResponseContainer responseContainer = new ResponseContainer();
        Network.login(mEmail, mPassword, new AsyncHttpResponseHandler() {

            @Override
            public void onSuccess(int statusCode, Header[] headers,
                    byte[] responseBody) {

                if (statusCode == 200) {
                    // Successfully got a response
                    for (int i = 0; i < headers.length; i++) {
                        if (headers[i].getName().equalsIgnoreCase("token")) {
                            // Set the token to the received value
                            Network.SetToken(headers[i].getValue());
                    // >>>>>>>      return true;   <<<<<<<<<
                            responseContainer.result = true;
                        }
                    }
                }
                // >>>>> return false  <<<<<<<<<<<<
                responseContainer.result = false;
            }

            @Override
            public void onFailure(int statusCode, Header[] headers,
                    byte[] responseBody, Throwable error) {
                // Response failed :(
                  //     >>>>>>>>>>>>>>>>>> return false <<<<<<<<<<<<<
                responseContainer.result = false;
            }           
        });

        // TODO: register the new account here.
        return responseContainer.result;
    }

    @Override
    protected void onPostExecute(final Boolean success) {
        mAuthTask = null;
        showProgress(false);

        if (success) {
            finish();
        } else {
            mPasswordView
                    .setError(getString(R.string.error_incorrect_password));
            mPasswordView.requestFocus();
        }
    }

    private class ResponseContainer {
        public boolean result;
    }
}

关于java - 从位于异步任务 doInBackGround 中的回调返回一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22245815/

相关文章:

java - J面板: how to add buttons above table?

Android 覆盖错误 - 它们是什么意思?

android - 异步任务后更新 ListFragment

java - 安卓:“BadTokenException:无法添加窗口;你的 Activity 在运行吗?

android - 在 Android 中的 AsyncTask 之后更新 CustomArrayAdapter

java - Generic ObjectPool - 如何返回一个通用类?

java - SpringMVC、MySQL动态查询

javascript - react native ListView 项目 ZIndex

java - 带连接的 JPA 标准构建器包装器

java - 安卓 Java : Activity called AFTER onPause( )