Facebook and Google Login using a custom button in an android studio
Facebook
Google
Login
android studio
android
Button
- By Code solution
- Jan 20th, 2021
- 0 comments
- 0
Facebook and Google Login using a custom button in an android studio.
Creating New Project
- Create a new project in Android Studio from File ⇒ New Project. When selecting Empty Activity and proceed.
- Add Facebook and Google dependency to your build.gradle and rebuild the project.
dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) //noinspection GradleCompatible implementation 'com.android.support:appcompat-v7:27.1.1' implementation 'com.android.support:design:27.+' implementation 'com.android.support.constraint:constraint-layout:1.1.0' implementation 'com.android.support:support-v4:27.1.1' testImplementation 'junit:junit:4.12' androidTestImplementation 'com.android.support.test:runner:1.0.1' implementation 'com.facebook.android:facebook-android-sdk:[4,5)' implementation 'com.google.android.gms:play-services:12.0.1' }
- Open String.xml located under res ⇒ values and add the below values.
<resources> <string name="app_name">GoogleFbLoginstring> <string name="facebook_app_id">303427880192019string> <string name="fb_login_protocol_scheme">fb303427880192019string> resources>
Create four XML layouts named activity_main.xml under res ⇒ layouts.
xml version="1.0" encoding="utf-8"?> <ScrollView 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" tools:context=".LoginActivity"> <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingTop="56dp" android:paddingLeft="24dp" android:paddingRight="24dp"> <FrameLayout android:id="@+id/FrameLayout1" android:layout_width="match_parent" android:layout_height="wrap_content" > <com.facebook.login.widget.LoginButton android:id="@+id/login_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:visibility="gone" /> <Button android:id="@+id/fb" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="#416BC1" android:onClick="onClick" android:text="FaceBook Login" android:textColor="#ffffff" android:textStyle="bold" /> FrameLayout> <FrameLayout android:id="@+id/FrameLayout2" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp"> <com.google.android.gms.common.SignInButton android:id="@+id/btn_sign_in" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginBottom="0dp" /> <Button android:id="@+id/google" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="#cf4333" android:onClick="onClick" android:text="Google Login" android:textColor="#ffffff" android:textStyle="bold" /> FrameLayout> LinearLayout> ScrollView>
- Open MainActivity.java and modify the code as below.
package com.wapptech.waytofeed; import android.content.Intent; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import com.bumptech.glide.Glide; import com.facebook.CallbackManager; import com.facebook.FacebookCallback; import com.facebook.FacebookException; import com.facebook.GraphRequest; import com.facebook.GraphResponse; import com.facebook.login.LoginResult; import com.facebook.login.widget.LoginButton; 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.GoogleSignInOptions; import com.google.android.gms.auth.api.signin.GoogleSignInResult; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.SignInButton; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.OptionalPendingResult; import com.google.android.gms.common.api.ResultCallback; import com.google.android.gms.common.api.Status; import org.json.JSONException; import org.json.JSONObject; import java.net.MalformedURLException; import java.net.URL; import java.util.Arrays; import java.util.List; import static android.provider.ContactsContract.Intents.Insert.EMAIL; public class MainActivity extends AppCompatActivity implements View.OnClickListener, GoogleApiClient.OnConnectionFailedListener{ private static final String TAG = MainActivity.class.getSimpleName(); private static final int RC_SIGN_IN = 430; private GoogleApiClient mGoogleApiClient; private SignInButton btnSignIn; public LoginButton loginButton; public Button fb, google; public CallbackManager callbackManager; public String id, name, email, gender, birthday; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); callbackManager = CallbackManager.Factory.create(); fb = (Button) findViewById(R.id.fb); google = (Button) findViewById(R.id.google); loginButton = (LoginButton) findViewById(R.id.login_button); List < String > permissionNeeds = Arrays.asList("user_photos", "email", "user_birthday", "public_profile", "AccessToken"); loginButton.registerCallback(callbackManager, new FacebookCallback < LoginResult > () {@Override public void onSuccess(LoginResult loginResult) { System.out.println("onSuccess"); String accessToken = loginResult.getAccessToken() .getToken(); Log.i("accessToken", accessToken); GraphRequest request = GraphRequest.newMeRequest( loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {@Override public void onCompleted(JSONObject object, GraphResponse response) { Log.i("LoginActivity", response.toString()); try { id = object.getString("id"); try { URL profile_pic = new URL( "http://graph.facebook.com/" + id + "/picture?type=large"); Log.i("profile_pic", profile_pic + ""); } catch (MalformedURLException e) { e.printStackTrace(); } Log.e("UserDate", String.valueOf(object)); } catch (JSONException e) { e.printStackTrace(); } } }); Bundle parameters = new Bundle(); parameters.putString("fields","id,name,email,gender, birthday"); request.setParameters(parameters); request.executeAsync(); } @Override public void onCancel() { System.out.println("onCancel"); } @Override public void onError(FacebookException exception) { System.out.println("onError"); Log.v("LoginActivity", exception.getCause().toString()); } }); initializeControls(); initializeGPlusSettings(); } private void initializeControls(){ btnSignIn = (SignInButton) findViewById(R.id.btn_sign_in); btnSignIn.setOnClickListener(this); } private void initializeGPlusSettings(){ GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestEmail() .build(); mGoogleApiClient = new GoogleApiClient.Builder(this) .enableAutoManage(this, this) .addApi(Auth.GOOGLE_SIGN_IN_API, gso) .build(); btnSignIn.setSize(SignInButton.SIZE_STANDARD); btnSignIn.setScopes(gso.getScopeArray()); } private void signIn() { Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient); startActivityForResult(signInIntent, RC_SIGN_IN); } private void signOut() { Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback( new ResultCallback() { @Override public void onResult(Status status) { updateUI(false); } }); } private void handleGPlusSignInResult(GoogleSignInResult result) { Log.d(TAG, "handleSignInResult:" + result.isSuccess()); if (result.isSuccess()) { GoogleSignInAccount acct = result.getSignInAccount(); //Fetch values String personName = acct.getDisplayName(); String personPhotoUrl = acct.getPhotoUrl().toString(); String email = acct.getEmail(); String familyName = acct.getFamilyName(); Log.e(TAG, "Name: " + personName +", email: " + email + ", Image: " + personPhotoUrl +", Family Name: " + familyName); updateUI(true); } else { updateUI(false); } } @Override public void onStart() { super.onStart(); OptionalPendingResult opr = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient); if (opr.isDone()) { Log.d(TAG, "Got cached sign-in"); GoogleSignInResult result = opr.get(); handleGPlusSignInResult(result); } else { opr.setResultCallback(new ResultCallback() { @Override public void onResult(GoogleSignInResult googleSignInResult) { handleGPlusSignInResult(googleSignInResult); } }); } } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { // An unresolvable error has occurred and Google APIs (including Sign-In) will not // be available. Log.d(TAG, "onConnectionFailed:" + connectionResult); } @Override protected void onActivityResult(int requestCode, int responseCode, Intent data) { if (requestCode == RC_SIGN_IN) { GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data); handleGPlusSignInResult(result); }else{ super.onActivityResult(requestCode, responseCode, data); callbackManager.onActivityResult(requestCode, responseCode, data); } } public void onClick(View v) { if (v == fb) { loginButton.performClick(); }else if(v == google){ signIn(); } } private void updateUI(boolean isSignedIn) { if (isSignedIn) { btnSignIn.setVisibility(View.GONE); } else { btnSignIn.setVisibility(View.VISIBLE); } } }
- After Finally open AndroidManifest.XML and make MainActivity as launcher activity.
xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.wapptech.menu">
<uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/> <activity android:name="com.facebook.FacebookActivity" android:configChanges= "keyboard|keyboardHidden|screenLayout|screenSize|orientation" android:label="@string/app_name" /> <activity android:name="com.facebook.CustomTabActivity" android:exported="true"> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <data android:scheme="@string/fb_login_protocol_scheme" /> intent-filter> activity>
<activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> intent-filter> activity> application> manifest>