The last time i wrote a tutorial on Integrating Android Facebook SDK v3.6 with your App was 4-5 months back. Now that the latest Facebook SDK version is v3.17.2 lets do it again.
This Tutorial will demonstrate how to login to a Android App using Facebook login.
There are many changes to the SDK, the major additions are
1. Your app requires a API level 9 or below.
2. Graph API 2.1 is in.
Lets see what all we have missed in detail,
SDK v3.7 : 21st Feb, 2014
This version had some bug fixes related to ConcurrentModificationException during Session.StatusCallbacks run during session state changes. It also had some new additions like ProgessCallback to monitor upload progress and WebDialog builders.
SDK v3.8 : 24th Mar, 2014
This version had a new addition PhotoShareDialogBuilder that allows sharing photos via Share Dialog. It also had a fix that disabled data saving in the WebView-based Login dialog.
SDK v3.14 12th May, 2014
This was a major leap from 3.8 to 3.14, don't know where the in between releases go,maybe alpha releases. This version had some major additions and modifications.
Modifications :
1. From this SDK ver. all class by default calls to the Graph API 2.0
2. LoginButton uses the New Login.
3. Migration handling code has been removed
4. Code Samples are being Updated
Additions :
1. AudienceNetwork SDK
2. MessageDialogBuilder
3. PhotoMessageDialogBuilder
4. OpenGrapDialogBuilder
5. Bolt SDK
6. FacebookAppLinkResolver
7. Versioning to SDK request calls
8. Ability to query the session for Permissions granted and declined
SDK v3.14.1 13th May, 2014
This minor version had the following Bug Fixes
1. AudienceNetwork bug being fixed
2. NUX Login bug fixed
3. Pull requests from lopespm and gertcuykens
SDK v3.15 : 12th Jun : 2014
This Major release had internal and stability improvements and logImpression() and handleClick() functions were removed.
SDK v3.16 : 18th Jul : 2014
New FriendPickerFragment that allows for taggable friends and invitable friends
1. PublishInstall being removed and activateApp to be used instead.
2. GraphAPI, ProfilePicture and SessionLogin samples are being removed.
3. Pull Request 361 fixed.
SDK v3.17 : 7th Aug : 2014
This Major release has the following,
Additions :
1. New default_audience dialog oauth param.
2. Settings.setIsLoggingEnabled method to enable logging.
3. Application session events to tracks application session through onResume and onPause.
4. FacebookRequestError had new methods being added, getErrorUserMessage, getErrorUserTitle and getErrorIsTransient.
Modifications :
1. Graph API updaded to v2.1
2. Minimum Android SDK verison supported now is 9
Bug Fixes :
1. Deadlock in AppEventsLogger at application starts fixed.
2. NullPointerException by AppEventsLogger.logEvent if Facebook app is not installed fixed.
3. Compilation warnings fixed.
SDK v3.17.1 : 7th Aug : 2014
Fix for logging app activate events
SDK v3.17.2 : 21st Aug : 2014
App link Analytics added.
Step 1 : Download Facebook SDK for Android
I hope you already download it, if not here is the link https://developers.facebook.com/docs/android (facebook-android-sdk-3.17.2.zip size 4.8mb) you can also the repo on Github
Step 2 : Prerequisites
1. Facebook SDK 3.17.2 for Android
2. Eclipse Juno v4.2 or later with a default install and the Android SDK
(Better to download Android ADT tool form Android Developer website).
3. Java v1.6 or above
4. Android API level 9 component installed in order to test your app on Emulator.
Step 3 : Installing Facebook.apk on Android Emulator
As earlier verions we do not get the facebook apk file included in the zip file, so if you want to test it on an Emulator then download Facebook-11.zip (https://developers.facebook.com/resources/Facebook-11.zip)
As we do not have Google Play installed on a Emulator we need to install the apk using the adb install command.
Steps :
a. Open Android Virtual Device (AVD) Manager (In Eclipse Menu under Window > Android Virtual Device Manager)
b. Create a new AVD with API level 8, if you already have a AVD, no need to create new
c. Launch the AVD, wait till the Emulator Loads Completely, i.e. the OS loads and Lock Screen appears (or else you may get some unwanted error while installing facebook.apk).
d. Locate Facebook-11.apk and note down the absolute path of the Apk
e. Now locate adb tools : eg. E:\Eclipse\adt-bundle-windows-x86_64-20130522\ adt-bundle-windows-x86_64-20130522\ sdk\ platform-tools
f. Now open Command Prompt (Terminal) and go to the location where adb tool is present and execute the following command
adb install I:\Facebook-11.apk
Note : It may take 15-20 minutes for facebook apk to be installed on the Emulator (patience needed).
Once this is done you will get a Success message on the Command prompt and you will see Facebook app icon on your AVD.
Step 4 : Setting up Workspace with Facebook SDK libraries
Important for Windows users ! : Your Facebook SDK files and Workspace should be on the same drive or else you may face issues while linking it. So before starting just make sure that they are under the same drive (for me its E:/)
Open Workspace,
Right Click > Import Existing Projects into Workspace,
Locate FacebookSDK Projects and Select Facebook SDK Projects only (deselect all others)
Create a new Android Project for testing, fill in the Application name,Project Name and Package Name, See that the Java Version is 1.6.
I have added an fb icon under bin > res > drawable-hdpi and have set it as a ImageView in MainActivity.
Step 5 : Generating KeyHash for your device
Many of us get stuck at generating KeyHashes!. The simplest and quickest way to generate keyhash is add the following code onCreate function.
try {
PackageInfo info = getPackageManager().getPackageInfo(
"com.code2care.facebookSDKTuts",
PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
System.out.println("KeyHash : "+ Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}
Note : Remember to change the package name accordingly (for me its com.code2care.facebookSDKTuts) Once you run the app you will find the keyhash in LogCat,
Step 6: Register your App with Facebook Developers Android App Page
You need to add this keyhash to your facebook developer accounts App details page.
a. Go to https://developers.facebook.com/apps, Click on Create New App
b. You will get a Pop-up, enter the App name (you can use your app name instead) and select a catagory.
c. Now the Dashboard will be loaded, and you will get the App ID and Secret Key for your App.
d. Now go to Settings and Click Add Platform, Select Android
e. Fill in the Details like Package Name (eg. com.code2care.demos.317Test) , Class Name (om.code2care.demos.317Test.MainActivity) and the KeyHash we just created at step 5.
f. Go to Status & Review and Make the App Live, (Note : Make sure you add your email id in Contact Email in Settings)
Step 7: Configuration of String XML of you App
Add applicationId to string.xml.
<string name="applicationId">318980594930439</string>
Add the below lines in your Manifest.xml file, in application tag just after your main acitivity tag,
<activity android:name="com.facebook.LoginActivity"
android:theme="@android:style/Theme.Translucent.NoTitleBar"
android:label="@string/app_name" />
<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/applicationId"/>
also add this line, change your app_id appropirately
<provider android:authorities="com.facebook.app.NativeAppCallContentProvider694100583997756" android:name="com.facebook.NativeAppCallContentProvider" android:exported="true"/>
Add Internet and ACCESS NETWORK STATE Permission under : AndroidManifest.xml > Application Tab > Application Nodes > User Permissions
android.permission.INTERNET android.permission.ACCESS_NETWORK_STATE
Now if you run the program will get Jar mismatch! Fix your dependencies Error, to fix this issue you need to delete android-support-v4.jar under Your Project libs folder and place here the same file from FacebookSDK project's libs file.
Java Files: MainActivity.java
/**
*
* Code2care 2014
*
* Code Under MIT Licence
*
* Before running this App
*
* 1. Set your applicationId in string.xml
* 2. Un-commend KeyHashCode to generate your keyhash and
* add to your Facebook App Dashboard Settings.
*
* 3. Make sure you download Facebook SDK for Android v3.17.2 or later and
* link the library to this Project
*
* 4. If any questions drop in a mail to questions.c2c@gmail.com
*
*
* know more : http://code2care.org
*
* Like us : http://facebook.com/code2care
*
* Tweet us : http://twitter.com/code2care
*
*/
package com.code2care.demos.code2careDemo;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends FragmentActivity {
private MainFragment mainFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
////Un-comment to get your keyHash from LogCat, Make sure to change package name appropriately
// try {
// PackageInfo info = getPackageManager().getPackageInfo(
// "com.code2care.demos.code2careDemo",
// PackageManager.GET_SIGNATURES);
// for (Signature signature : info.signatures) {
// MessageDigest md = MessageDigest.getInstance("SHA");
// md.update(signature.toByteArray());
// System.out.println("KeyHash : "+ Base64.encodeToString(md.digest(),
// Base64.DEFAULT));
// }
// } catch (NameNotFoundException e) {
// } catch (NoSuchAlgorithmException e) {
// }
if (savedInstanceState == null) {
// Add the fragment on initial activity setup
mainFragment = new MainFragment();
getSupportFragmentManager().beginTransaction()
.add(android.R.id.content, mainFragment).commit();
} else {
// Or set the fragment from restored state info
mainFragment = (MainFragment) getSupportFragmentManager()
.findFragmentById(android.R.id.content);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
MainFragment.java
package com.code2care.demos.code2careDemo;
import android.content.Intent;
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.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.widget.LoginButton;
public class MainFragment extends Fragment {
private static final String TAG = "MainFragment";
private UiLifecycleHelper uiHelper;
private Session.StatusCallback callback = new Session.StatusCallback() {
@Override
public void call(Session session, SessionState state, Exception exception) {
onSessionStateChange(session, state, exception);
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uiHelper = new UiLifecycleHelper(getActivity(), callback);
uiHelper.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_main, container, false);
LoginButton authButton = (LoginButton) view.findViewById(R.id.authButton);
authButton.setFragment(this);
return view;
}
private void onSessionStateChange(Session session, SessionState state, Exception exception) {
if (state.isOpened()) {
Log.i(TAG, "Logged in...");
} else if (state.isClosed()) {
Log.i(TAG, "Logged out...");
}
}
@Override
public void onResume() {
super.onResume();
Session session = Session.getActiveSession();
if (session != null &&
(session.isOpened() || session.isClosed()) ) {
onSessionStateChange(session, session.getState(), null);
}
uiHelper.onResume();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
}
@Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
@Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
uiHelper.onSaveInstanceState(outState);
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.code2care.demos.code2careDemo"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="9"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.facebook.LoginActivity"
android:theme="@android:style/Theme.Translucent.NoTitleBar"
android:label="@string/app_name" />
<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/applicationId"/>
</application>
</manifest>
Result :
- Check Internet Connection WIFI 4G is active on Android Programmatically
- Android Emulator cannot be opened because the developer cannot be verified. [M1 Mac]
- How to Change Android Toast Position?
- Fail to connect to camera service Android java RuntimeException
- How to create Custom RatingBar Android Programming Tutorial
- Fixing Android unknown error 961 while downloading app
- Android AlertDialog with Yes No and Cancel Button
- Share or Send SMS via Android Intent
- The Android Virtual Device myEmulator is currently running an emulator and cannot be deleted.
- Pass data between two Android Activities and access it using Intent
- SQLite with Android Easy to Understand Tutorial that covers Select, Insert, Update and Delete
- [FIX] AndroidRuntime: FATAL EXCEPTION: main - java.lang.RuntimeException NullPointerException
- Android EditText Cursor Colour appears to be white
- Android Development - How to switch between two Activities
- Android xml error Attribute is missing the Android namespace prefix [Solution]
- Android : Remove ListView Separator/divider programmatically or using xml property
- Android is starting optimizing... app 1 of 1
- java.lang.NoClassDefFoundError android.support.v4.content.LocalBroadcastManager
- AlertDialog with single button example : Android
- Android : Exception raised during rendering: action_bar API 22
- Maven : java.lang.ClassNotFoundException: Xmx512m
- Android Lint app_name is not translated in af (Afrikaans) am (Amharic) ar (Arabic) bg (Bulgarian)
- Center align text in TextView Android Programming
- How to Download and Install Android adb Tool on Linux, Mac or Windows
- Multiline EditText in Android Example
- How to install SpaCy (NLP Library) on Mac - Python
- fix fatal: --local can only be used inside a git repository error - Git
- Check Bluetooth is turned on or off on Android device programmatically [Java Code] - Android
- Center align text in TextView Android Programming - Android
- [Android] RuntimeException: Unable to start activity Need BLUETOOTH permission - Android
- Fix - Error:Invalid Gradle JDK configuration found (Android Studio) - Gradle
- SDK Manager: failed to install : Android Studio on Windows - Android-Studio
- The Date Command and its usage [Linux - Unix - macOS] - Linux