2017-06-11 406 views
0

我一直在關注this article,以將Google Sign-In實施到Android應用中。使用Google登錄授權YouTube Data API

這個代碼最後一位爲我們提供了一個GoogleSignInAccount對象包含有關登錄的用戶信息:

private void handleSignInResult(GoogleSignInResult result) { 
    Log.d(TAG, "handleSignInResult:" + result.isSuccess()); 
    if (result.isSuccess()) { 
     // Signed in successfully, show authenticated UI. 
     GoogleSignInAccount acct = result.getSignInAccount(); 
     mStatusTextView.setText(getString(R.string.signed_in_fmt, acct.getDisplayName())); 
     updateUI(true); 
    } else { 
     // Signed out, show unauthenticated UI. 
     updateUI(false); 
    } 
} 

在所有code samples provided YouTube數據API的,下面的驗證碼用於:

public static Credential authorize() throws IOException { 
    // Load client secrets. 
    InputStream in = ApiExample.class.getResourceAsStream("/client_secret.json"); 
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in)); 

    // Build flow and trigger user authorization request. 
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
    HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES) 
     .setDataStoreFactory(DATA_STORE_FACTORY) 
     .setAccessType("offline") 
     .build(); 
    Credential credential = new AuthorizationCodeInstalledApp(
    flow, new LocalServerReceiver()).authorize("user"); 
    System.out.println(
     "Credentials saved to " + DATA_STORE_DIR.getAbsolutePath()); 
    return credential; 
} 

現在,因爲我一直在使用谷歌登錄功能已經通過身份驗證,我怎麼能創建使用GoogleSignInAccount對象傳遞給YouTube.Builder一個Credential對象?

+0

我會寫了這個問題後的答案,但在此期間,[這](https://gist.github.com/bertrandmartel/7d323b09af889f5c03b862612c796046)幫我解決我的問題。 – sudoman

回答

0
public static final Collection<String> YOUTUBE_SCOPE = Arrays.asList("https://www.googleapis.com/auth/youtube.force-ssl https://www.googleapis.com/auth/youtubepartner"); 

... 

private void handleSignInResult(GoogleSignInResult result) { 

    ... 

    GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(context, YOUTUBE_SCOPE); 
    credential.setSelectedAccount(acct.getAccount()); 

    ... 

} 

Source