Google Plus 登录身份验证
使用 Plus 登录验证用户
onCreate
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestScopes(new Scope(Scopes.PLUS_LOGIN))
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Auth.GOOGLE_SIGN_IN_API,gso)
.addApi(Plus.API)
.build();
在 onStart()
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
mAuth.addAuthStateListener(mAuthListener);
}
protected void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
@Override
public void onConnected(Bundle bundle) {
mSignInClicked = false;
getProfileInformation();
//getGoogleOAuthTokenAndLogin();
Toast.makeText(this, "User is connected! (in onConnected MActivty)",Toast.LENGTH_LONG).show();
// Get user's information
// Update the UI after signin
// updateUI(true);
}
@Override
public void onConnectionSuspended(int i) {
mGoogleApiClient.connect();
//updateUI(false);
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (!connectionResult.hasResolution()) {
GooglePlayServicesUtil.getErrorDialog(connectionResult.getErrorCode(), this,
0).show();
} else if(connectionResult.hasResolution()) {
mConnectionResult = connectionResult;
resolveSignInError();
}
}
private void resolveSignInError() {
Log.e("pavan", "User RESOLVE SIGN IN ERROR CALLED OUT OF IF");
if(mSignInClicked){
if (mConnectionResult.hasResolution()) {
try {
Log.e("pavan", "User RESOLVE SIGN IN ERROR CALLED OUT OF IF TRY");
mIntentInProgress = true;
mConnectionResult.startResolutionForResult(this, GOOGLE_SIGIN);
} catch (IntentSender.SendIntentException e) {
Log.e("pavan", "User RESOLVE SIGN IN ERROR CALLED OUT OF IF CATCH");
mIntentInProgress = false;
mGoogleApiClient.connect();
}
}
}
}
获取个人资料信息
private void getProfileInformation() {
try {
if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
Person currentPerson = Plus.PeopleApi
.getCurrentPerson(mGoogleApiClient);
String personName = currentPerson.getDisplayName();
String personPhotoUrl = currentPerson.getImage().getUrl();
String personGooglePlusProfile = currentPerson.getUrl();
String email = Plus.AccountApi.getAccountName(mGoogleApiClient);
} catch (Exception e) {
e.printStackTrace();
}
}
使用 Firebase 进行身份验证,
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
//AuthCredential credential = GoogleAuthProvider.getCredential(tokenCredential, null);
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(),null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
Log.d("TAG", "signInWithCredential:onComplete:" + task.isSuccessful());
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
Log.w("TAG", "signInWithCredential", task.getException());
Toast.makeText(MainActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}else{
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Log.e("SahajLOG", "Login PREF ISSSSSSSS ONACTIVITYRESULT "+prefs.getBoolean("AuthByGplus", AuthByGplus));
prefs.edit().putBoolean("AuthByGplus", true).commit();
Log.e("SahajLOG", "Login PREF ISSSSSSSS ONACTIVITYRESULT IFTRUE.. "+prefs.getBoolean("AuthByGplus", AuthByGplus));
Intent intent=new Intent(getApplicationContext(),MainActivity.class);
startActivity(intent);
finish();
}
// [START_EXCLUDE]
// hideProgressDialog();
// [END_EXCLUDE]
}
});
}
onActivityResult
@Override
protected void onActivityResult(int requestCode, int responseCode,
Intent intent) {
if (requestCode == GOOGLE_SIGIN) {
if (responseCode != RESULT_OK) {
mSignInClicked = false;
}
mIntentInProgress = false;
if (!mGoogleApiClient.isConnecting()) {
mGoogleApiClient.connect();
if (mGoogleApiClient.isConnected()) {
// getGoogleOAuthTokenAndLogin();
}
}
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(intent);
if (result.isSuccess()) {
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = result.getSignInAccount();
Log.e("SahajLOG", "account " + account.getIdToken());
//getGoogleOAuthTokenAndLogin();
firebaseAuthWithGoogle(account);
} else {
// Google Sign In failed, update UI appropriately
// [START_EXCLUDE]
Log.e("SahajLOG", "SIGN IN FAILED");
// [END_EXCLUDE]
}
}
public void signInWithGplus() {
if (!mGoogleApiClient.isConnecting()) {
mSignInClicked = true;
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, GOOGLE_SIGIN);
}
}
登出
@Override
public void onLogout() {
mAuth.signOut();
if (mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
mGoogleApiClient.disconnect();
mGoogleApiClient.connect();
SignedInWithGoogle=false;
}
// Google sign out
switchToLoginFragment();
}