Skip to main content

Android Integrating Facebook Login

Users can sign up in your app using their Facebook account , that would make your app more user-friendly. Follow these steps to enable Facebook login- 

1. Create a new project in android studio and give a unique package name , then fill all other necessary details.
2. Go to Facebook for developers and create a new app and create app Id.
3. A new window will be opened, click on Settings then on Add Platform, select Android. A form will appear something like this-
  • Enter the package name and the class name. In my case , class name is MainActivity.
  • Now, for key Hashes, open command prompt and execute the following command and if it asks for password enter "android"-
keytool -exportcert -alias androiddebugkey -keystore "C:\Users\%USERNAME%\.android\debug.keystore" | openssl sha1 -binary | openssl base64
(If you get the error stating "keytool is not recognized as an internal or external command",make sure the directory to keytool.exe is on path- C:\Program Files\Java\jre(version no.)\bin).
  • Paste the key hash to the Key Hashes field and save the details.
4. Now, add Facebook SDK into your project. Open  project-level build.gradle  and add mavenCentral() repository. Add this line of code inside buildscript{}-
repositories {
        jcenter()
        mavenCentral()
    }
5. Open app-level build.gradle to add the following dependency-
dependencies {
    compile 'com.facebook.android:facebook-android-sdk:4.6.0'    }
6. Copy you App Id, open app/res/values/strings.xml in your project and add this line of code-
<string name="facebook_app_id">Your App Id</string>
7. Open AndroidManifest.xml -
  • Add internet permission-
<uses-permission android:name="android.permission.INTERNET"/>
  • Add meta-data element inside application tab-
<meta-data android:name="com.facebook.sdk.ApplicationId"
            android:value="@string/facebook_app_id"/>
  • Add FacebookActivity inside application tab-
 <activity android:name="com.facebook.FacebookActivity"
            android:configChanges=
                "keyboard|keyboardHidden|screenLayout|screenSize|orientation"
            android:label="@string/app_name" />
8. Open activity_main.xml and add facebook login button-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="10dp"
    tools:context="com.gunjan.andriodcodesnippets.MainActivity">
   <TextView
       android:id="@+id/tv_signin"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="Facebook Login"
       android:textSize="30sp"
       />
   <com.facebook.login.widget.LoginButton
       android:id="@+id/login_button"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_gravity="center_horizontal"
       android:layout_marginTop="30dp"
       android:layout_marginBottom="30dp" />
</LinearLayout>
9. Now, open MainActivity.java-
In onCreate() method,
  • Initialize FacebookSdk before setContentView().
  • Add a reference to login button.
  • Create a callback Manager.
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        FacebookSdk.sdkInitialize(getApplicationContext());
        setContentView(R.layout.activity_main);
        callBackManager=CallbackManager.Factory.create();

        login_button=(LoginButton)findViewById(R.id.login_button);
    }
Register a callback using LoginButton 
login_button.registerCallback(callBackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                String userId=loginResult.getAccessToken().getUserId();
                Log.e("Test",userId);
                Toast.makeText(getApplicationContext(),"Successfully Signed in",Toast.LENGTH_LONG).show();
            }

            @Override
            public void onCancel() {
                Toast.makeText(getApplicationContext(),"Couldn't sign in",Toast.LENGTH_LONG).show();
            }

            @Override
            public void onError(FacebookException error) {
                Toast.makeText(getApplicationContext(),"Error occurred",Toast.LENGTH_LONG).show();
            }
        });
Now, in onActivityResult(), forward the login results to the callbackManager-
@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        callBackManager.onActivityResult(requestCode,resultCode,data);
    }
The complete MainActivity.java-
public class MainActivity extends AppCompatActivity{
    private LoginButton login_button;
    private CallbackManager callBackManager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        FacebookSdk.sdkInitialize(getApplicationContext());
        setContentView(R.layout.activity_main);
        callBackManager=CallbackManager.Factory.create();

        login_button=(LoginButton)findViewById(R.id.login_button);
        login_button.registerCallback(callBackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                String userId=loginResult.getAccessToken().getUserId();
                Log.e("Test",userId);
                Toast.makeText(getApplicationContext(),"Successfully Signed in",Toast.LENGTH_LONG).show();
            }

            @Override
            public void onCancel() {
                Toast.makeText(getApplicationContext(),"Couldn't sign in",Toast.LENGTH_LONG).show();
            }

            @Override
            public void onError(FacebookException error) {
                Toast.makeText(getApplicationContext(),"Error occurred",Toast.LENGTH_LONG).show();
            }
        });
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        callBackManager.onActivityResult(requestCode,resultCode,data);
    }
}
10. Run the project.

Comments

Popular Posts