从谷歌和Android获取访问令牌

时间:2013-08-07 07:13:57

标签: android google-plus

谁能告诉我我做错了什么?我需要从Google Plus获取访问令牌..

我把它放在我的onConnected()方法中但是我没有获得访问令牌,而是我收到错误...

代码:

try {
        String token = GoogleAuthUtil.getToken(this, mPlusClient.getAccountName() + "", "oauth2:" + Scopes.PLUS_PROFILE + 
                                "https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email");
        Log.d("AccessToken", token);
    } catch (UserRecoverableAuthException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (GoogleAuthException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

错误:

08-07 10:10:24.199: E/GoogleAuthUtil(17203): Calling this from your main thread can lead to deadlock and/or ANRs

有谁能告诉我从用户那里获取Google Plus访问令牌的正确方法是什么?

4 个答案:

答案 0 :(得分:5)

您需要将令牌请求放在后台线程中。我已经发布了一些示例代码,展示了如何在这个问题中执行此操作:

"Calling this from your main thread can lead to deadlock and/or ANRs while getting accesToken" from GoogleAuthUtil(Google Plus integration in Android)

答案 1 :(得分:4)

您可以在onConnected()方法中访问令牌。在onConnected()方法范围内添加此代码。

final String SCOPES = "https://www.googleapis.com/auth/userinfo.profile";
         new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... params) {
               String ace = "";
               try {
                  ace = GoogleAuthUtil.getToken(getApplicationContext(),
                                                Plus.AccountApi.getAccountName(mGoogleApiClient),
                                                "oauth2:" + SCOPES);
               }
               catch (IOException e) {
                  e.printStackTrace();
               }
               catch (GoogleAuthException e) {
                  e.printStackTrace();
               }
               Log.i("", "mustafa olll " + ace);
               return null;
            }
         }.execute();

答案 2 :(得分:2)

您需要使用异步任务获取它。

public void onConnected(Bundle connectionHint) {
// Reaching onConnected means we consider the user signed in. 
Log.i(TAG, "onConnected");

// Update the user interface to reflect that the user is signed in. 
mSignInButton.setEnabled(false); 
mSignOutButton.setEnabled(true); 
mRevokeButton.setEnabled(true); 

// Retrieve some profile information to personalize our app for the user. 
Person currentUser = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);


AsyncTask<Void, Void, String > task = new AsyncTask<Void, Void, String>() {
    @Override 
    protected String doInBackground(Void... params) {
        String token = null;
        final String SCOPES = "https://www.googleapis.com/auth/plus.login ";

        try { 
            token = GoogleAuthUtil.getToken(
                     getApplicationContext(),
                     Plus.AccountApi.getAccountName(mGoogleApiClient), 
                     "oauth2:" + SCOPES);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (GoogleAuthException e) {
            e.printStackTrace();
        } 


      return token;

    } 

    @Override 
    protected void onPostExecute(String token) {
        Log.i(TAG, "Access token retrieved:" + token);
    } 

}; 
task.execute();


System.out.print("email" + email);
mStatus.setText(String.format(
        getResources().getString(R.string.signed_in_as),
        currentUser.getDisplayName()));

Plus.PeopleApi.loadVisible(mGoogleApiClient, null) 
        .setResultCallback(this);

// Indicate that the sign in process is complete. 
mSignInProgress = STATE_DEFAULT; }

您的访问令牌将存储到令牌变量中。

答案 3 :(得分:1)

以下是您可以使用的代码。如果有人有更好的建议,请发帖:

     /**
     * Successfully connected (called by PlusClient)
     */
    @Override
    public void onConnected(Bundle connectionHint) {
        /* First do what ever you wanted to do in onConnected() */
         ....
         ....

        /* Now get the token using and async call*/
        GetGooglePlusToken token    =   new GetGooglePlusToken(this.getActivity(), mPlusClient);
        token.execute();

    }



class GetGooglePlusToken extends AsyncTask<Void, Void, String> {
    Context context;
    private GoogleApiClient mGoogleApiClient;
    private String TAG  = this.getClass().getSimpleName();

    public GetGooglePlusToken(Context context, GoogleApiClient mGoogleApiClient) {
        this.context = context;
        this.mGoogleApiClient = mGoogleApiClient;
    }

    @Override
    protected String doInBackground(Void... params) {
        String accessToken1 = null;
        try {

            Bundle bundle = new Bundle();

            String  accountname  =   Plus.AccountApi.getAccountName(mGoogleApiClient);
            String scope = "oauth2:" + Scopes.PLUS_LOGIN + " " + "https://www.googleapis.com/auth/userinfo.email" + " https://www.googleapis.com/auth/plus.profile.agerange.read";
            accessToken1 = GoogleAuthUtil.getToken(context,
                    accountname,
                    scope);
            return accessToken1;

        } catch (IOException transientEx) {
            // network or server error, the call is expected to succeed if you try again later.
            // Don't attempt to call again immediately - the request is likely to
            // fail, you'll hit quotas or back-off.
            //TODO: HANDLE
            Log.e(TAG, "transientEx");
            transientEx.printStackTrace();
            accessToken1 = null;

        } catch (UserRecoverableAuthException e) {
            // Recover
            Log.e(TAG, "UserRecoverableAuthException");
            e.printStackTrace();
            accessToken1 = null;

        } catch (GoogleAuthException authEx) {
            // Failure. The call is not expected to ever succeed so it should not be
            // retried.
            Log.e(TAG, "GoogleAuthException");
            authEx.printStackTrace();
            accessToken1 = null;
        } catch (Exception e) {
            Log.e(TAG, "RuntimeException");
            e.printStackTrace();
            accessToken1 = null;
            throw new RuntimeException(e);
        }
        Log.wtf(TAG, "Code should not go here");
        accessToken1 = null;
        return accessToken1;
    }

    @Override
    protected void onPostExecute(String response) {
        Log.d(TAG, "Google access token = " + response);
    }
}