Share Video Files Using Latest Android Facebook SDK

Hello Readers! Welcome to Android facebook integration series. If you are trying to advertise your app, integrating social media into your application is one of the best way to do it. Number of people using social media like facebook, twitter, LinkedIn etc. are increasing day by day. So, their importance as marketing tools or connecting your business with the people can not be underestimated. Moreover, It’s free. You don’t need to pay a single penny for this.
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. Before starting this tutorial, I strongly recommend to go through How to basic setup for facebook SDK post before you start. This tutorial talks about how to create facebook app, do basic setup etc. These are necessary steps to share any video files using android facebook SDK. However, we have also written post on How to implement Facebook Like Button, Share Link using Latest Android Facebook SDK, Share Image Using Latest Android Facebook SDK. You can check out these tutorials, if you need.

Output

At the end of this tutorial, you will get output similar as below.

Tutorialwing - android facebook share video output

Tutorialwing – android facebook share video output

Source Code

Android Facebook Integration – share video tutorial source code

1. Getting Started

In this tutorial, you will learn how to share video files using latest android facebook SDK. Important thing to notice in this tutorial is that a button (and not ShareButton provided by Android Facebook SDK) has been used to share video files. We have already seen how to use ShareButton to share link and images files using android facebook SDK. If you want to learn how to use ShareButton, you can check Share Link using Latest Android Facebook SDK, Share Image Using Android Facebook SDK tutorials. Similarly, you can use your own widget to perform share operations using Android facebook SDK.

1.1 Creating a new project

Follow steps written below to create a new project.
a. Goto File –> New –> New Project. Then, Write application name as AndroidFacebookShareVideoTutorial and click next.
b. Select Minimum SDK 15 or more –> click next –> Select Empty Activity –> click next –> click finish.
If you have followed above process correctly, you will get a newly created project successfully.

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.androidfacebooksharevideotutorial"
          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.androidfacebooksharevideotutorial;

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.androidfacebooksharevideotutorial",
					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) {
		}
	}
}

If you have added MyApplication class, don’t forget to add android:name=”.MyApplication” 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.androidfacebooksharevideotutorial;

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 Share Video files using latest Android Facebook SDK

Now, Everything is setup. So, we will see how to share video files, using latest Android Facebook SDK, on Button Click. We will do this in following steps.
a. Create a fragment ShareVideoFragment.java and it’s layout fragment_share.xml. Write code to show button and perform share operation on click.
b. Use this fragment in MainActivity.java and show final output.

Let’s start with first step.

1.3.1 Create Fragment and use button to perform share operation on click

Create a fragment (named ShareVideoFragment.java) and an xml file (named fragment_share.xml).

Add button into xml file and write code, in java file, to perform share operations.

1.3.1.1 Add Button widget into xml file

Open fragment_share.xml file and add Button 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">

    <Button
        android:id="@+id/shareButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Share Video"/>

</LinearLayout>



1.3.1.2 Write code to share image into Java file

In ShareVideoFragment.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 video files. So, we will use ShareVideoContent class. Moreover, an instance of ShareVideo class can be used to describe the video to be shared.

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

Some methods being used to set Content are:
setLocalUrl method : Sets the Url of the video you want to share.
setVideo method : Sets the video you want to share.

Thus, Content to be shared is complete. Now, set the content to ShareDialog.

d. Set the ShareDialog. Define the Callback for ShareDialog

When you click on Button, A pop up is opened which shows all the videos present in gallery. You can select any videos you want to share. Then, you will see 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.
	}
};
e. Set the content to ShareDialog

Set the content you want to share to in ShareDialog once it is ready.

shareDialog.show(content, ShareDialog.Mode.AUTOMATIC);
Final ShareVideoFragment.java class code
package com.tutorialwing.androidfacebooksharevideotutorial;

import android.content.Intent;
import android.net.Uri;
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 android.widget.Button;

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.ShareVideo;
import com.facebook.share.model.ShareVideoContent;
import com.facebook.share.widget.ShareDialog;

import static android.app.Activity.RESULT_OK;

public class ShareVideoFragment extends Fragment {

	private static final String TAG = ShareVideoFragment.class.getName();

	private CallbackManager callbackManager;

	ShareDialog shareDialog;

	@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);
		setButtonShare(view);
	}

	private void setButtonShare(View view) {
		Button shareButton = (Button) view.findViewById(R.id.shareButton);
		shareButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.setType("video/*");
				intent.setAction(Intent.ACTION_GET_CONTENT);
				startActivityForResult(Intent.createChooser(intent, "Complete action using"), 1);
			}
		});
	}

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

		if (resultCode != RESULT_OK)
			return;

		if (requestCode == 1) {
			Uri videoFileUri = data.getData();
			ShareVideo video = new ShareVideo.Builder()
					.setLocalUrl(videoFileUri)
					.build();
			ShareVideoContent content = new ShareVideoContent.Builder()
					.setVideo(video)
					.build();

			shareDialog.show(content, ShareDialog.Mode.AUTOMATIC);
		} else {
			// 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, "Succesfully posted");
			// Write some code to do some operations when you shared content successfully.
		}

		@Override
		public void onCancel() {
			Log.e(TAG, "Cancel occured");
			// 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 ShareVideoFragment in MainActivity.java and show final output.

We have successfully created content to share and set this in ShareDialog inside ShareVideoFragment class. Now, we will add this ShareVideoFragment 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.androidfacebooksharevideotutorial;

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);

		addVideoFragment();
	}

	private void addVideoFragment() {
		ShareVideoFragment shareVideoFragment = new ShareVideoFragment();
		FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
		fragmentTransaction.add(R.id.facebook_like_button, shareVideoFragment);
		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 video files using latest android facebook SDK.




Output

If you run the app, you will see a button. Clicking on this button will show a pop containing all the videos present in gallery, When you select any videos to share, it will show preview of the videos you are about to share in facebook. However, you can change the preview according to your choice. Then, click on POST button to share the content. Finally, you will get output similar 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 etc. We have discussed each and everything in a separate post. You can check out these tutorials as well. Hope this tutorial helped you.

2 Comments

  1. Rajeev Kumar October 21, 2016
  2. Rosa Palacios Yans March 16, 2017

Leave a Reply