Android Facebook Graph API 更新状态

标签 android facebook facebook-graph-api

我尝试在 Android 上使用 Facebook 图形 API 来更新状态 http://developers.facebook.com/docs/reference/api/status/ 所以,我的问题是,您是否可以给我一些使用此 API 更新状态的示例代码。

最佳答案

这是我使用 Graph API 的完整解决方案

如果您打算做的只是更新用户状态,您只需要获得“publish_stream”权限。 从 developers.facebook.com... “publish_stream”:使您的应用能够将内容、评论和点赞发布到用户的流和用户 friend 的流中。通过此权限,您可以随时将内容发布到用户的供稿中,无需离线访问。但是,请注意,Facebook 推荐用户发起的共享模式。

这很重要,因为这意味着您无需在每次尝试更新状态时都重新授权。诀窍是保存 key / token 并将其与任何更新请求一起发送。

请注意:我在 Facebook.java 类中将“Facebook.DEFAULT_AUTH_ACTIVITY_CODE”从私有(private)更改为公共(public)。

我的代码有两个按钮,一个用于检查保存的 token ,另一个用于发送空白 token ,这样我就可以测试如果 token 由于某种原因失败会发生什么。如果确实失败,并且 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();
}
}

主.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>

关于Android Facebook Graph API 更新状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4641680/

相关文章:

android - 如何在 Android 中从 Facebook 检索我的位置和电话号码?

android - 我无法在 macOS Sierra 上安装英特尔 HAXM

android - 奇怪的 AndroidViewModel LiveData 观察者行为

android - 在 flutter/Dart 中获取 youtube 视频详细信息

facebook - 使用 Facebook Graph Api 对 Facebook 页面的评论获取 "FROM"字段

iOS 10 Facebook graph.facebook.com SSL 错误 - FBSDK 安全网络请求失败

Android 如何保存位图 - 错误代码

javascript - 如何从 Facebook 浏览器重定向到 Android 市场?

xcode - 在 xcode 中找不到 AppDelegate.m

java - 如何在android中使用graph api获取好友列表?