Share Link 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 media files using android facebook SDK. However, we have also written post on How to implement Facebook Like Button, Share Media Files using Latest Android Facebook SDK, Share Image Using Latest Android Facebook SDK and Share Video Files using Custom Button. You can check out these tutorials, if you need.

Output

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

Tutorialwing android facebook share link output post

Tutorialwing android facebook share link output post

Source Code

Android facebook integration – share link tutorial source code

1. Getting Started

In this tutorial, you will learn how to share link using latest 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 AndroidFacebookShareLinkTutorial 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="tutorialwing.com.androidfacebooksharelinktutorial"
          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"/>

        <provider
            android:name="com.facebook.FacebookContentProvider"
            android:authorities="com.facebook.app.FacebookContentProviderYOUR_FACEBOOK_APP_ID"
            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 tutorialwing.com.androidfacebooksharelinktutorial;

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(
					"tutorialwing.com.androidfacebooksharelinktutorial",
					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 MainAcitivity.java and activity_main.xml file. At this point of time, It would look like below.
MainActivity.java

package tutorialwing.com.androidfacebooksharelinktutorial;

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 Link 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 link using latest Android Facebook SDK. We will do this in following steps.
a. Create a fragment ShareLinkFragment.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 ShareLinkFragment.java) and an xml file (named fragment_share.xml).

We use ShareButton widget, provided by Facebook SDK, to implement share link 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 link 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 link Java file

In ShareLinkFragment.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, ShareLinkContent class has been used.

ShareLinkContent content = new ShareLinkContent.Builder()
		.setContentTitle("Tutorialwing - Free programming tutorials")
		.setImageUrl(Uri.parse("https://scontent-sin6-1.xx.fbcdn.net/t31.0-8/13403381_247495578953089_8113745370016563192_o.png"))
		.setContentDescription("Tutorialwing is an online platform for free programming tutorials. These tutorials are designed for beginners as well as experienced programmers.")
		.setContentUrl(Uri.parse("https://www.facebook.com/tutorialwing/"))
		.setShareHashtag(new ShareHashtag.Builder()
				.setHashtag("#Tutorialwing")
				.build())
		.setQuote("Learn and share your knowledge")
		.build();

Some methods being used to set Content are:
setContentTitle method : Sets the title of the content
setImageUrl method : Sets url of the image you want to show
setContentDescription method : Sets the description you want to show.
setContentUrl method : Sets the url of the page you want to share
setShareHashtag method : Sets the Hashtag you to show in the post you shared.
setQuote method : Sets the quotes with the post you want to share.

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 ShareLinkFragment.java class code
package tutorialwing.com.androidfacebooksharelinktutorial;

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 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.ShareHashtag;
import com.facebook.share.model.ShareLinkContent;
import com.facebook.share.widget.ShareButton;
import com.facebook.share.widget.ShareDialog;

public class ShareLinkFragment extends Fragment {

	private static String TAG = ShareLinkFragment.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(this);

		// 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);
		setLinkShare(view);
	}

	private void setLinkShare(View view) {
		ShareLinkContent content = new ShareLinkContent.Builder()
				.setContentTitle("Tutorialwing - Free programming tutorials")
				.setImageUrl(Uri.parse("https://scontent-sin6-1.xx.fbcdn.net/t31.0-8/13403381_247495578953089_8113745370016563192_o.png"))
				.setContentDescription("Tutorialwing is an online platform for free programming tutorials. These tutorials are designed for beginners as well as experienced programmers.")
				.setContentUrl(Uri.parse("https://www.facebook.com/tutorialwing/"))
				.setShareHashtag(new ShareHashtag.Builder()
						.setHashtag("#Tutorialwing")
						.build())
				.setQuote("Learn and share your knowledge")
				.build();

		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.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.
		}
	};
}

1.3.2 Use ShareLinkFragment in MainActivity.java and show final output.

We have successfully created content to share and set this in ShareButton inside ShareLinkFragment class. Now, we will add this ShareLinkFragment 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 tutorialwing.com.androidfacebooksharelinktutorial;

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

		addShareLinkFragment();
	}

	private void addShareLinkFragment() {
		FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
		fragmentTransaction.add(R.id.facebook_share_button, new ShareLinkFragment());
		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 link 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.

Leave a Reply