終於讓我找到如何做到這一點。
需要聲明此二:
Facebook facebookClient;
SharedPreferences mPrefs;
在OnCreate函數初始化我用facebookClient facebook的的AppID。
是午餐Facebook的份額必須是活動類
有,我加入到活動三個功能:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
facebookClient.authorizeCallback(requestCode, resultCode, data);
}
public void loginToFacebook() {
mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if (access_token != null) {
facebookClient.setAccessToken(access_token);
}
if (expires != 0) {
facebookClient.setAccessExpires(expires);
}
if (!facebookClient.isSessionValid()) {
facebookClient.authorize(this, new String[] { "publish_stream" }, new DialogListener() {
@Override
public void onCancel() {
// Function to handle cancel event
}
@Override
public void onComplete(Bundle values) {
// Function to handle complete event
// Edit Preferences and update facebook acess_token
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token", facebookClient.getAccessToken());
editor.putLong("access_expires", facebookClient.getAccessExpires());
editor.commit();
postToWall();
}
@Override
public void onError(DialogError error) {
// Function to handle error
}
@Override
public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors
}
});
}
}
private void postToWall() {
Bundle parameters = new Bundle();
parameters.putString("name", "Battery Monitor");
parameters.putString("link", "https://play.google.com/store/apps/details?id=com.ck.batterymonitor");
parameters.putString("picture", "link to the picture");
parameters.putString("display", "page");
// parameters.putString("app_id", "228476323938322");
facebookClient.dialog(MainActivity.this, "feed", parameters, new DialogListener() {
@Override
public void onFacebookError(FacebookError e) {
// TODO Auto-generated method stub
}
@Override
public void onError(DialogError e) {
// TODO Auto-generated method stub
}
@Override
public void onComplete(Bundle values) {
// TODO Auto-generated method stub
}
@Override
public void onCancel() {
// TODO Auto-generated method stub
}
});
}
,並在最後:
ImageButton facebookButton = (ImageButton) findViewById(R.id.button_FacebookShare);
facebookButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
loginToFacebook();
if (facebookClient.isSessionValid()) {
postToWall();
}
}
});
它做一個自動登錄Facebook,然後置換Facebook的share \ post對話框。 該代碼是從這tutorial
你註冊你的應用程序在Facebook上,並得到應用程序ID,如果是的話,你可以使用它。如果沒有,請參閱[this](http://developers.facebook.com/docs/mobile/android/build/) – Siddhesh
而不是發送三個字符串,您可以將所有內容以格式發送到一個字符串中 – Siddhesh
可能的[Post message to Facebook的牆從android fb sdk總是錯誤](http://facebook.stackoverflow.com/questions/3726429/post-message-to-facebook-wall-from-android-fb-sdk-always-error) – Igy