Social media integration is one of the most important modes of OAuth for any App. Recently we have been getting a lot of queries on ‘how to integrate Facebook with Apps’. To resolve these queries we have created a sample Android App and below mentioned are the steps to integrate Facebook with this App.
La integración de las redes sociales es uno de los modos más importantes de OAuth para cualquier aplicación. Recientemente hemos tenido muchas inquietudes acerca de “Como integrar Facebook con aplicaciones”. Para resolver estas inquietudes, hemos creado una muestra de una aplicación Android y abajo mencionamos los pasos para integrar Facebook con esta aplicación.
Click To Tweet
Also Read: How to Integrate Twitter in your Android App
About the application:
1. This application shows how we can integrate an Android App with Facebook API.
2. The sample shows how we can get our Facebook friends to increase the online presence.
Running Sample:
1. First of all download Facebook SDK from here .
2. Create a Facebook application here to get a Facebook APP ID for your application.
3. You need to create a key hash of your signature from android debug.keystore (for the development stage).
4. For this First download OpenSSL from here and extract to a folder (in my case, c:\openssl) and follow these steps.
A. To create key hash, you need to navigate to your JAVA jdk folder, where the keytool.exe is. (in my case, in windows
is: C:\Program Files (x86)\Java\jdk1.6.0_16\bin)
B. This also requires path of your debug.keystore (in my case, in windows is: C:\Users\MyUsername\.android).
C. Now open your command prompt and navigate to the jdk bin folder and run following command.
keytool -exportcert -alias androiddebugkey -keystore "" > C:\openssl\bin\debug.txt
D. Navigate to C:\openssl\bin\ using command prompt and run following commands.
openssl sha1 -binary debug.txt >debug_sha.txt
openssl base64 -in debug_sha.txt >debug_base64.txt
E. debug_base64.txt contains the key hash.
F. Copy this key hash to your Facebook Application that you made in step 2.
(Edit Settings -> Native Android App -> Key Hashes:) and also enable Facebook login and save it.
G. Now your application is authenticated with Face-Book.
5. Download the project from here and import it in the eclipse.
6. Import Facebook SDK project in your eclipse (which you have downloaded in step 1) and make it a library project.
7. Add this library project into your sample android application.
8. Open Constants.java file and change FB_APP_ID variable value with your FB APP ID.
9. Build your android application and install on your android device.
Design Details:
Authorization With Facebook: To use Facebook API in your android application you have to authorize application. As a sample I have authorized my application in FacebookService.java file. In this method you have to pass following three parameters :
1. Your host Activity on which you have to get callback from Facebook API.
2. All Facebook API permissions required for your application in form of String array.(in this sample I had requested for friends_online_presence).
3. This is called only the first time after installation with Facebook.
4. Once your application is authorized , you can use Facebook API directly.
[code java]public void fetchFacebookProfile(final FriendList hostActivity)
{
if(mUIThreadHandler == null){
mUIThreadHandler = new Handler();
}
facebook.authorize(hostActivity, new
String[] {
"friends_online_presence"}
, new DialogListener() {
@Override
public void onComplete(Bundle values)
{ if(mPrefs == null){
mPrefs = appContext.getSharedPreferences("MyGamePreferences", android.content.Context.MODE_PRIVATE);
}
SharedPreferences.Editor editor = mPrefs.edit();
UserContext.accessToken= facebook.getAccessToken();
editor.putString("access_token", facebook.getAccessToken());
editor.putLong("access_expires", facebook.getAccessExpires());
editor.commit();
FacebookService.this.getFacebookProfile(hostActivity);
}
@Override
public void onFacebookError(FacebookError error) {
hostActivity.onFbError();
}
@Override
public void onError(DialogError e) {
hostActivity.onFbError();
}
@Override
public void onCancel() {
hostActivity.onFbError();
}
});
}[/code]
Authorization callback : After the authorization step you have to authorize callback as an acknowledgement in onActivityResult method of your host Activity. This is done in FriendList.java file.
[code java]@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// super.onActivityResult(requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
if (!UserContext.authorized) {
FacebookService.instance().authorizeCallback(requestCode,
resultCode, data);
UserContext.authorized = true;
}
}[/code]
Get Facebook Profile: You can get your Facebook profile after getting authorization (in onComplete() describe above) which is done in FacebookService.java file.
[code java]public void getFacebookProfile(FriendList callingActivity)
{
Bundle params = new Bundle();
params.putString("fields", "name, picture");
mAsyncRunner.request("me", params, new FacebookRequestListener(callingActivity));
}[/code]
Get Facebook Friends: You can get your Facebook friends by writing your own query or can refer the following code , written in FacebookService.java file.
[code java]public void getFacebookFriends(FacebookFriendListRequester caller){
if(mUIThreadHandler == null){
mUIThreadHandler = new Handler();
}
Bundle params = new Bundle();
params.putString("method","fql.query");
params.putString("query","SELECT name,uid,pic,online_presence FROM user WHERE uid IN
( SELECT uid2 FROM friend WHERE uid1 = me()) ORDER BY name" );
mAsyncRunner.request(params, new FacebookFriendListRequest(caller));
}[/code]
It would be great to hear the views from the readers of this blog. In case you have any more questions or suggestions, please feel free to reach out to us at support@shephertz.com.
Click To Tweet
Acerca de la aplicación:
1. Esta aplicación muestra cómo podemos integrar una aplicación Android con Facebook API
2. La muestra ilustra cómo podemos hacer que nuestros amigos en Facebook incrementen su presencia online.
Como opera la muestra:
A. To create key hash, you need to navigate to your JAVA jdk folder, where the keytool.exe is. (in my case, in windows
is: C:\Program Files (x86)\Java\jdk1.6.0_16\bin)
B. This also requires path of your debug.keystore (in my case, in windows is: C:\Users\MyUsername\.android).
C. Now open your command prompt and navigate to the jdk bin folder and run following command.
keytool -exportcert -alias androiddebugkey -keystore "" > C:\openssl\bin\debug.txt
D. Navigate to C:\openssl\bin\ using command prompt and run following commands.
openssl sha1 -binary debug.txt >debug_sha.txt
openssl base64 -in debug_sha.txt >debug_base64.txt
E. debug_base64.txt contains the key hash.
F. Copy this key hash to your Facebook Application that you made in step 2.
(Edit Settings -> Native Android App -> Key Hashes:) and also enable Facebook login and save it.
G. Now your application is authenticated with Face-Book.
5. Descargue el proyecto desde aquí e impórtelo en el eclipse.
6. Importe el proyecto de Facebook SDK en su eclipse (el cual usted descargó en el paso 1) y conviértalo a una biblioteca de proyectos.
7. Agregue esta biblioteca de proyectos a su aplicación Android de muestra
8. Abra el archivo Constants.java y cambie el valor variable de FB_APP_ID con su Facebook APP ID.
9. Cree su aplicación Android e instálela en su dispositivo Android
Detalles de diseño:
Autorización con Facebook: Para usar Facebook API en su aplicación Android tiene que autorizar la aplicación. Por ejemplo autoricé mi aplicación en FacebookService.java. En este método debe pasar por los siguientes tres parámetros:
1. Su servidor de actividades en el cual debe recibir una retrollamada desde Facebook API.
2. Todos los permisos de Facebook API requeridos para su aplicación en forma de matriz de cadenas. (En esta muestra he solicitado por friends_online_presence).
3. Esto es utilizado solo la primera vez luego de la instalación con Facebook.
4. Una vez su aplicación es autorizada, puede usar directamente Facebook API.
public void fetchFacebookProfile(final FriendList hostActivity)
{
if(mUIThreadHandler == null){
mUIThreadHandler = new Handler();
}
facebook.authorize(hostActivity, new
String[] {
"friends_online_presence"}
, new DialogListener() {
@Override
public void onComplete(Bundle values)
{ if(mPrefs == null){
mPrefs = appContext.getSharedPreferences("MyGamePreferences", android.content.Context.MODE_PRIVATE);
}
SharedPreferences.Editor editor = mPrefs.edit();
UserContext.accessToken= facebook.getAccessToken();
editor.putString("access_token", facebook.getAccessToken());
editor.putLong("access_expires", facebook.getAccessExpires());
editor.commit();
FacebookService.this.getFacebookProfile(hostActivity);
}
@Override
public void onFacebookError(FacebookError error) {
hostActivity.onFbError();
}
@Override
public void onError(DialogError e) {
hostActivity.onFbError();
}
@Override
public void onCancel() {
hostActivity.onFbError();
}
});
}
Retrollamada de autorización: Después del paso de autorización, debe autorizar la retrollamada como reconocimiento en el método en onAtivityResult de su servidor de actividades. Esto se realiza en el archivo FriendList.java.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// super.onActivityResult(requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
if (!UserContext.authorized) {
FacebookService.instance().authorizeCallback(requestCode,
resultCode, data);
UserContext.authorized = true;
}
}
Obtener su perfil de Facebook: Puede obtener su perfil de Facebook luego de obtener la autorización (en onComplete () descrita abajo) esta se realiza en el archivo FacebookService.java.
public void getFacebookProfile(FriendList callingActivity)
{
Bundle params = new Bundle();
params.putString("fields", "name, picture");
mAsyncRunner.request("me", params, new FacebookRequestListener(callingActivity));
}
Amigos en Facebook: Puede agregar sus amigos de Facebook escribiendo su propia solicitud o puede referir el siguiente código, escrito en el archivo FacebookService.java.
public void getFacebookFriends(FacebookFriendListRequester caller){
if(mUIThreadHandler == null){
mUIThreadHandler = new Handler();
}
Bundle params = new Bundle();
params.putString("method","fql.query");
params.putString("query","SELECT name,uid,pic,online_presence FROM user WHERE uid IN
( SELECT uid2 FROM friend WHERE uid1 = me()) ORDER BY name" );
mAsyncRunner.request(params, new FacebookFriendListRequest(caller));
}
Sería genial saber acerca de los lectores de este blog. En caso de que tenga más preguntas o sugerencias, por favor contáctenos a support@shephertz.com.
Leave A Reply