Firebase is a platform for all Android,Ios and Web Applications.provides automatic data synchronization, authentication services, messaging, file storage, analytics, and more.Today,i write this post how to SignUp with Facebook and Google using firebase concept in detail.
Facebook Integration Part:
Before going to this approach you must have an Facebook developer account,In case you have no account click to this link: https://developers.facebook.com/apps/
1.Create project write your project Name.It's easy to fill all the specified fields but one main point here mentioned i.e SHA1 key generation.
To generate this key you must download the Openssl.
1.C:\Program Files\Java\jdk1.8.0_121\bin\keytool.exe
It is path for JDK key tool.exe
2.C:\Users\Admin\Downloads\openssl-0.9.8k_X64\bin\openssl.exe
It is path for openssl
Key Tool Generation Process:
Run Your command prompt by this command.
keytool -exportcert -alias androiddebugkey -keystore "C:\Users\USERNAME\.android\debug.keystore" | "C:\Users\Admin\Downloads\openssl-0.9.8k_X64\bin\openssl.exe" sha1 -binary | "C:\Users\Admin\Downloads\openssl-0.9.8k_X64\bin\openssl.exe" base64
After do this Steps go to Firebase console for setup Facebook Login roles and google roles.This is link for firebase :https://console.firebase.google.com
1.Create Project as below way.Once click one Add project it will show another screen below...
After done this step Select the option Android Apps then process the project profile as below screen
After complete above steps finally You will appear the below screen.In this you have Sign Up Methods like Facebook,email,google bla..bla...
Now we go for coding part ....
LoginActivity.Java
import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.view.View; import android.view.View.OnClickListener; import com.facebook.AccessToken; import com.facebook.CallbackManager; import com.facebook.FacebookCallback; import com.facebook.FacebookException; import com.facebook.FacebookSdk; import com.facebook.login.LoginManager; import com.facebook.login.LoginResult; import com.google.android.gms.auth.api.Auth; import com.google.android.gms.auth.api.signin.GoogleSignInAccount; import com.google.android.gms.auth.api.signin.GoogleSignInResult; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthCredential; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FacebookAuthProvider; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.auth.GoogleAuthProvider; import com.google.firebase.iid.FirebaseInstanceId; import com.toss.socialposts.Constants; import com.toss.socialposts.HomeActivity; import com.toss.socialposts.R; import com.toss.socialposts.managers.DatabaseHelper; import com.toss.socialposts.managers.ProfileManager; import com.toss.socialposts.managers.listeners.OnObjectExistListener; import com.toss.socialposts.model.Profile; import com.toss.socialposts.utils.GoogleApiHelper; import com.toss.socialposts.utils.LogUtil; import com.toss.socialposts.utils.LogoutHelper; import com.toss.socialposts.utils.PreferencesUtil; import java.util.Arrays; public class LoginActivity extends BaseActivity implements GoogleApiClient.OnConnectionFailedListener { private static final String TAG = LoginActivity.class.getSimpleName(); private static final int SIGN_IN_GOOGLE = 9001; private FirebaseAuth mAuth; private FirebaseAuth.AuthStateListener mAuthListener; private GoogleApiClient mGoogleApiClient; private CallbackManager mCallbackManager; private String profilePhotoUrlLarge; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); FacebookSdk.sdkInitialize(getApplicationContext()); setContentView(R.layout.activity_login); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); } mGoogleApiClient = GoogleApiHelper.createGoogleApiClient(this); findViewById(R.id.googleSignInButton).setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { signInWithGoogle(); } }); mAuth = FirebaseAuth.getInstance(); if (mAuth.getCurrentUser() != null) { } mAuthListener = new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { final FirebaseUser user = firebaseAuth.getCurrentUser(); if (user != null) { checkIsProfileExist(user.getUid()); } else { } } }; mCallbackManager = CallbackManager.Factory.create(); LoginManager.getInstance().registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() { @Override public void onSuccess(LoginResult loginResult) { LogUtil.logDebug(TAG, "facebook:onSuccess:" + loginResult); profilePhotoUrlLarge = String.format(getString(R.string.facebook_large_image_url_pattern), loginResult.getAccessToken().getUserId()); handleFacebookAccessToken(loginResult.getAccessToken()); } @Override public void onCancel() { LogUtil.logDebug(TAG, "facebook:onCancel"); } @Override public void onError(FacebookException error) { LogUtil.logError(TAG, "facebook:onError", error); showSnackBar(error.getMessage()); } }); findViewById(R.id.facebookSignInButton).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { signInWithFacebook(); } }); } @Override public void onStart() { super.onStart(); mAuth.addAuthStateListener(mAuthListener); if (mGoogleApiClient != null) { mGoogleApiClient.connect(); } } @Override public void onStop() { super.onStop(); if (mAuthListener != null) { mAuth.removeAuthStateListener(mAuthListener); } if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) { mGoogleApiClient.stopAutoManage(this); mGoogleApiClient.disconnect(); } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); mCallbackManager.onActivityResult(requestCode, resultCode, data); if (requestCode == SIGN_IN_GOOGLE) { GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data); if (result.isSuccess()) { showProgress(); GoogleSignInAccount account = result.getSignInAccount(); profilePhotoUrlLarge = String.format(getString(R.string.google_large_image_url_pattern), account.getPhotoUrl(), Constants.Profile.MAX_AVATAR_SIZE); firebaseAuthWithGoogle(account); } else { hideProgress(); } } } private void checkIsProfileExist(final String userId) { ProfileManager.getInstance(this).isProfileExist(userId, new OnObjectExistListener<Profile>() { @Override public void onDataChanged(boolean exist) { if (!exist) { startCreateProfileActivity(); } else { PreferencesUtil.setProfileCreated(LoginActivity.this, true); DatabaseHelper.getInstance(LoginActivity.this.getApplicationContext()) .addRegistrationToken(FirebaseInstanceId.getInstance().getToken(), userId); } hideProgress(); finish(); } }); } private void startCreateProfileActivity() { Intent intent = new Intent(LoginActivity.this, NextActivty.class); intent.putExtra(CreateProfileActivity.LARGE_IMAGE_URL_EXTRA_KEY, profilePhotoUrlLarge); startActivity(intent); } private void handleFacebookAccessToken(AccessToken token) { showProgress(); AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken()); mAuth.signInWithCredential(credential) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { Intent tas=new Intent(getApplicationContext(),NextActivity.class); startActivity(tas); finish(); if (!task.isSuccessful()) { handleAuthError(task); } } }); } private void handleAuthError(Task<AuthResult> task) { Exception exception = task.getException(); if (exception != null) { showWarningDialog(exception.getMessage()); } else { showSnackBar(R.string.error_authentication); } hideProgress(); } private void firebaseAuthWithGoogle(GoogleSignInAccount acct) { LogUtil.logDebug(TAG, "firebaseAuthWithGoogle:" + acct.getId()); showProgress(); AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null); mAuth.signInWithCredential(credential) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { Intent tas=new Intent(getApplicationContext(),HomeActivity.class); startActivity(tas); finish(); if (!task.isSuccessful()) { handleAuthError(task); } } }); } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { showSnackBar(R.string.error_google_play_services); hideProgress(); } private void signInWithGoogle() { if (hasInternetConnection()) { Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient); startActivityForResult(signInIntent, SIGN_IN_GOOGLE); } else { showSnackBar(R.string.internet_connection_failed); } } private void signInWithFacebook() { if (hasInternetConnection()) { LoginManager.getInstance().logInWithReadPermissions(LoginActivity.this, Arrays.asList("email", "public_profile")); } else { showSnackBar(R.string.internet_connection_failed); } } }
activity_login.xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:id="@+id/buttonsContainer" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginBottom="@dimen/login_screen_content_offset_center_top" android:gravity="center" android:orientation="vertical"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="@dimen/login_screen_title_margin" android:text="@string/app_name" style="@style/TextAppearance.MainTitle" /> <RelativeLayout android:id="@+id/facebookSignInButton" android:layout_width="@dimen/base_login_button_width" android:layout_height="@dimen/base_login_button_height" android:layout_gravity="center_horizontal" android:layout_margin="5dp" android:background="@drawable/facebook_button_bg" android:elevation="4dp"> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentStart="true" android:layout_centerVertical="true" android:paddingLeft="@dimen/large_intrinsic_padding" android:paddingRight="@dimen/large_intrinsic_padding" app:srcCompat="@drawable/ic_bt_login_facebook" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="@string/button_login_with_facebook" android:textColor="@drawable/login_button_text_selector" /> </RelativeLayout> <RelativeLayout android:id="@+id/googleSignInButton" android:layout_width="@dimen/base_login_button_width" android:layout_height="@dimen/base_login_button_height" android:layout_gravity="center_horizontal" android:layout_marginBottom="@dimen/login_screen_button_margin" android:background="@drawable/google_button_bg" android:elevation="4dp"> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentStart="true" android:layout_centerVertical="true" android:paddingLeft="@dimen/large_intrinsic_padding" android:paddingRight="@dimen/large_intrinsic_padding" app:srcCompat="@drawable/ic_bt_login_google" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="@string/button_login_with_google" android:textColor="@drawable/login_button_text_selector" /> </RelativeLayout> </LinearLayout> </FrameLayout>
Comments
Post a Comment