1/02/2011

[Android] Facebook API for Android


內文舊了,請先直接到官方文件看
https://developers.facebook.com/docs/ 



結合Facebook到Android程式中的JAVA函式庫
https://github.com/facebook/facebook-android-sdk

安裝環境

  1. 從GitHub取得函式庫:
git clone git://github.com/facebook/facebook-android-sdk.git
  1. 照 Android SDK Getting Started Guide 設定模擬器和編輯器
  2. Facebook Android SDK 運作在任何 Android 開發環境,如Eclipse:
  3. 建立new project 以 Facebook SDK 在 Eclipse workspace.
  4. File -> New -> Project -> Android Project -> Next.
  5. 選 "Create project from existing source".
  6. 選 facebook 目錄. You should see the project properties populated (你可以把Project名稱設成 "FacebookSDK").
  7. Finish 繼續
這時API就設定好準備讓其它程式去引用他

範例程式

這個函式庫內含兩個範例程式指導你開發
  • simple: 簡單的範例來展示授權、使用API、取得對話框
ANDROID_FB_API_01.jpg

  • stream: 可以看見你在Facebook上的消息的範例
ANDROID_FB_API_02.jpg

安裝範例程式到Eclipse (3.5):
  • Select File -> New -> Project, choose Android Project, and then click Next.

  • Select "Create project from existing source".

  • Choose either examples/simple or examples/stream. You should see the project properties populated.

  • Click Finish to continue.

  • "Build Project".

  • "Run Configurations..."

整合到現有程式


最簡單的方式是修改範例程式來結合facebook,但如果你需要整合到已有或想建立一個乾淨的專案的話:

  • Add a dependency on the Facebook Android SDK library on your application:

    1. Select File -> Properties. Open the Android section within the Properties dialog.

    2. In the bottom Library section, click Add... and select the Facebook SDK project.

    3. 有問題? 查手冊吧 Android documentation

  • 允許你的程式使用網路 (android.permission.INTERNET) 在 Android manifest 加上:


  • 註冊你的程式在 Facebook:

    1. 建立一個新的 Facebook 應用程式: http://www.facebook.com/developers/createapp.php . 如果你建立過同應用於PHP之類的
      ,你可以用同一組 application ID.

    2. 設定facebook上的應用程式資訊.

設定登入

選用,你可以讓你的登入系統結合Facebook做單一登入用
  • 註冊你的Android facebook Key Hash
  1. 產生 key hash:[code]keytool -exportcert -alias [alias] -keystore [keystore]
    | openssl sha1 -binary
    | openssl base64[/code]

  2. 到 Facebook developer settings  Mobile and Devices

  3. 在 Android 部份輸入 Key Hash
ANDROID_FB_API_03.jpg

  • 插入並呼叫 authorizeCallback() 方法在Activity的 onActivityResult() 函式. (如果沒有 onActivityResult 就建立它)
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
facebook.authorizeCallback(requestCode, resultCode, data);
// ... anything else your app does onActivityResult ...
}

用法

建立一個 Facebook 物件:

facebook = new Facebook(applicationId);
 此 Facebook 物件主要能做三件事:
  • 認證 and 授權: prompt users to log in to facebook and grant permissions to your application.

  • 建立 API 呼叫: fetch user profile data (such as name and profile pic), as well as info about a user's friends.

  • 顯示對話框: interact with user via a WebView. You primarily use this to publish to a user's feed without requiring upfront permissions.

認證 and 授權

Making the authorize request

To login the current user, call the authorize() method. By default, your application can read the user's basic information, which includes their name, profile picture, list of friends, and other information that they have made public.

[java]facebook.authorize(context, new AuthorizeListener());[/java]

Private user information is protected by a set of granular permissions. If you want to access private information, use the authorize() method to request permission:

[java]facebook.authorize(context,
String[] {"offline_access","user_photos"},
new AuthorizeListener())[/java]

You should use one of the buttons provided in the images/buttons/ directory to direct the user to login.

Login process

If the user has installed and is logged into the latest Facebook application on their device, then they will be directed to the Facebook app to grant permissions. If the user is not logged in, then they will need to do that first. If the Facebook application is not installed at all, then the Facebook Android SDK will gracefully fall back to a WebView-based flow that requires username/password.
Handle the authorize response
Your application handles the response with the onComplete method of a DialogListener object.

[java]class AuthorizeListener implements DialogListener {
public void onComplete(Bundle values) {
//  Handle a successful login
}
}[/java]

Check out the sample listeners for more details on the DialogListener interface.
Logging out
如果使用者想停止 Facebook 整合到你的 application ,你可以呼叫 logout method 清除程式狀態。

[java] facebook.logout(context);[/java]

建立 API 呼叫

通用API?
Facebook Graph API 目前很單純,取得使用者資訊、留言和朋友們

你可以連結 Graph API 呼叫"request" method。 例如:

[java]facebook.request("me");               // 取得登入者資訊
facebook.request("platform/posts");   // get the posts made by the "platform" page
facebook.request("me/friends");       // 取得登入者的朋友們
[/java]

因為要求是同步的,不會馬上呈現出來,所以不要呼叫在你的主程式內(如C的main)

請用一個執行緒(thread)去呼叫API,例如:


[java]
new Thread() {
@Override public void run() {
String resp = request("me");
handleResponse(resp);
}
}.start();
[/java]

查看 AsyncFacebookRunner class 和範例去實行異步查詢(asynchronous requests)



Response format

此服務的 response 是 JSON string. SDK 提供了 Util.parseJson() method 轉換 JSONObject,

whose fields and values can be inspected and accessed.

The sample implementation checks for a variety of error conditions and raises JSON or Facebook exceptions

if the content is invalid or includes an error generated by the server.

Advanced applications may wish to provide their own parsing and error handling.


Old REST API

The Old REST API is also supported. To access the older methods, pass in the named parameters and method name as a dictionary Bundle.

[java]
Bundle parameters = new Bundle();
parameters.putString("method", "auth.expireSession");
String response = request(parameters);
[/java]

See the comments on the request method for more details.

顯示對話框

SDK 提供一個 method 彈出 Facebook dialog 與使用者互動。 他可以輕易讓你的使用者發送意見,第一次使用時需要授權。

使用對話框:

[java]
facebook.dialog(context,
"feed",
new SampleDialogListener());
[/java]


錯誤資訊

Here's a few common errors and their solutions.
  • Build error: "missing gen files".
    重構你的project 試試 Project 的  Clean...
  • Error: "invalid_key"
    This error means that the Facebook server doesn't recognize your Android key hash. Make sure that you correctly generated and copy/pasted your key hash into the Facebook developer settings console (http://www.facebook.com/developers/apps.php), and make sure that your application has been signed with the same key you registered with Facebook.
  • Dialog won't load or shows a blank screen.
  • I can't upload photos with photos.upload.
    請確定Bundle value 於 photo 參數是 byte array.




17 則留言:

  1. 站長請教你一下
    官方的 example
    在模擬器上是正常的
    但發怖到 device 上
    都會出現:android_key_not_configured
    謝謝你

    回覆刪除
  2. 是在哪邊出現android_key_not_configured呢?
    我是在Example.java內的
    public static final String APP_ID = XXXXXXXXX
    其中的XXXXXXXXX設成自已FB APP的ID

    http://www.facebook.com/developers/apps.php
    應用程式 ID:
    XXXXXXXXX

    不好意思到現在才回復

    回覆刪除
  3. 請問大大~~要如何才可以上傳照片到指定的相本呢??
    我看example.java 他有可以上傳照片的範例
    但是 只能上傳到 "預設的相本"

    看了兩天 還是不知道怎麼做.....

    希望大大能指導一下

    回覆刪除
  4. 我試了一下那則範例會以你的應用程式名義發佈照片。我目前沒去找可以以個人名義發佈的方法

    回覆刪除
  5. 你好
    你這篇文章有3張圖死檔
    不知道能否修復?
    感謝

    回覆刪除
  6. 已修復完成~ 感謝回報

    回覆刪除
  7. 嘿 站長你好!

    你的講解很清楚! 可惜我一開始撰寫的時候沒先找到你的網站!

    我想請問你,你知道該如何取得使用者的大頭貼媽??

    回覆刪除
  8. 太過獎了,我只是把英文的東西寫成自已看的懂的話而已
    我現在手邊沒在做android的facebook api程式
    不過我之前在php版的做法是先抓到id後
    利用 https://graph.facebook.com/使用者facebookid/picture 就可以抓到使用者的大頭貼了
    例如 https://graph.facebook.com/19292868552/picture
    Android 版的FB API應該是利用 facebook.request("me/id"); 抓取id
    可能就麻煩您試試看

    回覆刪除
  9. c199002029/9/11 09:52

    站長您好~
    想請教您要如何判斷使用者登入FB並且授權應用程式了呢?
    因為目前在實做一個可以使用FB登入的系統,
    要讓使用者登入FB並且授權應用程式以後才跳往下個頁面。
    感謝您~

    回覆刪除
  10. c199002029/9/11 09:54

    還想請教一件事情~
    我目前在模擬器上可以執行並且可以使用FB
    但是到實機上測試時FB的功能就會失敗
    有可能是哪個步驟做錯了呢?

    回覆刪除
  11. 請問一下,我試的結果,早上是好的,下午就不能正常運作。
    它在authorize時,畫面閃一下,直接跳出。程式沒變,但早上是可以的,是否它有限制使用次數?
    先謝謝了

    回覆刪除
  12. 試試
    facebook.request("me")
    有資料的話再跳往下個功能

    回覆刪除
  13. 檢查一下DDMS有出現什麼訊息??

    回覆刪除
  14. 檢查一下DDMS有出現什麼訊息?

    回覆刪除
  15. 謝謝喔


    in
    isSessionValid:false
    authorize
    publish
    executing request POST https://graph.facebook.com/me/photos HTTP/1.1
    getStatusLine HTTP/1.1 200 OK
    {"id":"113353398770816"}

    印出來是,看起來是有成功的
    但從browser看facebook,畫面上並沒有任何反應…

    我的動作如下:
    public void uploadPicture(String token, String message, File imageFile) throws ParseException, IOException {
    HttpClient httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    HttpPost httppost = new HttpPost(PHOTO_UPLOAD_URL);

    MultipartEntity mpEntity = new MultipartEntity();

    mpEntity.addPart(Facebook.TOKEN, new StringBody(token));
    mpEntity.addPart(PARAMETER_NAME_PHOTO, new FileBody(imageFile, CONTENTBODY_PHOTO));
    mpEntity.addPart(PARAMETER_NAME_MESSAGE, new StringBody(message));
    httppost.setEntity(mpEntity);

    // DEBUG
    Log.v(CLASS_NAME, "executing request " + httppost.getRequestLine());
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity resEntity = response.getEntity();

    // DEBUG
    Log.v(CLASS_NAME, "getStatusLine " + response.getStatusLine());
    if (resEntity != null) {
    Log.v(CLASS_NAME, EntityUtils.toString(resEntity));
    } // end if

    if (resEntity != null) {
    resEntity.consumeContent();
    } // end if

    httpclient.getConnectionManager().shutdown();
    }

    回覆刪除
  16. 請問一下關於登出
    facebook.logout(context);
    這個context是要放甚麼?
    我試過放this也不行@@
    謝謝

    回覆刪除
  17. 先試試 getContext()
    不然可以參考下
    https://developers.facebook.com/docs/mobile/android/hackbook/
    最近多了 hackbook 的範例

    回覆刪除