簡體   English   中英

Android Facebook Graph API更新狀態

[英]Android Facebook Graph API to update status

我試圖使用Facebook圖形API和Android更新狀態http://developers.facebook.com/docs/reference/api/status/所以,我的問題是,如果你能給我一些示例代碼來更新狀態使用這個API。

這是我使用Graph API的完整解決方案

如果你打算做的只是更新用戶狀態,你只需要獲得“publish_stream”權限。 來自developers.facebook.com ...“publish_stream”:允許您的應用將內容,評論和喜歡發布到用戶的信息流和用戶朋友的信息流中。 有了此權限,您可以隨時將內容發布到用戶的Feed, 而無需offline_access 但請注意,Facebook建議使用用戶啟動的共享模型。

這很重要,因為這意味着每次嘗試更新狀態時都不需要重新授權。 訣竅是保存密鑰/令牌並使用任何更新請求發送它。

一個注意事項:我在Facebook.java類中將“Facebook.DEFAULT_AUTH_ACTIVITY_CODE”從私有更改為public。

我的代碼有兩個按鈕,一個用於檢查已保存的令牌,另一個用於發送空白令牌,因此我可以測試如果令牌由於某種原因失敗會發生什么。 如果它確實失敗,並且API返回帶有“OAuthException”的字符串,則此代碼會進行新的授權嘗試,然后再次嘗試更新狀態。

FBTest.java

package com.test.FBTest;

import java.io.IOException;
import java.net.MalformedURLException;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.Facebook.DialogListener;

public class FBTest extends Activity {

Facebook facebook = new Facebook("199064386804603");
EditText et1;
TextView tv1;
Button button1;
Button button2;

private int mAuthAttempts = 0;
private String mFacebookToken;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    button1 = (Button)findViewById(R.id.Button1);
    button2 = (Button)findViewById(R.id.Button2);
    tv1 = (TextView)findViewById(R.id.TextView1);
    et1 = (EditText)findViewById(R.id.EditText1);

    button1.setOnClickListener(new OnClickListener(){
        @Override
        public void onClick(View v) {
            b1Click();
        }

    });

    button2.setOnClickListener(new OnClickListener(){
        @Override
        public void onClick(View v) {
            b2Click();
        }

    });
}

private void saveFBToken(String token, long tokenExpires){
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    prefs.edit().putString("FacebookToken", token).commit();
}

private void fbAuthAndPost(final String message){

    facebook.authorize(this, new String[]{"publish_stream"}, new DialogListener() {

        @Override
        public void onComplete(Bundle values) {
            Log.d(this.getClass().getName(),"Facebook.authorize Complete: ");
            saveFBToken(facebook.getAccessToken(), facebook.getAccessExpires());
            updateStatus(values.getString(Facebook.TOKEN), message);
        }

        @Override
        public void onFacebookError(FacebookError error) {
            Log.d(this.getClass().getName(),"Facebook.authorize Error: "+error.toString());
        }

        @Override
        public void onError(DialogError e) {
            Log.d(this.getClass().getName(),"Facebook.authorize DialogError: "+e.toString());
        }

        @Override
        public void onCancel() {
            Log.d(this.getClass().getName(),"Facebook authorization canceled");
        }
    });
}

@Override
protected void onActivityResult(int requestCode, int resultCode,Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode){
    case Facebook.DEFAULT_AUTH_ACTIVITY_CODE:
        facebook.authorizeCallback(requestCode, resultCode, data);
    }
}

private void b1Click(){

    mAuthAttempts = 0;

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    mFacebookToken = prefs.getString("FacebookToken", "");

    if(mFacebookToken.equals("")){
        fbAuthAndPost(et1.getText().toString());
    }else{
        updateStatus(mFacebookToken,et1.getText().toString());
    }

}

private void b2Click(){
    mAuthAttempts = 0;
    updateStatus("",et1.getText().toString());
}

public void updateStatus(String accessToken, String message){  

    try {         
        Bundle bundle = new Bundle();
        bundle.putString("message", message);         
        bundle.putString(Facebook.TOKEN,accessToken);         
        String response = facebook.request("me/feed",bundle,"POST");         
        Log.d("UPDATE RESPONSE",""+response);
        showToast("Update process complete. Respose:"+response);
        if(response.indexOf("OAuthException") > -1){
            if(mAuthAttempts==0){
                mAuthAttempts++;
                fbAuthAndPost(message);
            }else{
                showToast("OAuthException:");
            }
        }
    } catch (MalformedURLException e) {         
        Log.e("MALFORMED URL",""+e.getMessage());
        showToast("MalformedURLException:"+e.getMessage());
    } catch (IOException e) {         
        Log.e("IOEX",""+e.getMessage());
        showToast("IOException:"+e.getMessage());
    }

    String s = facebook.getAccessToken()+"\n";
    s += String.valueOf(facebook.getAccessExpires())+"\n";
    s += "Now:"+String.valueOf(System.currentTimeMillis())+"\n";
    tv1.setText(s);

} 

private void showToast(String message){
    Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}
}

main.xml中

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <EditText
    android:id="@+id/EditText1"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    />
    <Button
    android:id="@+id/Button1"
    android:text="Test: With Auth"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    />
    <Button
    android:id="@+id/Button2"
    android:text="Test: Without Auth"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    />
    <TextView  
    android:id="@+id/TextView1"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    />
</LinearLayout>

好吧,這可能不是一個完美的代碼,但它現在有效。 您必須修改調用方式和時間以獲得更好的用戶體驗:

//Implementing SSO
    facebook.authorize(this, new String[]{"publish_stream"}, new DialogListener(){

        @Override
        public void onComplete(Bundle values) {
            updateStatus(values.getString(Facebook.TOKEN));
        }

        @Override
        public void onFacebookError(FacebookError e) {
            Log.d("FACEBOOK ERROR","FB ERROR. MSG: "+e.getMessage()+", CAUSE: "+e.getCause());
        }

        @Override
        public void onError(DialogError e) {
            Log.e("ERROR","AUTH ERROR. MSG: "+e.getMessage()+", CAUSE: "+e.getCause());
        }

        @Override
        public void onCancel() {
            Log.d("CANCELLED","AUTH CANCELLED");
        }
    });

這是更新的功能:

//updating Status
public void updateStatus(String accessToken){
    try {
        Bundle bundle = new Bundle();
        bundle.putString("message", "test update");
        bundle.putString(Facebook.TOKEN,accessToken);
        String response = facebook.request("me/feed",bundle,"POST");
        Log.d("UPDATE RESPONSE",""+response);
    } catch (MalformedURLException e) {
        Log.e("MALFORMED URL",""+e.getMessage());
    } catch (IOException e) {
        Log.e("IOEX",""+e.getMessage());
    }
}

我希望它有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM