Here, we will talk about facebook integration in android application. Now, it’s very easy to integrate facebook into android applications using android facebook SDK. You can easily share post, media, videos, link etc. using just a few lines of code.
We have also published some related tutorials in facebook integration series. If you wish, you can check it out –
TABLE OF CONTENT
Output
At the end of this tutorial, you will get output similar as below.
Source Code
Android facebook integration – share media tutorial source code
1. Getting Started
In this tutorial, you will learn how to share media files (i.e. images, videos etc.) using latest android facebook SDK. We will use ShareButton, provided by Android facebook SDK, for this purpose.
1.1 Creating a new project
Follow steps below to create new project. Please ignore the steps if you have already created a new application.
Step | Description |
---|---|
1. | Open Android Studio. |
2. | Go to File => New => New Project. Write application name as AndroidFacebookShareMediaTutorial. Then, click next button. |
3. | Select minimum SDK you need. However, we have selected 21 as minimum SDK. Then, click next button |
4. | Then, select Empty Activity => click next => click finish. |
5. | If you have followed above process correctly, you will get a newly created project successfully. However, you can also visit post to create a new project to know steps in detail. |
1.2. Basic setup for Android Facebook SDK
You need to do some setup to use facebook sdk into your application. I have already discussed about it into this tutorial. Please have a look at this post and integrate facebook sdk into your project. However, let me give brief explanation about what i have done till now to setup facebook sdk.
1.2.1 Add facebook-sdk gradle into app/build.gradle.
repositories { mavenCentral() } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:24.2.0' compile 'com.facebook.android:facebook-android-sdk:[4,5)' compile 'com.android.support:support-v4:24.2.0' }
1.2.2 Add facebook ID string into strings.xml file
<string name="facebook_app_id">YOUR FACEBOOK APP ID</string>
1.2.3 Add internet permission and meta data into AndroidManifest.xml file.
Add internet permission, ContentProvider and meta data into AndroidManifest.xml file. Replace YOUR_FACEBOOK_APP_ID with your facebook app id in ContentProvider. Finally, AndroidManifest.xml file would look like below.
<?xml version="1.0" encoding="utf-8"?> <manifest package="com.tutorialwing.androidfacebooksharemediatutorial" xmlns:android="http://schemas.android.com/apk/res/android"> <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <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"/> <provider android:authorities="com.facebook.app.FacebookContentProviderYOUR_FACEBOOK_APP_ID" android:name="com.facebook.FacebookContentProvider" android:exported="true"/> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity> </application> </manifest>
1.2.4 Create MyApplication class
Create a class named MyApplication and extend it with Application class. Then, write code to print KeyHash in it.
Note: You don’t need this class if you don’t want to print keyHash.
MyApplication.java class
package com.tutorialwing.androidfacebooksharemediatutorial; import android.app.Application; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.Signature; import android.util.Base64; import android.util.Log; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class MyApplication extends Application { @Override public void onCreate() { super.onCreate(); printHashKey(); } /** * Method that prints hash key. */ public void printHashKey() { try { PackageInfo info = getPackageManager().getPackageInfo( "com.tutorialwing.androidfacebooksharemediatutorial", 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) { } } }
Don’t forget to add android:name=”.MyApplication” for application in AndroidManifest.xml.
<application android:name=".MyApplication" --------> </application>
1.2.5 MainActivity Preview
You have MainActivity.java and activity_main.xml file. At this point of time, It would look like below.
MainActivity.java
package com.tutorialwing.androidfacebooksharemediatutorial; import android.os.Bundle; 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); } }
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"> </RelativeLayout>
1.3 Start Implementing Android Share Button to Share Media files using latest Android Facebook SDK
Now, Everything is setup. So, we will see how to use Android Facebook Share Button into android application to share media files using latest Android Facebook SDK. We will do this in following steps.
a. Create a fragment ShareMediaFragment.java and it’s layout fragment_share.xml. Write code to show share button and implement it’s functionality.
b. Use this fragment in MainActivity.java and show final output.
Let’s start with first step.
1.3.1 Create Fragment and implement android facebook share button into it
Create a fragment (named ShareMediaFragment.java) and an xml file (named fragment_share.xml).
We use ShareButton widget, provided by Facebook SDK, to implement share image functionality into our application.
<com.facebook.share.widget.ShareButton android:id="@+id/fb_share_button" android:layout_width="wrap_content" android:layout_height="wrap_content"/>
Add this button into xml file and write code to share image in java file.
1.3.1.1 Add ShareButton widget into xml file
Open fragment_share.xml file and add ShareButton widget into this file.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <com.facebook.share.widget.ShareButton android:id="@+id/fb_share_button" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </LinearLayout>
1.3.1.2 Write code to share image into Java file
In ShareImageFragment.java class, you need to do following setup,
a. Initialise facebook sdk
// Initialize facebook SDK. FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
b. Set up CallbackManager
Create an instance of callbackManager to handle login responses. Call callbackManager.onActivityResult(requestCode, resultCode, data), in onActivityResult method, to pass loginResult to LoginManager via callBackManager.
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //Code to perform other actions.... // Create a callbackManager to handle the login responses. callbackManager = CallbackManager.Factory.create(); } @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. Define Content you want to share
Version 4.0+ have new models for sharing content. Each type of content people want to share has new class. So, you need to use proper class accordingly. For example, if you want to share Link, you need to use ShareLinkContent class. In this tutorial, we are going to share media files( it can be audio or video files both). So, we will use ShareMediaContent class. Moreover, an instance of SharePhoto or ShareVideo class can be used to describe the photo or video to be shared. An image with name ani_cat.jpeg is there in drawable folder. you can get this image by downloading the source code from the link given at start of this tutorial.
Bitmap image = BitmapFactory.decodeResource(getResources(), R.drawable.ani_cat); SharePhoto sharePhoto = new SharePhoto.Builder() .setBitmap(image) .build(); //ShareVideo shareVideo = new ShareVideo.Builder() // .setLocalUrl(...) // .build(); ShareMediaContent content = new ShareMediaContent.Builder() .addMedium(sharePhoto) // .addMedium(shareVideo) .build();
Some methods being used to set Content are:
addMedium method : Sets the media files you want to share.
Rest methods used here are self descriptive.
Thus, Content to be shared is complete. Now, set the content to ShareButton.
d. Set Content to ShareButton
Facebook SDK has provided ShareButton which can be used to share content. In this post, it has been used to perform share operation. You need to set the content you want to share into this button.
ShareButton shareButton = (ShareButton) view.findViewById(R.id.fb_share_button); // Set the content you want to share. shareButton.setShareContent(content);
e. Set the ShareDialog. Define the Callback for ShareDialog
When you click on ShareButton, ShareDialog is opened which shows the preview of the content you are about to share. You can edit the preview, set visibility, add some messages etc. according to your choice. Then, click on POST button to share the content. For this actions to perform, you need to setup the ShareDialog. So, Create an instance of ShareDialog in onCreate method. Then, define the callback and register this callback to ShareDialog in onCreate method.
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); shareDialog = new ShareDialog(this); // this part is optional shareDialog.registerCallback(callbackManager, callback); } private FacebookCallback<Sharer.Result> callback = new FacebookCallback<Sharer.Result>() { @Override public void onSuccess(Sharer.Result result) { Log.v(TAG, "Successfully posted"); // Write some code to do some operations when you shared content successfully. } @Override public void onCancel() { Log.v(TAG, "Sharing cancelled"); // Write some code to do some operations when you cancel sharing content. } @Override public void onError(FacebookException error) { Log.v(TAG, error.getMessage()); // Write some code to do some operations when some error occurs while sharing content. } };
Final ShareMediaFragment.java class code
package com.tutorialwing.androidfacebooksharemediatutorial; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.facebook.CallbackManager; import com.facebook.FacebookCallback; import com.facebook.FacebookException; import com.facebook.FacebookSdk; import com.facebook.share.Sharer; import com.facebook.share.model.ShareMediaContent; import com.facebook.share.model.SharePhoto; import com.facebook.share.widget.ShareButton; import com.facebook.share.widget.ShareDialog; public class ShareMediaFragment extends Fragment { private static final String TAG = ShareMediaFragment.class.getName(); private ShareDialog shareDialog; private CallbackManager callbackManager; @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(); shareDialog = new ShareDialog(getActivity()); // This part is optional shareDialog.registerCallback(callbackManager, callback); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_share, container, false); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); setMediaShare(view); } private void setMediaShare(View view) { Bitmap image = BitmapFactory.decodeResource(getResources(), R.drawable.ani_cat); SharePhoto sharePhoto = new SharePhoto.Builder() .setBitmap(image) .build(); // ShareVideo shareVideo = new ShareVideo.Builder() // .setLocalUrl(...) // .build(); ShareMediaContent content = new ShareMediaContent.Builder() .addMedium(sharePhoto) // .addMedium(shareVideo) .build(); ShareDialog shareDialog = new ShareDialog(this); shareDialog.show(content, ShareDialog.Mode.AUTOMATIC); ShareButton shareButton = (ShareButton) view.findViewById(R.id.fb_share_button); shareButton.setShareContent(content); } @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<Sharer.Result> callback = new FacebookCallback<Sharer.Result>() { @Override public void onSuccess(Sharer.Result result) { Log.e(TAG, "Successfully posted"); // Write some code to do some operations when you shared content successfully. } @Override public void onCancel() { Log.e(TAG, "Cancel occurred"); // Write some code to do some operations when you cancel sharing content. } @Override public void onError(FacebookException error) { Log.e(TAG, error.getMessage()); // Write some code to do some operations when some error occurs while sharing content. } }; }
1.3.2 Use ShareMediaFragment in MainActivity.java and show final output.
We have successfully created content to share and set this in ShareButton inside ShareMediaFragment class. Now, we will add this ShareMediaFragment fragment to MainActivity and will show the final output. Finally, MainActivity.java class and activity_main.xml file would look like below.
MainActivity.java class
package com.tutorialwing.androidfacebooksharemediatutorial; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); addShareMediaFragment(); } private void addShareMediaFragment() { FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); fragmentTransaction.add(R.id.facebook_share_button, new ShareMediaFragment()); fragmentTransaction.commit(); } }
activity_main.xml file.
<?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_share_button" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> </LinearLayout> </RelativeLayout>
That’s all for Sharing media files using latest android facebook SDK.
Output
If you run the app, you will see a share button. Clicking on this button will show a dialog containing the content you are about to share. You can change the preview according to your choice. Then, click on POST button to share the content. Finally, you will get output as shown above.
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 for example images, audio files, video files or any media files etc. We have discussed each and everything in a separate post. You can check out these tutorials as well. Hope this tutorial helped you.
You must be logged in to post a comment.