使用 Graph API - Android

Android SDK 支援 Facebook Graph API 整合。透過 GraphRequestGraphResponse 類別,您能夠以非同步處理的方式,使用 JSON 格式做出要求與取得回應。透過 GraphRequestBatch,您還能夠單次來回 Facebook 伺服器即可做出批次要求。

進一步瞭解 Graph API:

另請參閱 GraphRequestGraphResponseGraphRequestBatch 參考資料,瞭解如何於其他使用案例中使用 Facebook Android SDK 與調用 Graph API。

必要條件

開始作業前,請設定以下事項:

GraphRequest 類別

GraphRequest 類別的 newMeRequest 方法會調用 /user/me 端點,擷取指定存取憑證的用戶資料。

Android SDK 會透過 access_token 傳送您的應用程式所具備的所有權限,並以此控制資料存取。若您的應用程式無存取憑證可用,則 Graph API 僅會傳回公開可用資訊。如需有關 User 屬性和權限的詳細資訊,請參閱 「Graph API 參考資料」中的「User」。

根據預設,newMeRequest 方法會從 User 物件擷取預設欄位。若您需要其他任何欄位,或為了提升效能而想降低回應承載,可加入 fields 參數並要求特定欄位:

GraphRequest request = GraphRequest.newMeRequest(
        accessToken,
        new GraphRequest.GraphJSONObjectCallback() {
            @Override
            public void onCompleted(
                   JSONObject object,
                   GraphResponse response) {
                // Application code
            }
        });
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,link");
request.setParameters(parameters);
request.executeAsync();

在回傳方法中,若要求成功,回應資料會還原序列化為 JSONObject。結果會省略因為缺乏權限而無法擷取的欄位。

對於已登入的用戶,SDK 可使用 ProfileProfileTracker 類別。請參閱 Android 專用 Facebook 登入

擷取用戶資料

您可存取的資料取決於用戶授與應用程式的權限,以及用戶選擇與應用程式分享的資料。以下範例為 Graph API 對於 user_locationuser_birthday 的原始回應:

{
  "id": "12345678", 
  "birthday": "1/1/1950", 
  "first_name": "Chris", 
  "gender": "male", 
  "last_name": "Colm", 
  "link": "http://www.facebook.com/12345678", 
  "location": {
    "id": "110843418940484", 
    "name": "Seattle, Washington"
  }, 
  "locale": "en_US", 
  "name": "Chris Colm", 
  "timezone": -8, 
  "updated_time": "2010-01-01T16:40:43+0000", 
  "verified": true
}

處理結果

視調用的端點而定,您會接收到 JSONObjectJSONArray

newMeRequest 等單一物件調用會傳回 JSONObject。如 newMyFriendsRequest 等多重結果調用會傳回 JSONArray

處理錯誤

您可檢查 GraphResponse 物件中的錯誤欄位,查看要求是否失敗。錯誤欄位的類型為 FacebookRequestError。您可調用的方法如下:

錯誤物件中的欄位可說明錯誤詳細資訊,包括:

  • error code
  • sub error code
  • error message 的陣列
  • user facing error message 的陣列
  • 及其他訊息。

如需有關可能錯誤代碼的詳細資訊,請參閱「使用 Graph API」中的「處理錯誤」

GraphResponse 物件中還有一個會將錯誤分類的 enum 欄位。三種可能的分類如下:

  • LOGIN_RECOVERABLE - 此錯誤需要用戶再次登入。您可調用 LoginManagerresolveError,並傳遞 GraphResponse 物件和應用程式的活動或片段。這樣會觸發「Faceboook 登入」UI,而且您需要調用該片段或活動來執行 CallbackManager,才能成功登入。
  • TRANSIENT - 表示發生暫時性問題,您的應用程式可重試要求。
  • OTHER - 表示發生一般性問題,您可檢查 error codesub error code 來取得詳細資訊。

解決疑難

若擷取用戶資料時發生任何問題,您可將下列程式碼加入在應用程式要求用戶資料前,以啟用 HTTP 要求記錄:

FacebookSdk.addLoggingBehavior(LoggingBehavior.REQUESTS);

這樣會在主控台紀錄中記錄有關 HTTP 要求和回應的詳細資訊。

批次要求

若您的應用程式需要處理下列類型的情境,您應該批次要求資料:

  • 在單一要求中存取相當大量的資料,或
  • 一次變更多個物件。

若想減少來回伺服器的次數,您可使用批次要求。舉例而言,若要擷取某位用戶及其朋友:

GraphRequestBatch batch = new GraphRequestBatch(
        GraphRequest.newMeRequest(
                access_token,
                new GraphRequest.GraphJSONObjectCallback() {
                    @Override
                    public void onCompleted(
                            JSONObject jsonObject,
                            GraphResponse response) {
                        // Application code for user
                    }
                }),
        GraphRequest.newMyFriendsRequest(
                access_token,
                new GraphRequest.GraphJSONArrayCallback() {
                    @Override
                    public void onCompleted(
                            JSONArray jsonArray, 
                            GraphResponse response) {
                        // Application code for users friends 
                    }
                })
);
batch.addCallback(new GraphRequestBatch.Callback() {
    @Override
    public void onBatchCompleted(GraphRequestBatch graphRequests) {
        // Application code for when the batch finishes
    }
});
batch.executeAsync();

以上範例顯示批次要求為非同步處理調用。若以上程式碼在背景執行緒上執行,而且您想封鎖直到調用結束,則可調用 batch.executeAndWait()

相關資源