How to Integrate Facebook in Android Studio

Kunal Kumar
Sep 7, 2018 · 5 min read
  1. Create New Android Studio project
  2. Provide Permission and and add dependency in Buid gradle

<uses-permission android:name=”android.permission.INTERNET” /> // //In manifest

In build.gradle

compile 'com.facebook.android:facebook-android-sdk:4.5.0'
compile 'com.squareup.picasso:picasso:2.5.2'

3. Create a class name MyApplication , With the help of this is class we are going to intialize FaceBook sdk

public class MyApplication extends Application {
// Updated your class body:
//App id 302760210527933
//hash key DUeaBQu0cH9dwfyGR+tEvPf3kYY=
PackageInfo info;
@Override
public void onCreate() {
super.onCreate();
// Initialize the SDK before executing any other operations,
FacebookSdk.sdkInitialize(getApplicationContext());
AppEventsLogger.activateApp(this);
try {
info = getPackageManager().getPackageInfo("com.you.name", PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md;
md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
String something = new String(Base64.encode(md.digest(), 0));
//String something = new String(Base64.encodeBytes(md.digest()));
Log.e("hash key", something);
}
} catch (PackageManager.NameNotFoundException e1) {
Log.e("name not found", e1.toString());
} catch (NoSuchAlgorithmException e) {
Log.e("no such an algorithm", e.toString());
} catch (Exception e) {
Log.e("exception", e.toString());
}
}
}
// In This class we initialize Facebook Sdk and get hash key

4. Now we register our app in Facebook
Step -1 : https://developers.facebook.com/
Step -2 : Goto MyApps -> Add New App -> Create a New App ID (Write down your app name)

Step 3: After that you get AppId

Step 4 : Then again click on “My App -> Your app -> Setting -> basic → Add Platform -> Select Android -> Put your hash key and package name ”

Now we Done with FACEBOOK Part now come in Coding Side

Create One New Activity —

public class FaceBook_login extends AppCompatActivity {
private final String TAG = FaceBook_login.this.getClass().getName();

private CallbackManager callbackManager;
private AccessToken accessToken;

private LoginButton loginButton;
private RelativeLayout rlProfileArea;
private TextView tvName;
private Button btnShareVideos, btnShareImages;
//int PICK_GALLERY_IMAGE = 101 ,PICK_GALLERY_VIDEO=102;
ShareButton shareButton;
ImageView fb_profile_pic;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_face_book_login);
shareButton = new ShareButton(FaceBook_login.this);

initParameters();
initViews();

// // Add code to print out the key hash
// try {
// PackageInfo info = getPackageManager().getPackageInfo(
// “mb.com.facebooksharingwithlogin”, PackageManager.GET_SIGNATURES);
// for (Signature signature : info.signatures) {
// MessageDigest md = MessageDigest.getInstance(“SHA”);
// md.update(signature.toByteArray());
// Log.d(“KeyHash:”, Base64.encodeToString(md.digest(), Base64.DEFAULT));
// }
// } catch (PackageManager.NameNotFoundException e) {
//
// } catch (NoSuchAlgorithmException e) {
//
// }

AccessTokenTracker accessTokenTracker = new AccessTokenTracker() {
@Override
protected void onCurrentAccessTokenChanged(
AccessToken oldAccessToken,
AccessToken currentAccessToken) {

if (currentAccessToken == null) {
Log.d(TAG, “User logged out successfully”);
rlProfileArea.setVisibility(View.GONE);
}
}
};

}

public void initParameters() {
accessToken = AccessToken.getCurrentAccessToken();
callbackManager = CallbackManager.Factory.create();

}

public void initViews() {

loginButton = (LoginButton) findViewById(R.id.activity_main_btn_login);
rlProfileArea = (RelativeLayout) findViewById(R.id.activity_main_rl_profile_area);
tvName = (TextView) findViewById(R.id.activity_main_tv_name);
btnShareVideos = (Button) findViewById(R.id.btnShareVideos);
btnShareImages = (Button) findViewById(R.id.btnShareImages);
fb_profile_pic= (ImageView)findViewById(R.id.fb_profile_pic);
btnShareVideos.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(“video/*”);
startActivityForResult(intent, 100);
}
});
btnShareImages.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(“image/*”);
startActivityForResult(intent, 200);
}
});

loginButton.setReadPermissions(Arrays.asList(new String[]{“email”, “user_birthday”, “user_hometown”}));

if (accessToken != null) {
getProfileData();
} else {
rlProfileArea.setVisibility(View.GONE);
}

// Callback registration
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
Log.d(TAG, “User login successfully”);
getProfileData();
}

@Override
public void onCancel() {
// App code
Log.d(TAG, “User cancel login”);
}

@Override
public void onError(FacebookException exception) {
// App code
Log.d(TAG, “Problem for login”);
}
});

}

public void getProfileData() {
try {
accessToken = AccessToken.getCurrentAccessToken();
rlProfileArea.setVisibility(View.VISIBLE);
GraphRequest request = GraphRequest.newMeRequest(
accessToken,
new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
URL imageURL;
Log.d(TAG, “Graph Object :” + object);
try {
String name = object.getString(“name”);
tvName.setText(“Welcome, “ + name);
imageURL = new URL(“https://graph.facebook.com/” + object.getString(“id”) + “/picture?type=large”);
String img_url_st = String.valueOf(imageURL);
Picasso.with(FaceBook_login.this).load(img_url_st).placeholder(R.drawable.download).into(fb_profile_pic);

//Bitmap bitmap = BitmapFactory.decodeStream(imageURL.openConnection().getInputStream());
//Bitmap bitmap = BitmapFactory.decodeStream(imageURL.openConnection().getInputStream());
//fb_profile_pic.setImageBitmap(bitmap);

Log.d(TAG, “Name :” + name);
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});

Bundle parameters = new Bundle();
parameters.putString(“fields”, “id, name, link, birthday, gender, email”);
request.setParameters(parameters);
request.executeAsync();
} catch (Exception e) {
e.printStackTrace();
}
}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 100:
if (resultCode == Activity.RESULT_OK) {
Uri uriPhoto = data.getData();
Log.d(TAG, “Selected image path :” + uriPhoto.toString());

Bitmap bitmap = null;
try {
bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uriPhoto));
SharePhoto photo = new SharePhoto.Builder().setBitmap(bitmap)
.build();
SharePhotoContent content = new SharePhotoContent.Builder()
.addPhoto(photo).build();

shareButton.setShareContent(content);
shareButton.performClick();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}

}
break;
case 200:
if (resultCode == RESULT_OK) {
Uri uriVideo = data.getData();

try {
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uriVideo,
filePathColumn, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String videoPath = cursor.getString(columnIndex);
cursor.close();
Log.d(TAG, “Selected video path :” + videoPath);

ShareVideo video = new ShareVideo.Builder()
.setLocalUrl(uriVideo).build();

ShareVideoContent content = new ShareVideoContent.Builder()
.setVideo(video).build();

shareButton.setShareContent(content);
shareButton.performClick();
}
} catch (Exception e) {
e.printStackTrace();
}

}
break;
default:
callbackManager.onActivityResult(requestCode, resultCode, data);
break;
}
}
}

============================================
AND XML is
<?xml version=”1.0" encoding=”utf-8"?>
<RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android"
xmlns:tools=”http://schemas.android.com/tools"
android:layout_width=”match_parent”
android:layout_height=”match_parent”
>

<com.facebook.login.widget.LoginButton
android:id=”@+id/activity_main_btn_login”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_alignParentBottom=”true”
android:layout_centerHorizontal=”true”
android:layout_gravity=”center_horizontal”
android:layout_marginBottom=”20dp”
/>

<RelativeLayout
android:id=”@+id/activity_main_rl_profile_area”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:layout_above=”@+id/activity_main_btn_login”
android:layout_alignParentLeft=”true”
android:layout_alignParentStart=”true”
android:layout_alignParentTop=”true”
android:layout_marginBottom=”20dp”
>

<TextView
android:id=”@+id/activity_main_tv_name”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_alignParentTop=”true”
android:layout_centerHorizontal=”true”
android:layout_marginTop=”100dp”
android:text=”NAME”
android:textColor=”@android:color/black”
android:textSize=”18sp”
/>
<Button
android:id=”@+id/btnShareVideos”
android:layout_width=”match_parent”
android:layout_height=”50dp”
android:layout_centerInParent=”true”
android:text=”Share Video”
android:layout_margin=”10dp”
android:textColor=”#ffffff”
android:background=”@color/colorPrimary”
/>
<Button
android:id=”@+id/btnShareImages”
android:layout_width=”match_parent”
android:layout_height=”50dp”
android:layout_below=”@+id/btnShareVideos”
android:layout_margin=”10dp”
android:textColor=”#ffffff”
android:text=”Share IMage”
android:layout_centerInParent=”true”
android:background=”@color/colorPrimary”
/>
<ImageView
android:id=”@+id/fb_profile_pic”
android:layout_width=”80dp”
android:layout_height=”80dp”
android:layout_centerInParent=”true”

android:layout_below=”@+id/btnShareImages”/>

</RelativeLayout>
</RelativeLayout>

Finally In manifest add

android:name=".MyApplication"Comaplete Manifest is

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

<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: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”
/>
<provider android:authorities=”com.facebook.app.FacebookContentProvider/put your app id”
android:name=”com.facebook.FacebookContentProvider”
android:exported=”true”
/>
<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”
/>
<activity android:name=”.FaceBook_login”>
<intent-filter>
<action android:name=”android.intent.action.MAIN” />

<category android:name=”android.intent.category.LAUNCHER” />
</intent-filter>
</activity>
</application>

</manifest>

=======================================

Result Screen Short

You can Request Complete Demo code — My Email id is kkunalandroid@gmail.com

Thanks and Happy Coding

Kunal Pathak

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade