1. Trang chủ
  2. » Luận Văn - Báo Cáo

HƯỚNG DẪN XÂY DỰNG ỨNG DỤNG FACEBOOK

18 298 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 18
Dung lượng 808,5 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

ANDROID FACEBOOK CONNECT TUTORIAL Source code : AndroidFacebookConnect.zip Generating App Signature for Facebook Settings To create facebook android native app you need to provide your

Trang 1

ANDROID FACEBOOK CONNECT TUTORIAL

Source code : AndroidFacebookConnect.zip Generating App Signature for Facebook Settings

To create facebook android native app you need to provide your Android application signature in

facebook app settings You can generate your application signature (keyhash) usingkeytool that comes with java But to generate signature you need openssl installed on your pc If you don’t have

one download openssl from here and set it in your system environment path

Open your command prompt (CMD) and run the following command to generate your keyhash

While generating hashkey it should ask you password Give password as android If it don’t ask for

password your keystore path is incorrect

keytool -exportcert -alias androiddebugkey -keystore "<path-to-users

directory>\.android\debug.keystore" | openssl sha1 -binary | openssl base64

check the following command how i generated hashkey on my pc

"C:\Users\Ravi\.android\debug.keystore" | openssl sha1 -binary | openssl base64

Registering your Facebook Application

After generating your app signature successfully, register your facebook application by going

to create new facebook application and fill out all the information needed And select Native

Android App and give your hashkey there which you generated previously using keytool

Trang 2

and note down your facebook App ID

Trang 3

Creating Facebook Reference Project

Once you are done with registering your facebook application, you need to download facebook SDK and create a new reference project This reference project will be used to compile your actual project

(git clone git://github.com/facebook/facebook-android-sdk.git)

2 In your Eclipse goto File ⇒ Import ⇒ Existing Projects into Workspace and select the facebook

project you downloaded from git repository

Trang 4

Creating Your Facebook Connect Project

1 Create new Project in your Eclipse IDE File ⇒ New ⇒ Android Project and fill out all the details

2 Now we need to add reference of this project to existing facebook project Right Click on Project

⇒ Properties ⇒ android ⇒ Click on Add button ⇒ select your facebook project ⇒ Click Apply

Trang 7

Now our project setup is done We can start coding our facebook application

3 Open your AndroidManifest.xml file add network connect permission in order to connect to

internet

<uses-permission android:name="android.permission.INTERNET"/>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

package="com.facebook.androidhive"

android:versionCode="1"

android:versionName="1.0" >

Trang 8

<uses-sdk android:minSdkVersion="8" />

<application

android:icon="@drawable/ic_launcher"

android:label="@string/app_name" >

<activity

android:label="@string/app_name"

android:name=".AndroidFacebookConnectActivity" >

<intent-filter >

<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />

</intent-filter>

</activity>

</application>

<! Connect to Internet Permissions >

<uses-permission android:name="android.permission.INTERNET"/>

</manifest>

4 Open Your Main Activity Class and initialize all the variables needed

publicclassAndroidFacebookConnectActivity extendsActivity {

// Your Facebook APP ID

private static String APP_ID = "308180782571605"; // Replace your App ID here

// Instance of Facebook Class

privateFacebook facebook;

privateAsyncFacebookRunner mAsyncRunner;

String FILENAME = "AndroidSSO_data";

privateSharedPreferences mPrefs;

@Override

publicvoidonCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

facebook = newFacebook(APP_ID);

mAsyncRunner = newAsyncFacebookRunner(facebook);

5 I created a simple interface which contains button to login, post to wall, show access tokens and

logout for testing purpose

Login to Facebook Account

I used a button to login into facebook account In your activity write a click event for Login button

click Inside click event declare a function named loginToFacebook();

Trang 9

Login button click event

btnFbLogin.setOnClickListener(newView.OnClickListener() {

@Override

publicvoidonClick(View v) {

loginToFacebook();

}

});

and function body for loginToFacebook() function is:

publicvoidloginToFacebook() {

mPrefs = getPreferences(MODE_PRIVATE);

String access_token = mPrefs.getString("access_token", null);

longexpires = mPrefs.getLong("access_expires", 0);

if(access_token != null) {

facebook.setAccessToken(access_token);

}

if(expires != 0) {

facebook.setAccessExpires(expires);

}

if(!facebook.isSessionValid()) {

facebook.authorize(this,

newString[] { "email", "publish_stream"},

newDialogListener() {

@Override

publicvoidonCancel() {

// Function to handle cancel event

}

@Override

publicvoidonComplete(Bundle values) {

// Function to handle complete event

// Edit Preferences and update facebook acess_token SharedPreferences.Editor editor = mPrefs.edit();

editor.putString("access_token",

facebook.getAccessToken());

editor.putLong("access_expires",

facebook.getAccessExpires());

editor.commit();

}

@Override

publicvoidonError(DialogError error) {

// Function to handle error

}

@Override

Trang 10

publicvoidonFacebookError(FacebookError fberror) {

// Function to handle Facebook errors

}

});

}

}

Trang 12

Posting Message to Facebook Wall

write a click event for post to wall button and inside click event write a function namedpostToWall()

btnPostToWall.setOnClickListener(newView.OnClickListener() {

@Override

publicvoidonClick(View v) {

postToWall();

}

});

and function body for postToWall() function is:

publicvoidpostToWall() {

// post on user's wall

facebook.dialog(this, "feed", newDialogListener() {

@Override

publicvoidonFacebookError(FacebookError e) {

}

@Override

publicvoidonError(DialogError e) {

}

@Override

publicvoidonComplete(Bundle values) {

}

@Override

publicvoidonCancel() {

}

});

}

Trang 14

Getting Profile Information from Facebook

To get profile information we need to make an api request to facebook graph API Following is a function that will make an api request to facebook profile graph api and will get profile information from facebook

getProfileInformation()

publicvoidgetProfileInformation() {

mAsyncRunner.request("me", newRequestListener() {

@Override

publicvoidonComplete(String response, Object state) {

Log.d("Profile", response);

String json = response;

try{

JSONObject profile = newJSONObject(json);

// getting name of the user

String name = profile.getString("name");

// getting email of the user

String email = profile.getString("email");

runOnUiThread(newRunnable() {

@Override

publicvoidrun() {

Toast.makeText(getApplicationContext(), "Name: " + name + "\nEmail: "+ email, Toast.LENGTH_LONG).show();

}

});

} catch(JSONException e) {

e.printStackTrace();

}

Trang 15

}

@Override

publicvoidonIOException(IOException e, Object state) {

}

@Override

publicvoidonFileNotFoundException(FileNotFoundException e,

Object state) {

}

@Override

publicvoidonMalformedURLException(MalformedURLException e,

Object state) {

}

@Override

publicvoidonFacebookError(FacebookError e, Object state) {

}

});

}

The above function will get json data from facebook You need to parse the json in order to get individual profile data If you are not aware of json parsing look at this article Android JSON Parsing Tutorial

The sample profile json from facebook will be like this

{

"id": "1464730016",

"name": "Ravi Tamada",

"first_name": "Ravi",

"last_name": "Tamada",

"link": "https://www.facebook.com/ravi8x",

"username": "ravi8x",

"birthday": "12/22/1988",

"hometown": {

"id": "112158005464147",

"name": "Baruva"

},

"location": {

"id": "102186159822587",

"name": "Chennai, Tamil Nadu"

},

"bio": "Author: www.androidhive.info\r\nCo-author: www.9lessons.info", "work": [

{

"employer": {

"id": "179366562092719",

"name": "ByteAlly"

},

"location": {

Trang 16

"id": "102186159822587",

"name": "Chennai, Tamil Nadu"

},

"position": {

"id": "124917314217511",

"name": "Product Head"

}

]

}

],

"favorite_athletes": [

{

"id": "18620649907",

"name": "Virat Kohli"

}

],

"education": [

{

"school": {

"id": "131587206873093",

"name": "Raghu Engineering College (REC)"

},

"degree": {

"id": "140065339390579",

"name": "B.Tech"

},

"year": {

"id": "142963519060927",

"name": "2010"

},

"type": "Graduate School",

"classes": [

{

"id": "192259410803415",

"name": "2010",

"with": [

{

"id": "584960408",

"name": "Santosh Patnaik"

}

],

"from": {

"id": "584960408",

"name": "Santosh Patnaik"

}

}

]

}

],

"gender": "male",

"relationship_status": "Single",

"website":

"www.androidhive.info\nwww.9lessons.info\nwww.twitter.com/ravitamada\nwww.abo ut.me/rv",

"timezone": 5.5,

"locale": "en_US",

"languages": [

Trang 17

{

"id": "106059522759137",

"name": "English"

},

{

"id": "107617475934611",

"name": "Telugu"

},

{

"id": "112969428713061",

"name": "Hindi"

},

{

"id": "343306413260",

"name": "Tamil"

}

],

"verified": true,

"updated_time": "2012-03-02T17:04:18+0000"

}

Extending facebook Permissions

If you want user’s other information like checkins, friends list etc., you need to extend facebook permissions while logging in user Check list of facebook permissions

facebook.authorize(this, newString[] { "email", "publish_checkins",

"publish_stream"},

newDialogListener() {

@Override

publicvoidonComplete(Bundle values) {}

@Override

publicvoidonFacebookError(FacebookError error) {}

@Override

publicvoidonError(DialogError e) {}

@Override

publicvoidonCancel() {}

}

);

Getting Access Token

Sometimes you might needed users access token for future purpose usage Following code will give you currently logged in user access token

Trang 18

String access_token = facebook.getAccessToken();

Logout from your app

When user want to stop using facebook for your app, you can provide logout method to clear app state and invalidate access token So further you can’t make request to facebook from your app logoutFromFacebook();

publicvoidlogoutFromFacebook() {

mAsyncRunner.logout(this, newRequestListener() {

@Override

publicvoidonComplete(String response, Object state) {

Log.d("Logout from Facebook", response);

if(Boolean.parseBoolean(response) == true) {

// User successfully Logged out

}

}

@Override

publicvoidonIOException(IOException e, Object state) {

}

@Override

publicvoidonFileNotFoundException(FileNotFoundException e,

Object state) {

}

@Override

publicvoidonMalformedURLException(MalformedURLException e,

Object state) {

}

@Override

publicvoidonFacebookError(FacebookError e, Object state) {

}

});

}

Ngày đăng: 05/04/2015, 17:37

TỪ KHÓA LIÊN QUAN

TÀI LIỆU CÙNG NGƯỜI DÙNG

TÀI LIỆU LIÊN QUAN

w