Login And Profile Access With Latest Facebook SDK

In this tutorial, you will learn about how to perform login and profile access with latest facebook SDK. You will learn how to perform action on behalf of user by getting permission etc.

Android Facebook SDK enables people to login to your app with Facebook Login. When people login using facebook, they also grant permission to your app to perform action on facebook on their behalf. So, you need to provide permissions details you want to be granted by the user before they login using facebook. When user try to login, they see the permission details, edit it if needed and grant the rest permissions to you. Once the permission is granted, you can post, like, get profile data on user’s behalf.

This tutorial is next part of Basic setup for Android Facebook Integration where we have done basic setup to integrate facebook into our android application. If you have not gone through previous post, please have a look at it. Otherwise, you might feel difficult to understand this post.

Output

Tutorialwing - Android facebook Integration  - Login, Profile Access

Tutorialwing – Android facebook Integration – Login, Profile Access

Source Code

facebook integration tutorial Source code

1. Getting Started

In this part, we will show to perform login and profile access with latest facebook SDK. Basically, you will learn how to login, get profile data, get access token etc. using android facebook SDK.

1.1 Add FacebookActivity to Manifest file.

Android Facebook SDK provides an activity that will open while login. You need to add that activity to your AndroidManifest.xml file.

<activity android:name="com.facebook.FacebookActivity"
          android:configChanges=
                 "keyboard|keyboardHidden|screenLayout|screenSize|orientation"
          android:theme="@android:style/Theme.Translucent.NoTitleBar"
          android:label="@string/app_name" />

Finally, AndroidManifest.xml file would look like below

<?xml version="1.0" encoding="utf-8"?>
<manifest package="tutorialwing.com.facebookintegrationtutorial"
          xmlns:android="http://schemas.android.com/apk/res/android">

    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:name=".MyApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <meta-data
            android:name="com.facebook.sdk.ApplicationId"
            android:value="@string/facebook_app_id"/>

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>

        <activity
            android:name="com.facebook.FacebookActivity"
            android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
            android:label="@string/app_name"
            android:theme="@android:style/Theme.Translucent.NoTitleBar"/>
    </application>
</manifest>

For the readers who has not gone through Basic setup for Android Facebook Integration, please don’t panic. This file contains basic setups to integrate facebook into your applications. If you want to understand it clearly, please go through it.

1.2 Use LoginButton in Fragment

You need to add fragment. So, Create a fragment and it’s layout(LoginFragment.java and fragment_login.xml).
The simplest way to use facebook login in your app is to use Facebook LoginButton. This is custom view implementation of button and provided by android facebook SDK. This wraps funtionality available in the LoginManager. When someone clicks on the button, the login is initiated with the permission set in LoginManager. The Button follows the LoginState and changes it’s text based on login/logout state. LoginButton code is as below.

    <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_marginBottom="30dp"
        android:layout_marginTop="30dp"/>

1.2.1 Add LoginButton in xml file

Add Facebook LoginButton in fragment xml file. Also, add a textview to show username after successful login.
Your fragment xml file would look like below.
fragment_login.xml file

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical">

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_margin="10dp"/>

    <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_marginBottom="30dp"
        android:layout_marginTop="30dp"/>
</LinearLayout>

1.2.2 Setup Fragment Class

Now, we will write the code to login using facebook sdk in LoginFragment.java. Before that you need to be familiarised with some terms. Some common terms used are:

LoginManager: Manages login process, handle responses etc with requested read or publish permissions.
CallbackManager: It is used to route callbacks to the facebook SDK with your registered callbacks. You should call it from the initiating activity or fragments onActivityResult call.
AccessToken: It shows user-id, accepted and denied permissions and token got after login.
Profile: This class has basic information about the person logged in.

Follow the steps below to add LoginButton.

a. Initialise facebook sdk
// Initialize facebook SDK.

FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
b. Create a callback manager to handle login responses
// Create a callbackManager to handle the login responses.

callbackManager = CallbackManager.Factory.create();

Then, call onActivityResult() method of callbackManager to pass login results to the callbackManager.
Note: Every activity and fragment that you integrate with the FacebookSDK Login or Share should forward on ActivityResult to the callbackManager.

@Override

public void onActivityResult(int requestCode, int resultCode, Intent data) {

	super.onActivityResult(requestCode, resultCode, data);


	// Call callbackManager.onActivityResult to pass login result to the LoginManager via callbackManager.
   callbackManager.onActivityResult(requestCode, resultCode, data);

}
c. Setup a callback

Next you need to set callback to be called once user is logged in .

private FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() {

	@Override

	public void onSuccess(LoginResult loginResult) {

		AccessToken accessToken = loginResult.getAccessToken();

		Toast.makeText(getActivity(), "AccessToken = " + accessToken, Toast.LENGTH_SHORT).show();
		// Add code to perform some action when user is logged in.
	}


	@Override

	public void onCancel() {

		Toast.makeText(getActivity(), "User Cancelled login", Toast.LENGTH_SHORT).show();

		// Add code to perform some actions when cancel login process
	}


	@Override

	public void onError(FacebookException e) {

		Toast.makeText(getActivity(), "Error occurred while login", Toast.LENGTH_SHORT).show();

		// Add code to perform some actions when some error occured while login.
	}

};
d. Customize LoginButton

You can customize login button i.e, you can set permissions to be granted, register callback etc. Also, If you are using the button in the fragment, you need to set fragment on the button by calling setFragment(this).

LoginButton loginButton = (LoginButton) view.findViewById(R.id.login_button);
loginButton.setReadPermissions("user_friends"); 

loginButton.setFragment(this);

loginButton.registerCallback(callbackManager, callback);

Till this point, we have successfully written code to login/logout user from faceboook. Now, we need to keep track of when user login/logout from facebook. Based on that, we will update our applications. Facebook SDK has provided ProfileTracker and AccessTokenTracker for this purposes.




How to use AccessTokenTracker provided by FacebookSDK

Whenever there is a change in AccessToken, AccessTokenTracker calls method onCurrentAccessTokenChanged to inform that there is a change in accessToken. This method has old accessToken and current accessToken as it’s parameters. To use it in applications follow steps below.
a. Get an instance of AccessTokenTracker

private AccessTokenTracker accessTokenTracker;

b. Initialise it as below

accessTokenTracker= new AccessTokenTracker() {
	@Override
	protected void onCurrentAccessTokenChanged(AccessToken oldToken, AccessToken newToken) {
		Toast.makeText(getActivity(), "AccessToken changed", Toast.LENGTH_SHORT).show();
	}
};

c. Now, you need to call startTracking/stopTracking method to start/stop tracking the accessToken changes in application. Call stopTracking method when you want to stop tracking about any changes in accessToken. We have called accessTokenTracker.startTracking() in onCreate method and accessTokenTracker.stopTracking() in onStop method in fragment.

How to use ProfileTracker provided by FacebookSDK

Whenever there is any change in profile, ProfileTracker calls onCurrentProfileChanged method to inform the application that profile has changed. It takes old profile and current profile as it’s parameters. To use it in applications, follow steps below.
a. Get an instance of ProfileTracker

private ProfileTracker profileTracker;

b. Initialise it as below.

profileTracker = new ProfileTracker() {
	@Override
	protected void onCurrentProfileChanged(Profile oldProfile, Profile newProfile) {
		displayMessage(newProfile);
	}
};

c. Now, you need to call startTracking/stopTracking method to start/stop tracking the profile changes in application. Call stopTracking method when you want to stop tracking about any changes in profile. We have called profileTracker.startTracking() in onCreate method and profileTracker.stopTracking() in onStop method in fragment.

Final LoginFragment.java code

After all the setup, Our LoginFragment.java class would look like below

package tutorialwing.com.facebookintegrationtutorial;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.AccessToken;
import com.facebook.AccessTokenTracker;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.Profile;
import com.facebook.ProfileTracker;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;

public class LoginFragment extends Fragment {

	private CallbackManager callbackManager;

	private TextView textView;

	private AccessTokenTracker accessTokenTracker;
	private ProfileTracker profileTracker;


	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// Initialize facebook SDK.
		FacebookSdk.sdkInitialize(getActivity().getApplicationContext());

		// Create a callbackManager to handle the login responses.
		callbackManager = CallbackManager.Factory.create();

		accessTokenTracker= new AccessTokenTracker() {
			@Override
			protected void onCurrentAccessTokenChanged(AccessToken oldToken, AccessToken newToken) {
				Toast.makeText(getActivity(), "AccessToken changed", Toast.LENGTH_SHORT).show();
			}
		};

		profileTracker = new ProfileTracker() {
			@Override
			protected void onCurrentProfileChanged(Profile oldProfile, Profile newProfile) {
				displayMessage(newProfile);
			}
		};

		accessTokenTracker.startTracking();
		profileTracker.startTracking();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fragment_login, container, false);
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);

		textView = (TextView) view.findViewById(R.id.textView);
		customizeLoinButton(view);
	}

	private void customizeLoinButton(View view) {
		LoginButton loginButton = (LoginButton) view.findViewById(R.id.login_button);
		loginButton.setReadPermissions("user_friends");
		loginButton.setFragment(this);
		loginButton.registerCallback(callbackManager, callback);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		// Call callbackManager.onActivityResult to pass login result to the LoginManager via callbackManager.
		callbackManager.onActivityResult(requestCode, resultCode, data);
	}

	private FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() {
		@Override
		public void onSuccess(LoginResult loginResult) {
			AccessToken accessToken = loginResult.getAccessToken();
			Toast.makeText(getActivity(), "AccessToken = " + accessToken, Toast.LENGTH_SHORT).show();
		}

		@Override
		public void onCancel() {
			Toast.makeText(getActivity(), "User Cancelled login", Toast.LENGTH_SHORT).show();
		}

		@Override
		public void onError(FacebookException e) {
			Toast.makeText(getActivity(), "Error occurred while login", Toast.LENGTH_SHORT).show();
		}
	};

	private void displayMessage(Profile profile){
			String name = (profile != null) ? profile.getName() : "User not logged in";
			textView.setText(name);
	}

	@Override
	public void onStop() {
		super.onStop();
		accessTokenTracker.stopTracking();
		profileTracker.stopTracking();
	}

	@Override
	public void onResume() {
		super.onResume();
		Profile profile = Profile.getCurrentProfile();
		displayMessage(profile);
	}
}



1.3 Add Fragment in Activity to use Login feature

We have done all the setups to use facebook login in our applications. Now, Add LoginFragment in our MainActivity as below.
MainActivity.java

package tutorialwing.com.facebookintegrationtutorial;

import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		addFragment();
	}

	private void addFragment() {
		LoginFragment loginFragment = new LoginFragment();
		FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
		fragmentTransaction.add(R.id.facebook_login_button, loginFragment);
		fragmentTransaction.commit();
	}
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin">

    <LinearLayout
        android:id="@+id/facebook_login_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

    </LinearLayout>

</RelativeLayout>

That’s all for Login using facebook SDK.

Output

If you run the app at this point, you will see a facebook login prompt is opened when you click on login button. When you enter your user credential, it will ask for permission to be granted. You can edit the permission and click ok. Notice that button text is changed based on login status of user. A TextView is added to show UserName when user is logged-in.

Note: If you face any difficulty in this process, you can download the source code from above link.

Conclusion

Android Facebook SDK is easily understandable and very useful when we want to promote our business via social media. We can use Android Facebook SDK in our android application to login, share content etc. Here, we have discussed about how to perform login and profile access with latest facebook sdk, get access token and get profile details of logged-in user using facebook SDK.

One Response

  1. Rajeev Kumar October 12, 2016

Leave a Reply