繁体   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