【问题标题】:Facebook wall post with text and image带有文字和图像的 Facebook 墙贴
【发布时间】:2025-11-27 05:35:01
【问题描述】:

几天来,我一直在寻找有关使用图形 API 制作带有图标或图像和一些文本的 facebook 墙贴的简单教程。我尝试了无数教程,它们看起来都非常复杂,我无法让它们工作。即使是 SDK 附带的示例也不会创建会话。

我已经成功设置了 SDK 并获得了我的 APP_ID,剩下的就是用于在用户墙上分享我的应用的自定义按钮的 Java 代码。

【问题讨论】:

  • 首先,您是否已将哈希添加到您的 Facebook 开发者应用程序中?

标签: android facebook-graph-api android-fragments


【解决方案1】:

您可以通过两种不同的方式在 Facebook 上发布图片。如果您想从 URL 中发布图片,您可以按如下方式发布:

Bundle parameters = new Bundle();
parameters.putString("description","your description/message");
parameters.putString("link", "your link");
parameters.putString("name", "Name of your application/ any name you want to post");
// parameters.putString("caption", " caption if any!");
parameters.putString("picture", "Link to your image");

try 
{
    facebook.request("me");
    response = facebook.request("me/feed", parameters, "POST");
    Log.d("Tests", "got response: " + response);
} 
catch (Exception e) 
{
        e.printStackTrace();
}

或者如果您想从 SD 卡中发布图像,您可以从您要发布的图像中创建一个位图,然后将其转换为 ByteArray 并发布如下:

Bundle parameters = new Bundle();
                    Log.e("byte array", ""+mByteArray);
                    parameters.putString("message", "your message");
                    parameters.putByteArray("picture",  mByteArray);

                    try 
                        {
                            facebook.request("me");
                            response = facebook.request("me/photos", parameters, "POST");
                            Log.d("Tests", "got response: " + response);

                        } 
                    catch (Exception e) 
                        {
                            e.printStackTrace();
                        }

附:第一种方法是在用户的脸书墙上贴图,后者是上传用户脸书相册中的图片和留言,也将作为更新发布!

【讨论】:

  • 如何将多张图片分享到facebook
  • @jyomin 你有这个问题的解决方案吗?
【解决方案2】:

您可以以非常简单的方式发布带有应用程序文本的图像。

在单击按钮小部件时调用此方法说btnImagePostToWall like...

btnImagePostToWall.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            postImageToWall();
        }
    });

通过向 Facebook Graph API 发出请求来获取个人资料信息......

public void postImageToWall() {

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

                @Override
                public void onFacebookError(FacebookError e) {
                    // TODO Auto-generated method stub
                }

                @Override
                public void onError(DialogError dialogError) {
                    // TODO Auto-generated method stub
                }

                @Override
                public void onComplete(Bundle values) {
                    postImageonWall();
                }

                @Override
                public void onCancel() {
                    // TODO Auto-generated method stub
                }
            });
}

private void postImageonWall() {
    byte[] data = null;

    Bitmap bi = BitmapFactory.decodeResource(getResources(),
            R.drawable.ic_launcher);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bi.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    data = baos.toByteArray();
    Bundle params = new Bundle();
    params.putString(Facebook.TOKEN, facebook.getAccessToken());
    params.putString("method", "photos.upload");
    params.putByteArray("picture", data); // image to post
    params.putString("caption", "My text on wall with Image "); // text to post
    AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
    mAsyncRunner.request(null, params, "POST", new SampleUploadListener(),
            null);
}

只需创建一个实现 AsyncFacebookRunner.RequestListener 的类 SampleUploadListener...

class SampleUploadListener implements AsyncFacebookRunner.RequestListener {

    @Override
    public void onComplete(String response, Object state) {
    }

    @Override
    public void onIOException(IOException e, Object state) {
    }

    @Override
    public void onFileNotFoundException(FileNotFoundException e,
            Object state) {
    }

    @Override
    public void onMalformedURLException(MalformedURLException e,
            Object state) {
    }

    @Override
    public void onFacebookError(FacebookError e, Object state) {
    }

}

希望这对您有所帮助.... :-)

【讨论】:

    【解决方案3】:

    给你。您可能需要进行一些调试等,但这对我有用。

    FbLoginActivity 类:执行身份验证并发布到您的墙和/或应用程序的墙。

    用法:

    Intent i = new Intent(getApplicationContext(), FbLoginActivity.class);
    i.putExtra("SCORE", score);
    startActivity(i);
    

    FbLoginActivity:

    import java.io.ByteArrayOutputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.net.MalformedURLException;
    import org.json.JSONException;
    import org.json.JSONObject;
    
    import android.app.Activity;
    import android.app.AlertDialog;
    import android.content.DialogInterface;
    import android.content.Intent;
    import android.content.SharedPreferences;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.os.Bundle;
    import android.preference.PreferenceManager;
    import android.util.Log;
    import android.widget.Toast;
    
    import com.facebook.android.AsyncFacebookRunner;
    import com.facebook.android.AsyncFacebookRunner.RequestListener;
    import com.facebook.android.DialogError;
    import com.facebook.android.Facebook;
    
    import com.facebook.android.Facebook.DialogListener;
    import com.facebook.android.FacebookError;
    import com.facebook.android.Util;
    
    public class FbLoginActivity extends Activity {
    private final String TAG = "FbLoginActivity";
    private String token; // used to identify the fb user
    private static final String FACEBOOK_APP_ID = "your_key_here";
    //private String[] permissions = { "email", "friends_about_me", "friends_location"};
    private String[] permissions = {"publish_stream" };
    private String rankText;
    public static String userName;
    private AlertDialog alertDialog;
    private boolean isMyWall = false, isAppWall = true;
    
    // facebook SSO
    Facebook fb = new Facebook(FACEBOOK_APP_ID);
    private AsyncFacebookRunner runner = new AsyncFacebookRunner(fb);
    
    
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.register);
    
        showFbDialog();
    
        SessionEvents.addAuthListener(new SampleAuthListener());
    
    }
    
    private void accessUserData(String token) {
           // get information about the currently logged in user
           runner.request("me", meRequestListener);
    }
    
    private String getRankText() {
        String txt = "your text to be shared here"
    
        return txt;
    }
    
    private void postToFb() {
        // post to feed
        Bundle params = new Bundle();
        params.putString("to", "me");
        params.putString("message", "test msg");
    
       try {
    
           runner.request("me/feed", params, "POST", meRequestListener, null);
       } catch(Throwable t) {
            Log.e(TAG, "caught throwable: " + t, t);
            Toast.makeText(this, "Error on login, is Facebook Installed?", Toast.LENGTH_LONG).show();
            startActivity(new Intent(getApplicationContext(), MaleRankingActivity.class));
       }
    }
    
    public void postImageonWall() {
    
        byte[] data = null;
    
          Bitmap bi = BitmapFactory.decodeFile("/sdcard/viewitems.png");
          ByteArrayOutputStream baos = new ByteArrayOutputStream();
          bi.compress(Bitmap.CompressFormat.JPEG, 100, baos);
          data = baos.toByteArray();
    
    
          Bundle params = new Bundle();
          params.putString(Facebook.TOKEN, fb.getAccessToken());
          params.putString("method", "photos.upload");
          params.putByteArray("picture", data);
    
          AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(fb);
          //mAsyncRunner.request(null, params, "POST", new SampleUploadListener(), null);
    
    }
    
    
    
     private RequestListener meRequestListener = new RequestListener () {
       //called on successful completion of the Request
       public void onComplete(final String response, final Object state){
           Log.d(TAG, "<onComplete> response: " + response);
           try {
               JSONObject fbResponse = new JSONObject(response);
               // set userName
               userName = fbResponse.getString("name");
               Log.d(TAG, "<onComplete> fbResponse: " + fbResponse);           
           } catch (JSONException e) {
               Log.e(TAG, "caught exception: " + e, e);
           }
       }
    
       // called if there is an error
       public void onFacebookError(FacebookError error, final Object state){}
    
       public void onMalformedURLException(java.net.MalformedURLException e, Object state){}
    
       public void onFileNotFoundException(FileNotFoundException arg0, Object arg1) {
           // TODO Auto-generated method stub
    
       }
    
       public void onIOException(IOException arg0, Object arg1) {
           // TODO Auto-generated method stub
    
       }
    };
    
    private void authorizeAndPost() {
       final Bundle params = new Bundle();        
       try {
        // force authorization
           //fb.logout(this);
    
           /*
            * Get existing access_token if any
            */
           SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
           String access_token = mPrefs.getString("access_token", null);
           long expires = mPrefs.getLong("access_expires", 0);
           if(access_token != null) {
               fb.setAccessToken(access_token);
           }
           if(expires != 0) {
               fb.setAccessExpires(expires);
        }
    
        fb.authorize(this, permissions, new DialogListener() {
    
    
                public void onComplete(Bundle values) {
                Log.d(TAG, "<onComplete> entry");
    
                // get rank text 
                rankText = getRankText();
    
                // set text
                params.putString("message", rankText);
    
                // post to ur wall
                if (isMyWall) {                             
                        runner.request("me/feed", params, "POST", new WallPostRequestListener(), null);
                }
    
                // post to rate ur date wall
                if (isAppWall) {
                    runner.request("259166150820823/feed", params, "POST", new WallPostRequestListener(), null);
                }
    
                // toast
                CharSequence text = "Posted date to Facebook!";
                int duration = Toast.LENGTH_LONG;
                Toast toast = Toast.makeText(getApplicationContext(), text, duration);
                toast.show();
    
                // start ranking activity
                Intent intent = new Intent(getApplicationContext(), ShareResultActivity.class);
                intent.putExtra("share_result", "You have successfully posted your date to Facebook!");
                token = fb.getAccessToken();
                Log.d(TAG, "<onComplete> fb access token: " + token);
                //intent.putExtra("userId", token);
    
                long token_expires = fb.getAccessExpires();
                Log.d(TAG, "<onComplete> token expires: " + token_expires);
    
                SharedPreferences prefs= PreferenceManager.getDefaultSharedPreferences(FbLoginActivity.this);
                prefs.edit().putLong("access_expires", token_expires).commit();
                prefs.edit().putString("access_token", token).commit();
                //fb.setAccessExpires(300000); // for testing
    
                // access user data
                accessUserData(token);
    
                //postDateToFb();
    
                startActivity(intent);                          
                }
    
    
                public void onFacebookError(FacebookError e) {
                    Log.e(TAG, "fb error: " + e.getMessage(), e);
                }
    
                public void onError(DialogError e) {
                    Log.e(TAG, "dialog error: " + e.getMessage(), e);
                }
    
                public void onAuthFail(String error) {                  
                    Log.d("<fbExample>", "login failed: " + error);
                }
    
                public void onCancel() {
                    Log.d(TAG, "fb cancelled");
                }
        });
       } catch(Throwable t) {
        Log.e(TAG, "caught throwable: " + t, t);
        Toast.makeText(this, "Error on login, is Facebook Installed?", Toast.LENGTH_LONG).show();
        startActivity(new Intent(getApplicationContext(), LandingActivity.class));
       }
    }
    
    
    public class WallPostRequestListener extends BaseRequestListener {
    
       public void onComplete(final String response, final Object state) {
           Log.d("Facebook-Example", "Got response: " + response);
           String message = "I just rated my date a creeper!";
           try {
               JSONObject json = Util.parseJson(response);
               message = json.getString("message");
           } catch (JSONException e) {
               Log.w("Facebook-Example", "JSON Error in response");
           } catch (FacebookError e) {
               Log.w("Facebook-Example", "Facebook Error: " + e.getMessage());
           }
           final String text = "Your Wall Post: " + message;
           FbLoginActivity.this.runOnUiThread(new Runnable() {
               public void run() {
                   //mText.setText(text);
               }
           });
       }
    
        public void onCancel() {
            Log.d(TAG, "fb cancel");
    
        }
    
        public void onComplete(Bundle arg0) {
            Log.e(TAG, "fb complete.");
    
        }
    
        public void onError(DialogError arg0) {
            Log.e(TAG, "fb err:" + arg0.getMessage());
    
        }
    
        public void onFacebookError(FacebookError arg0) {
            Log.e(TAG, "fb err:" + arg0.getMessage());
    
        }
    
        public void onFacebookError(FacebookError arg0, Object arg1) {
            Log.e(TAG, "fb err:" + arg0.getMessage());
    
        }
    
        public void onFileNotFoundException(FileNotFoundException arg0,
                Object arg1) {
            Log.e(TAG, "fb err:" + arg0.getMessage(), arg0);
    
        }
    
        public void onIOException(IOException arg0, Object arg1) {
            Log.e(TAG, "fb err:" + arg0.getMessage(), arg0);
    
        }
    
        public void onMalformedURLException(MalformedURLException arg0,
                Object arg1) {
            Log.e(TAG, "fb err:" + arg0.getMessage(), arg0);
    
        }
    }
    
    public class SampleAuthListener implements SessionEvents.AuthListener {
    
       public void onAuthSucceed() {
    
           Log.d("<fbExample>", "fb auth token: " + fb.getAccessToken());
    
       }
    
       public void onAuthFail(String error) {
    
           Log.d("<fbExample>", "login failed: " + error);
       }
    }
    
    @Override  
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
            fb.authorizeCallback(requestCode, resultCode, data);  
    }
    
    private void showFbDialog() {
        alertDialog = new AlertDialog.Builder(this)
    
        .setTitle("I want to:")
        .setMultiChoiceItems(new String[] {"Post to my wall", "Post to app's wall" },
                new boolean[]{false, true, false, true, false, false, false},
                new DialogInterface.OnMultiChoiceClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton,
                            boolean isChecked) {
    
                        /* User clicked on a check box do some stuff */
                        Log.d(TAG, "multichoice got click, whichButton: " + whichButton + ", isChecked: " + isChecked);
                        if (whichButton == 0 && isChecked) {
                            isMyWall = true;
                        }
                        if (whichButton == 1 && isChecked) {
                            isAppWall = true;
                        } else if (whichButton == 1 && !isChecked) {
                            isAppWall = false;
                        }
                    }
                })
        .setPositiveButton("Ok",
                new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
    
                /* User clicked Yes so do some stuff */
                Log.d(TAG, "Ok got click");
    
                authorizeAndPost();
            }
        })
        .setNegativeButton("Cancel",
                new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
    
                /* User clicked No so do some stuff */
                Log.d(TAG, "Cancel got click");
    
                startActivity(new Intent(getApplicationContext(), YourActivity.class ));
    
            }
        })
       .create();
        alertDialog.show();
    }
    }
    

    【讨论】:

    • 真的很难理解大部分代码,它似乎对我不起作用。必须有更清晰的方式在用户墙上发帖
    • 如果您详细阅读这些教程,这段代码应该对您有意义。它被张贴作为参考。对不起,如果它没有帮助,但它对我有用。祝你好运!
    • 你能把这个教程的链接发给我吗?我在这个活动中遇到了很多错误。
    • 教程是here
    最近更新 更多