【问题标题】:Android: How to implement callback on async task which fetch Google token?Android:如何在获取 Google 令牌的异步任务上实现回调?
【发布时间】:2015-08-31 12:11:48
【问题描述】:

我正在尝试在我的应用上实现 google 登录。我设法登录并存储令牌,但由于任务是异步的,我不知道它何时完成,因此我无法在进一步的方法中安全地使用令牌。如何向 onPostExecute 添加回调方法?

代码如下:

 @Override
public void onConnected(Bundle bundle) {
    // onConnected indicates that an account was selected on the device, that the selected
    // account has granted any requested permissions to our app and that we were able to
    // establish a service connection to Google Play services.
    Log.d(TAG, "onConnected:" + bundle);
    mShouldResolve = false;

    mAccountName = Plus.AccountApi.getAccountName(mGoogleApiClient);

    //HERE I RETRIEVE THE TOKEN AND NEED TO IMPLEMENT CALLBACK
    new RetrieveTokenTask().execute(mAccountName);


    // Show the signed-in UI
    Intent intent = new Intent(getActivity(), MainActivity.class);
    startActivity(intent);
}

@Override
public void onClick(View v) {

    if (v.getId() == R.id.sign_in_button) {
        onSignInClicked();
    }
}

private void onSignInClicked() {
    // User clicked the sign-in button, so begin the sign-in process and automatically
    // attempt to resolve any errors that occur.
    mShouldResolve = true;
    mGoogleApiClient.connect();

    // Show a message to the user that we are signing in.
    //mStatusTextView.setText(R.string.signing_in);
    Log.i("GoogleSignIn", "in progress");
}


private class RetrieveTokenTask extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {
        String accountName = params[0];
        String scopes = "oauth2:profile email";
        String token = null;
        try {
            token = GoogleAuthUtil.getToken(getActivity().getApplicationContext(), accountName, scopes);
        } catch (IOException e) {
            Log.e(TAG, e.getMessage());
        } catch (UserRecoverableAuthException e) {
            //startActivityForResult(e.getIntent(), REQ_SIGN_IN_REQUIRED);
        } catch (GoogleAuthException e) {
            Log.e(TAG, e.getMessage());
        }
        return token;
    }

    @Override
    protected void onPostExecute(String token) {
        super.onPostExecute(token);
        Log.i("Token Value: ", token);
        //TODO : access token verifier https://developers.google.com/identity/sign-in/android/backend-auth
        accessToken = token;
    }
}

【问题讨论】:

    标签: android android-asynctask google-signin


    【解决方案1】:

    你可以在 onPostExecute 方法中启动主要活动.. 这样你就可以确定任务已经执行并且即将完成。

    检查一下

    private class RetrieveTokenTask extends AsyncTask<String, Void, String> {
    
     private Callback callback;
    
    public RetrieveTokenTask(Callback callback){
         this.callback = callback;
    }
    
    @Override
    protected String doInBackground(String... params) {
        String accountName = params[0];
        String scopes = "oauth2:profile email";
        String token = null;
        try {
            token = GoogleAuthUtil.getToken(getActivity().getApplicationContext(), accountName, scopes);
        } catch (IOException e) {
            Log.e(TAG, e.getMessage());
        } catch (UserRecoverableAuthException e) {
            //startActivityForResult(e.getIntent(), REQ_SIGN_IN_REQUIRED);
        } catch (GoogleAuthException e) {
            Log.e(TAG, e.getMessage());
        }
        return token;
    }
    
    @Override
    protected void onPostExecute(String token) {
        super.onPostExecute(token);
        Log.i("Token Value: ", token);
        //TODO : access token verifier https://developers.google.com/identity/sign-in/android/backend-auth
        accessToken = token;
        callback.done();
    }
    

    }

    //create an interface
    public interface Callback{
      //create the callback method
       void done();
    }
    

    启动任务时,像这样在构造函数中传递回调接口的实例,例如

    new RetrieveTokenTask(this).execute(mAccountName);
    

    并使您的活动实现回调接口。 例如MainActivity implements Callback

    现在MainActivity会有一个done方法,这个方法就是你的回调。

    我希望这个解释会有所帮助。

    【讨论】:

    • 当然可以,但我的问题是是否可以向异步任务添加回调方法;)
    【解决方案2】:

    不要在 Android 上使用 AsyncTask。这很糟糕,真的很糟糕。您将开始出现内存泄漏,这很糟糕。

    这里有更多关于为什么 AsyncTask 在 Android 上不好的信息:http://simonvt.net/2014/04/17/asynctask-is-bad-and-you-should-feel-bad/

    对于您的网络调用,为什么要重新发明轮子?有很多成熟且经过测试的库可以为您完成所有艰苦的工作,它们甚至为您提供回调。

    我推荐你来自 Square 的 Retrofit,它们为你提供同步调用以及异步(回调)和 observables。只需选择您想要的,很可能是带有回调的异步。

    【讨论】:

    猜你喜欢
    • 2023-03-11
    • 2023-03-16
    • 2015-12-24
    • 1970-01-01
    • 2013-04-03
    • 1970-01-01
    • 2013-01-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多