Facebook与文本和图象的墙壁岗位

时间:2013-08-12 22:57:11

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

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

我在设置SDK方面取得了成功,并获得了剩余的APP_ID,这是用于在用户墙上共享我的应用程序的自定义按钮的Java代码。

3 个答案:

答案 0 :(得分:1)

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

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();
                        }

P.S。第一种方法是在用户的Facebook墙上发布图像,后者用于在Facebook上用户的相册中上传带有消息的图片,这也将作为更新发布!

答案 1 :(得分:0)

你去吧。你可能需要做一些调试等,但这对我有用。

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();
}
}

答案 2 :(得分:0)

您可以非常简单的方式使用应用中的文字发布图像。

在点击按钮小部件时调用此方法,如{... 1}} ...

btnImagePostToWall

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

btnImagePostToWall.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            postImageToWall();
        }
    });

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

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);
}

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