This post is about how to enable users of your Android app to share data (links, photos, and videos) from your app to Facebook.
Get Github code from HERE.
The Sharing SDK
The Sharing SDK for Android is used to share data from your app to Facebook. It is a component of the Facebook SDK for Android.
When someone shares from your app, the content that they share appears on their Timeline. Content that your users share to their Timeline can also appear in the News Feeds of their friends.
Follow the steps below to add Facebook Sharing SDK to your app:
1 . Go to facebook developer site and log in using your Facebook account.
2 . After login, click on My Apps option shown at the top right.
3 . Now, select an app or create a new one.
Import the Facebook SDK
4 . Open Project-level build.gradle file and add the mavenCentral() repository to download the SDK from the Maven Central Repository:
buildscript {
repositories {
google()
mavenCentral()
}
5 . Open App-level build.gradle file and add the latest version of the SDK dependency under the dependencies section and then click on Sync Now.
dependencies {
implementation 'com.facebook.android:facebook-share:latest.release'
}
Edit Your Resources and Manifest
6 . Open your /app/res/values/strings.xml file and add the below string elements:
<resources>
<!--
On the Dashboard, navigate to Settings > Basic > App ID.
-->
<string name="facebook_app_id">"ENTER YOUR APP ID"</string>
<!--
On the Dashboard, navigate to Settings > Advanced > Security > Client token.
-->
<string name="facebook_client_token">"ENTER YOUR CLIENT TOKEN"</string>
</resources>
7 . Open /app/manifest/AndroidManifest.xml file:
- Add meta-data elements to the application element for your app ID and client access token:
<application android:label="@string/app_name" ...>
...
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="@string/facebook_app_id" />
<meta-data
android:name="com.facebook.sdk.ClientToken"
android:value="@string/facebook_client_token" />
...
</application>
- Add an activity for Facebook inside your application element:
<activity
android:name="com.facebook.FacebookActivity"
android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:label="@string/app_name" />
- Add a uses-permission element for the internet to the manifest above the application element:
<uses-permission android:name="android.permission.INTERNET" />
- Add a ContentProvider to your AndroidManifest.xml file and set {APP_ID} to your app ID:
<provider android:authorities="com.facebook.app.FacebookContentProvider{APP_ID}"
android:name="com.facebook.FacebookContentProvider"
android:exported="true"/>
- Add the following queries block to your AndroidManifest.xml file outside the application element to make the Facebook App visible to your App:
<queries>
<provider android:authorities="com.facebook.katana.provider.PlatformProvider" />
</queries>
Creating the Layout File
The below layout file consist of three buttons (to share a link, photo, and video to Facebook).
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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=".MainActivity">
<Button
android:id="@+id/btn_share_link"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Share Link"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/btn_share_photo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="Share Photo"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/btn_share_link" />
<Button
android:id="@+id/btn_share_video"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="Share Video"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/btn_share_photo" />
</androidx.constraintlayout.widget.ConstraintLayout>
The UI of the above layout file looks like this:
Creating the Application class
The MyApplication class contains a printHashKey() method which will create a key hash for your app.
MyApplication.kt
package com.c1ctech.sharedatatofacebook
import android.app.Application
import android.content.pm.PackageManager
import android.util.Base64
import android.util.Log
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
class MyApplication: Application() {
override fun onCreate() {
super.onCreate()
printHashKey()
}
//Method that prints hash key.
fun printHashKey() {
try {
val info = packageManager.getPackageInfo(
"com.c1ctech.sharedatatofacebook",
PackageManager.GET_SIGNATURES
)
for (signature in info.signatures) {
val md: MessageDigest = MessageDigest.getInstance("SHA")
md.update(signature.toByteArray())
Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT))
}
} catch (e: PackageManager.NameNotFoundException) {
} catch (e: NoSuchAlgorithmException) {
}
}
}
Open the AndroidManifest.xml file and add the application name property as shown below:
<application
android:name=".MyApplication"
....
</application>
Adding package name, activity class name, and key hash
- Open your app from here, then go to Settings > Basic.
- Now scroll to the bottom and click on +Add Platform.
- Select the platform to Android and then click on next.
- Add the above created key hash, application package name, and class name. Finally, click on save changes:
Creating the MainActivity File
The MainActivity.kt file contains the below code:
MainActivity.kt
package com.c1ctech.sharedatatofacebook
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.c1ctech.sharedatatofacebook.databinding.ActivityMainBinding
import com.facebook.CallbackManager
import com.facebook.FacebookSdk
import com.facebook.share.widget.ShareDialog
import android.content.Intent
import com.facebook.share.model.*
class MainActivity : AppCompatActivity() {
private val REQUEST_VIDEO_CODE: Int = 1000
lateinit var activityMainBinding: ActivityMainBinding
lateinit var shareDialog: ShareDialog
lateinit var callbackManager: CallbackManager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
activityMainBinding = ActivityMainBinding.inflate(layoutInflater)
// initializes the Facebook SDK
FacebookSdk.sdkInitialize(applicationContext)
setContentView(activityMainBinding.root)
// create an instance of callbackManager
// It manages the callbacks into the FacebookSdk from an Activity's onActivityResult()'s method.
callbackManager = CallbackManager.Factory.create()
//create a ShareDialog.
shareDialog = ShareDialog(this)
//share a link from this app to Facebook
activityMainBinding.btnShareLink.setOnClickListener {
val linkContent = ShareLinkContent.Builder()
.setContentUrl(Uri.parse("https://www.youtube.com/"))
.setQuote("Useful link")
.build()
//returns True if the ShareLinkContent type can be shown via the dialog
if (ShareDialog.canShow(ShareLinkContent::class.java)) {
shareDialog.show(linkContent)
}
}
//share a photo from this app to Facebook
activityMainBinding.btnSharePhoto.setOnClickListener {
val image: Bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.tiger)
val photo = SharePhoto.Builder()
.setBitmap(image)
.build()
//returns True if the SharePhotoContent type can be shown via the dialog
if (ShareDialog.canShow(SharePhotoContent::class.java)) {
val photoContent = SharePhotoContent.Builder()
.addPhoto(photo)
.build()
shareDialog.show(photoContent)
}
}
//share a video from this app to Facebook
activityMainBinding.btnShareVideo.setOnClickListener {
// uploading video from phone
val sharingIntent = Intent()
sharingIntent.setType("video/*")
sharingIntent.setAction(Intent.ACTION_GET_CONTENT)
startActivityForResult(
Intent.createChooser(sharingIntent, "Select a video"),
REQUEST_VIDEO_CODE
)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
// call the SDK's callbackManager in your onActivityResult to handle the response
callbackManager.onActivityResult(requestCode, resultCode, data)
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_VIDEO_CODE) {
val videoUrl = data?.data
val video = ShareVideo.Builder()
.setLocalUrl(videoUrl)
.build()
val videoContent = ShareVideoContent.Builder()
.setVideo(video)
.setContentTitle("This is useful video")
.setContentDescription("Video made by me")
.build()
//returns True if the ShareVideoContent type can be shown via the dialog
if (ShareDialog.canShow(ShareVideoContent::class.java)) {
shareDialog.show(videoContent)
}
}
}
}
}
In the above code,
- sdkInitialize() method initializes the Facebook SDK.
- The instance of callbackManager manages the callbacks into the FacebookSdk from the Activity’s onActivityResult() method.
- To share links, we need to create a ShareLinkContent object which describes link content to be shared.
- To share photos, we need to create a SharePhotoContent object which describes photo content to be shared.
- To share videos, we need to create a ShareVideoContent object which Provides the interface for video content to be shared.
- The Share dialog switches to the native Facebook for Android app then returns control to your app after a post is published.
- The share dialog canShow() method returns true if the specified content type can be shown via the dialog.
Given below is the screenshot of the app when you share a link to Facebook.
Similarly, when you share a photo and a video to Facebook, it will look like this: