# Facebook Credential in Android ###### tags: `Android` `Facebook Credential` ## OUTLINE: [TOC] ## How to use Facebook Credential? ### 1. Register and create a new app in the link below: URL: https://developers.facebook.com/ :::info Step 1: Create your app ![](https://i.imgur.com/IFbWwND.png =400x200) Step 2: Follow the **STEPS** given ![](https://i.imgur.com/ewkaCT4.png =400x200) ::: ### 2. Manifest Must include the following in manifest. ``` java== <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> ``` ### 3. Gradle (Project) Remember to add jcenter() and mavenCentral to repositories. ``` java== buildscript { repositories { google() jcenter() mavenCentral() } } ``` ### 4. Gradle(App) First implement the facebook dependency. If appcompat gets errors, then re implement part of it to erase error. ``` java== //Facebook SDK implementation 'com.facebook.android:facebook-android-sdk:5.0.1' //Re implement those that became error when apply fb in appcompat-v7 implementation 'com.android.support:cardview-v7:28.0.0' implementation 'com.android.support:customtabs:28.0.0' implementation 'com.android.support:support-media-compat:28.0.0' implementation 'com.android.support:support-v4:28.0.0' ``` ### 5. Set up FB login Button Must use **++<com.facebook.login.widget.LoginButton/>++** in order to set up the button. Whether to use the default button or not, you can decide it in your xml. ++*Default Button:*++ ![](https://i.imgur.com/zHw0meb.png =250x50) ### 6. FB Login Button in main **CallbackManager:** Manages the callbacks into the FacebookSdk from an Activity's or Fragment's onActivityResult() method. >If login succeeds, the LoginResult parameter has the new AccessToken, and the most recently granted or declined permissions.[color=#206dfc] ``` java== final LoginButton btn_fb_login = findViewById(R.id.btn_fb_login); private CallbackManager fb_callback = CallbackManager.Factory.create(); btn_fb_login.registerCallback(fb_callback, new FacebookCallback<LoginResult>() { @Override public void onSuccess(LoginResult loginResult) { Log.d("NOTE:","LOGIN SUCCESS!"); } @Override public void onCancel() { Log.d("NOTE:","LOGIN CANCEL!"); } @Override public void onError(FacebookException error) { Log.d("NOTE:","LOGIN ERROR!"); } }); ``` ### 7. OnActivityResult >**Why do we need it?** When we want to log in by facebook, it will open another activity asking for log in request/fill information to log in. So we need onActivityResult to arrange what want to do when getting back from the other activity.[color=#55a6e8] ``` java== @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { fb_callback.onActivityResult(requestCode, resultCode, data); super.onActivityResult(requestCode, resultCode, data); } ``` ##### How do we know whether requestCode was or not from Facebook SDK? You can use ++*FacebookSdk.isFacebookRequestCode(requestCode)*++. ``` java== if(FacebookSdk.isFacebookRequestCode(requestCode)){ fb_callback.onActivityResult(requestCode, resultCode, data); } ``` ### 8. AccessTokenTracker >**When does it work?** It will come here after new FacebookCallback<LoginResult> is done running. And if the token was changed, the code below will be processed.[color=#55a6e8] ``` java== AccessTokenTracker tokenTracker = new AccessTokenTracker() { @Override protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) { if(currentAccessToken == null){ Toast.makeText(LoginActivity.this, "LOG OUT", Toast.LENGTH_SHORT).show(); } else { getUserInfo(currentAccessToken); //See STEP 9 to know what this function does. } } }; ``` ### 9. Get User's information >**What is GraphRequest?** The GraphRequest class has a newMeRequest method which calls the ++**/user/me**++ endpoint to fetch the user data for the given access token. ++*By default a newMeRequest method fetches default fields from a user object.*++ If you need any additional fields, or want to reduce the response payload for performance reasons, you can add a fields parameter and request specific fields. [color=#55a6e8] ``` java== public void getUserInfo(AccessToken token){ GraphRequest request = GraphRequest.newMeRequest(token, new GraphRequest.GraphJSONObjectCallback() { @Override public void onCompleted(JSONObject user, GraphResponse response) { Log.d("HEYOBJECT",user.toString()); try { //You can get information like this v String name = user.getString("name"); String img_url = user.getJSONObject("picture").getJSONObject("data").getString("url"); String email = object.getString("email"); } catch (JSONException e) { e.printStackTrace(); } } }); Bundle parameters = new Bundle(); //Here you can decide what fields you want to get returned: parameters.putString("fields","id,name,picture,email"); request.setParameters(parameters); request.executeAsync(); } ``` This is how the information will seem to be in onCompleted as jsonObject: ``` java== { "id":"User FB ID", "name":"User FB Name", "picture": {"data": {"height":50, "is_silhouette":false, "url":"Picture url", "width":50} }, "email":"User FB Email" } ``` #### How to get the fields you want? >parameters.putString("fields","id,name,picture,email");[color=#55a6e8] Check which information you can get, and which need App Review: https://developers.facebook.com/docs/facebook-login/permissions#reference-default ## Log in automatically **Did users log in once?** Then avoid bothering users to log in the second time! You can check whether they log in before by using the code below: ``` java== AccessToken accessToken = AccessToken.getCurrentAccessToken(); boolean isLoggedIn = accessToken != null && !accessToken.isExpired(); if(isLoggedIn){ //Log in actions // } ``` ## Customize your FB button! 1. Rectangle Rounded button 2. Round Button ++Note:++ FB Logo Usage conditions: https://en.facebookbrand.com/#brand-guidelines-assets ### 1. Want a rounded corner FB button? ![](https://i.imgur.com/Tf9Idvp.png =200x100) Then you need a **++*shape drawable* and an *update in XML*++**: **Update XML:** ``` java== <FrameLayout android:layout_width="250dp" android:layout_height="50dp" android:layout_gravity="center"> <com.facebook.login.widget.LoginButton android:id="@+id/btn_fb_login" android:layout_width="match_parent" android:layout_height="match_parent" android:visibility="gone"/> <Button android:id="@+id/fb" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/button_rounded_fb" android:drawableStart="@drawable/fb_logo_24px" android:drawableLeft="@drawable/fb_logo_24px" android:paddingEnd="20dp" android:paddingStart="20dp" android:text="@string/fb" android:textAllCaps="false" android:textColor="#ffffff" android:textSize="14sp" android:textStyle="bold"/> </FrameLayout> ``` **Shape Drawable:** This one will be used as button background in XML. ``` java== <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <stroke android:color="#FFFF" android:width="1dp"/> <corners android:radius="40dp"/> <solid android:color="@color/colorFb"/> </shape> ``` ### 2. Round Button Instead of buton, you will have an ImageButton to replace the original one. By centering the image in the middle, we will get what we want: ![](https://i.imgur.com/YXfXri3.png =50x50) ``` java== <FrameLayout android:layout_width="50dp" android:layout_height="50dp" android:layout_gravity="center"> <com.facebook.login.widget.LoginButton android:id="@+id/btn_fb_logins" android:layout_width="match_parent" android:layout_height="match_parent" android:visibility="gone"/> <ImageButton android:id="@+id/fbs" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/button_rounded_fb" android:src="@drawable/fb_logo_24px" android:padding="8dp" android:scaleType="centerInside"/> </FrameLayout> ``` ## Note: Progress order :::success This is how it will proccess in order: 1. onActivityResult 2. FacebookCallback 3. onCurrentAccessTokenChanged 4. GraphRequest.newMeRequest -> onCompleted :::