2016-08-31 58 views

回答

2

不幸的onclick裏面以下,火力地堡沒有任何內置功能在成功登錄後獲取用戶的性別/出生日期。您必須自己從每個提供程序中檢索這些數據。

這裏是你會如何使用Google People API

public class SignInActivity extends AppCompatActivity implements 
     GoogleApiClient.ConnectionCallbacks, 
     GoogleApiClient.OnConnectionFailedListener, 
     View.OnClickListener { 
    private static final int RC_SIGN_IN = 9001; 

    private GoogleApiClient mGoogleApiClient; 

    private FirebaseAuth mAuth; 
    private FirebaseAuth.AuthStateListener mAuthListener; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_google_sign_in); 

     // We can only get basic information using FirebaseAuth 
     mAuth = FirebaseAuth.getInstance(); 
     mAuthListener = new FirebaseAuth.AuthStateListener() { 
      @Override 
      public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { 
       FirebaseUser user = firebaseAuth.getCurrentUser(); 
       if (user != null) { 
        // User is signed in to Firebase, but we can only get 
        // basic info like name, email, and profile photo url 
        String name = user.getDisplayName(); 
        String email = user.getEmail(); 
        Uri photoUrl = user.getPhotoUrl(); 

        // Even a user's provider-specific profile information 
        // only reveals basic information 
        for (UserInfo profile : user.getProviderData()) { 
         // Id of the provider (ex: google.com) 
         String providerId = profile.getProviderId(); 
         // UID specific to the provider 
         String profileUid = profile.getUid(); 
         // Name, email address, and profile photo Url 
         String profileDisplayName = profile.getDisplayName(); 
         String profileEmail = profile.getEmail(); 
         Uri profilePhotoUrl = profile.getPhotoUrl(); 
        } 
       } else { 
        // User is signed out of Firebase 
       } 
      } 
     }; 

     // Google sign-in button listener 
     findViewById(R.id.google_sign_in_button).setOnClickListener(this); 

     // Configure GoogleSignInOptions 
     GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) 
       .requestIdToken(getString(R.string.server_client_id)) 
       .requestServerAuthCode(getString(R.string.server_client_id)) 
       .requestEmail() 
       .requestScopes(new Scope(PeopleScopes.USERINFO_PROFILE)) 
       .build(); 

     // Build a GoogleApiClient with access to the Google Sign-In API and the 
     // options specified by gso. 
     mGoogleApiClient = new GoogleApiClient.Builder(this) 
       .enableAutoManage(this, this) 
       .addOnConnectionFailedListener(this) 
       .addConnectionCallbacks(this) 
       .addApi(Auth.GOOGLE_SIGN_IN_API, gso) 
       .build(); 
    } 

    @Override 
    public void onClick(View v) { 
     switch (v.getId()) { 
      case R.id.google_sign_in_button: 
       signIn(); 
       break; 
     } 
    } 

    private void signIn() { 
     Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient); 
     startActivityForResult(signInIntent, RC_SIGN_IN); 
    } 

    @Override 
    public void onActivityResult(int requestCode, int resultCode, Intent data) { 
     super.onActivityResult(requestCode, resultCode, data); 

     // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...); 
     if (requestCode == RC_SIGN_IN) { 
      GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data); 
      if (result.isSuccess()) { 
       // Signed in successfully 
       GoogleSignInAccount acct = result.getSignInAccount(); 

       // execute AsyncTask to get gender from Google People API 
       new GetGendersTask().execute(acct); 

       // Google Sign In was successful, authenticate with Firebase 
       firebaseAuthWithGoogle(acct); 
      } 
     } 
    } 

    class GetGendersTask extends AsyncTask<GoogleSignInAccount, Void, List<Gender>> { 
     @Override 
     protected List<Gender> doInBackground(GoogleSignInAccount... googleSignInAccounts) { 
      List<Gender> genderList = new ArrayList<>(); 
      try { 
       HttpTransport httpTransport = new NetHttpTransport(); 
       JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance(); 

       //Redirect URL for web based applications. 
       // Can be empty too. 
       String redirectUrl = "urn:ietf:wg:oauth:2.0:oob"; 

       // Exchange auth code for access token 
       GoogleTokenResponse tokenResponse = new GoogleAuthorizationCodeTokenRequest(
         httpTransport, 
         jsonFactory, 
         getApplicationContext().getString(R.string.server_client_id), 
         getApplicationContext().getString(R.string.server_client_secret), 
         googleSignInAccounts[0].getServerAuthCode(), 
         redirectUrl 
       ).execute(); 

       GoogleCredential credential = new GoogleCredential.Builder() 
         .setClientSecrets(
          getApplicationContext().getString(R.string.server_client_id), 
          getApplicationContext().getString(R.string.server_client_secret) 
         ) 
         .setTransport(httpTransport) 
         .setJsonFactory(jsonFactory) 
         .build(); 

       credential.setFromTokenResponse(tokenResponse); 

       People peopleService = new People.Builder(httpTransport, jsonFactory, credential) 
         .setApplicationName("My Application Name") 
         .build(); 

       // Get the user's profile 
       Person profile = peopleService.people().get("people/me").execute(); 
       genderList.addAll(profile.getGenders()); 
      } 
      catch (IOException e) { 
       e.printStackTrace(); 
      } 
      return genderList; 
     } 

     @Override 
     protected void onPostExecute(List<Gender> genders) { 
      super.onPostExecute(genders); 
      // iterate through the list of Genders to 
      // get the gender value (male, female, other) 
      for (Gender gender : genders) { 
       String genderValue = gender.getValue(); 
      } 
     } 
    } 
} 

得到谷歌用戶的性別,您可以找到關於Accessing Google APIs

1

不,您無法直接獲取這些數據。但是您可以使用用戶的ID並從各個提供商那裏獲取這些數據。請在每個這些提供程序的公共API中可用的數據之前進行檢查,例如,Google僅棄用了來自peopleApi的幾個方法。

反正這裏是我對於Facebook

// Initialize Firebase Auth 
FirebaseAuth mAuth = FirebaseAuth.getInstance(); 

// Create a listener 
FirebaseAuth.AuthStateListener mAuthListener = firebaseAuth -> { 
     FirebaseUser user = firebaseAuth.getCurrentUser(); 
     if (user != null) { 
      // User is signed in 
      Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid()); 
     } else { 
      // User is signed out 
      Log.d(TAG, "onAuthStateChanged:signed_out"); 
     } 

     if (user != null) { 
      Log.d(TAG, "User details : " + user.getDisplayName() + user.getEmail() + "\n" + user.getPhotoUrl() + "\n" 
        + user.getUid() + "\n" + user.getToken(true) + "\n" + user.getProviderId()); 

      String userId = user.getUid(); 
      String displayName = user.getDisplayName(); 
      String photoUrl = String.valueOf(user.getPhotoUrl()); 
      String email = user.getEmail(); 

      Intent homeIntent = new Intent(LoginActivity.this, HomeActivity.class); 
      startActivity(homeIntent); 
      finish(); 
     } 
    }; 

//Initialize the fB callbackManager 
mCallbackManager = CallbackManager.Factory.create(); 

做,做FB登錄按鈕

LoginManager.getInstance().registerCallback(mCallbackManager, 
      new FacebookCallback<LoginResult>() { 
       @Override 
       public void onSuccess(LoginResult loginResult) { 
        Log.d(TAG, "facebook:onSuccess:" + loginResult); 
        handleFacebookAccessToken(loginResult.getAccessToken()); 
       } 

       @Override 
       public void onCancel() { 
        Log.d(TAG, "facebook:onCancel"); 
       } 

       @Override 
       public void onError(FacebookException error) { 
        Log.d(TAG, "facebook:onError", error); 
       } 
      }); 

LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile", "email")); 
+1

我不能在您的樣品中看到你的性別或出生日期? –

+0

那些沒有提供我的firebase,因爲你需要使用Facebook的圖形API和你在這裏得到的用於對圖形API進行各種查詢的uid。 https://developers.facebook.com/docs/graph-api –

+0

我明白了,所以無法使用Firebase sdk完成。我需要單獨使用Graph API或People API來獲取它們 –

1

對於Facebook的更多信息:

要獲得的Facebook的accessToken從火力很簡單。我正在使用Firebase身份驗證用戶界面。使用Facebook進行身份驗證後,您將獲得來自Firebase用戶對象的基本信息,如顯示名稱,電子郵件,提供商詳細信息但是如果你想要更多的信息如性別,生日facebook Graph API就是解決方案。一旦用戶通過Facebook進行身份驗證,您就可以獲得像這樣的訪問令牌。

AccessToken.getCurrentAccessToken() 但有時它會給你NULL值而不是有效的訪問令牌。確保你之前已經初始化了Facebook SDK。

public class MyApplication extends Application { 
    @Override 
    public void onCreate() { 
    super.onCreate(); 
    FacebookSdk.sdkInitialize(this); 
    } 

} 初始化使用graphAPI後

if(AccessToken.getCurrentAccessToken()!=null) { 

    System.out.println(AccessToken.getCurrentAccessToken().getToken()); 

    GraphRequest request = GraphRequest.newMeRequest(
      AccessToken.getCurrentAccessToken(), 
      new GraphRequest.GraphJSONObjectCallback() { 
       @Override 
       public void onCompleted(JSONObject object, GraphResponse response) { 
        // Application code 
        try { 
         String email = object.getString("email"); 
         String gender = object.getString("gender"); 
        } catch (JSONException e) { 
         e.printStackTrace(); 
        } 
       } 
      }); 
    Bundle parameters = new Bundle(); 
    parameters.putString("fields", "id,name,email,gender,birthday"); 
    request.setParameters(parameters); 
    request.executeAsync(); 

} 
else 
{ 
    System.out.println("Access Token NULL"); 
} 

編碼快樂:)

相關問題