Android:如何在Facebook墙上发布带有图片标题和一些描述的链接

时间:2012-10-05 09:50:42

标签: android facebook

我在我的应用程序中使用xml解析来解析rss feed。我在我的应用程序中集成了facebook。我的要求是,当我点击分享按钮时,它与图像标题和单个描述共享我的内容。

我存储解析数据的主要活动。

SplashActivity.java

package com.example.shareslab;



import java.util.ArrayList;
import java.util.List;

import com.example.shareslab.R;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.text.Spanned;
import android.text.Html.ImageGetter;
import android.util.Log;
import android.view.Gravity;
import android.view.ViewGroup.LayoutParams;
import android.widget.Toast;

public class SplashActivity extends Activity {
    /** Called when the activity is first created. */
    ProgressDialog progress;
    private List<com.example.shareslab.Message> messages;
    public static String singleDescription;
    public static String title;

    static List<String>imageURLAmit;
    static List<String> titles;
    static List<String> description,link;
    public static String[][] arrays;
    public static ArrayList<String> galleryImages;
    public static int position=0;
    //Handle user current location

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash_activity);



        // Register the listener with the Location Manager to receive location updates

        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = cm.getActiveNetworkInfo();
        Log.d("net status ", "show   "+info);
        if (info != null && info.isAvailable()) {
            Log.d("net connected", "show   "+info);
            System.out.println("Connection OKK");
            new DownloadCities().execute();        

        }
        else{
            Log.d("net not connected", "show   "+info);
            Toast.makeText(SplashActivity.this, "Check Internet connection. And try again.", Toast.LENGTH_LONG).show();
        }
    }


    private class DownloadCities extends AsyncTask<String, Void, String> {
        private String ResultString = "";

        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            if(progress.isShowing()){

                System.out.println("IN POST EXE");
                progress.dismiss();
                startActivity(new Intent(SplashActivity.this,MessageList.class));
            }


            super.onPostExecute(result);
        }

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub

            progress = ProgressDialog.show(SplashActivity.this, "","Loading....");
            progress.setIndeterminate(true);
            progress.getWindow().setGravity(Gravity.BOTTOM);;

            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... arg0) {
            // TODO Auto-generated method stub
            try {
                System.out.println("Going to call  getCitiesFromServer()");
                loadFeed();
            }
            catch (Exception e) { // <-- Use the correct exception type
                ResultString = "Some error message";
            }
            return null;
        }

    }


    private void loadFeed(){
        position=0;

        try{
            BaseFeedParser parser = new BaseFeedParser();
            messages = parser.parse();
            titles = new ArrayList<String>(messages.size());
            description = new ArrayList<String>(messages.size());
            link = new ArrayList<String>(messages.size());
            arrays=new String[messages.size()][];

            final List<String> imageURL=new ArrayList<String>(1);
            imageURLAmit=new ArrayList<String>(messages.size());
            for (com.example.shareslab.Message msg : messages){



                Spanned title=Html.fromHtml(msg.getTitle());
                titles.add(title.toString());
                link.add(msg.getLink().toString());
                Spanned data=Html.fromHtml(msg.getDescription(),new ImageGetter() {

                    public Drawable getDrawable(String source) {

                        // TODO Auto-generated method stub
                            imageURL.add(source);
                        return null;
                    }
                },null);



                if(imageURL.size()!=0){
                    imageURLAmit.add(imageURL.get(0));                  

                }else{
                    imageURLAmit.add("http://blog.kevinlearynet.netdna-cdn.com/files/applausemeter-300x200.jpg");
                }

                System.out.println("Position b4 loop : "+position);
                int j;
                arrays[position]=imageURL.toArray(new String[imageURL.size()]);
                System.out.println("2D array colomn length : "+arrays[position].length);
                position++;
                System.out.println("Position afeter loop : "+position);
                imageURL.clear();           
                description.add( data.toString());
                System.out.println("End addition");
            }
            System.out.println("Final Image URL lenght : "+imageURL.size());


        } catch (Throwable t){
            Log.e("AndroidNews",t.getMessage(),t);
        }

    }

}`

这里是Facebook共享的Facebookc.java类。

Facebookc.java

    package com.example.shareslab;



import com.example.shareslabfb.DialogError;
import com.example.shareslabfb.Facebook;
import com.example.shareslabfb.Facebook.DialogListener;
import com.example.shareslabfb.FacebookError;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Toast;

public class Facebookc extends Activity{

    private static final String APP_ID = "392939617444978";
    private static final String[] PERMISSIONS = new String[] {"publish_stream"};

    private static final String TOKEN = "access_token";
        private static final String EXPIRES = "expires_in";
        private static final String KEY = "facebook-credentials";

    private Facebook facebook;
    private String messageToPost;

    public boolean saveCredentials(Facebook facebook) {
            Editor editor = getApplicationContext().getSharedPreferences(KEY, Context.MODE_PRIVATE).edit();
            editor.putString(TOKEN, facebook.getAccessToken());
            editor.putLong(EXPIRES, facebook.getAccessExpires());
            return editor.commit();
        }

        public boolean restoreCredentials(Facebook facebook) {
            SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences(KEY, Context.MODE_PRIVATE);
            facebook.setAccessToken(sharedPreferences.getString(TOKEN, null));
            facebook.setAccessExpires(sharedPreferences.getLong(EXPIRES, 0));
            return facebook.isSessionValid();
        }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        facebook = new Facebook(APP_ID);
        restoreCredentials(facebook);

        requestWindowFeature(Window.FEATURE_NO_TITLE);

        setContentView(R.layout.facebook_dialog);

        String facebookMessage = getIntent().getStringExtra("facebookMessage");
        if (facebookMessage == null){
            facebookMessage = "";
        }
        messageToPost = facebookMessage;
    }

    public void doNotShare(View button){
        finish();
    }
    public void share(View button){
        if (! facebook.isSessionValid()) {
            loginAndPostToWall();
        }
        else {
            postToWall(messageToPost);
        }
    }

    public void loginAndPostToWall(){
         facebook.authorize(this, PERMISSIONS, Facebook.FORCE_DIALOG_AUTH, new LoginDialogListener());
    }

    public void postToWall(String message){
               Bundle parameters = new Bundle();

               parameters.putString("message", message);
               parameters.putString("name", "titles.get(position)");
               parameters.putString("caption","shareslab.com");
               parameters.putString("link", "http://www.shareslab.com");
               parameters.putString("picture", "imageURLAmit.get(position)");
               parameters.putString("description","description.get(position)");

                try {
                    facebook.request("me");
            String response = facebook.request("me/feed", parameters, "POST");
            Log.d("Tests", "got response: " + response);
            if (response == null || response.equals("") ||
                    response.equals("false")) {
                showToast("Blank response.");
            }
            else {
                showToast("Message posted to your facebook wall!");
            }
            finish();
        } catch (Exception e) {
            showToast("Failed to post to wall!");
            e.printStackTrace();
            finish();
        }
    }

    class LoginDialogListener implements DialogListener {
        public void onComplete(Bundle values) {
            saveCredentials(facebook);
            if (messageToPost != null){
            postToWall(messageToPost);
        }
        }
        public void onFacebookError(FacebookError error) {
            showToast("Authentication with Facebook failed!");
            finish();
        }
        public void onError(DialogError error) {
            showToast("Authentication with Facebook failed!");
            finish();
        }
        public void onCancel() {
            showToast("Authentication with Facebook cancelled!");
            finish();
        }
    }

    private void showToast(String message){
        Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
    }
}

2 个答案:

答案 0 :(得分:1)

如果您的图像保存在SD卡中,则可以在获取图像后使用以下代码: -

在代码中,uri of image被声明为imageUri。

public void performPostToWall(Uri imageUri){
    byte[] data = null;
    ContentResolver cr = context.getContentResolver();
    InputStream in = null;

    try {
        in = cr.openInputStream(imageUri);
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = 1;
        Bitmap thumb = BitmapFactory.decodeStream(in, null, options);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        thumb.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        data = baos.toByteArray();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (Exception e) {
        Toast.makeText(context, "Unable to upload image", Toast.LENGTH_LONG).show();
    }

    Bundle params = new Bundle();
    params.putByteArray("picture", data);
    if (!(captionText == null || captionText.equals("")))
        params.putString("caption", captionText);

    Request req = new Request(session, "me/photos", params, HttpMethod.POST, new Request.Callback() {
        @Override
        public void onCompleted(Response response) {
            context.onPostToMyWallWithImageResponse(response);
        }
    });

    req.executeAsync();

}

答案 1 :(得分:0)

这段代码

public void postToWall(String message){
          try {
        String response=facebook.request("me");  
        Bundle parameters = new Bundle();
        parameters.putString("message", _id);
        parameters.putString("caption", " message.");
        parameters.putString("description", "A secret message is waiting for you.");
        parameters.putString("name", "A Secret Message For You");
        parameters.putString("picture", "http://sheokhanda.files.wordpress.com/2010/06/spring-colors.jpg");
        parameters.putString("link", "http://www.google.com" );

        response = facebook.request("me/feed", parameters, "POST");

        Log.d("Tests", "got response: " + response);
        if (response == null || response.equals("") || response.equals("false")) {
            Log.i(TAG, "Blank Response...");
        }
        else {
            Log.i(TAG, "Message posted to your facebook wall!..");
        }
    } catch (Exception e) {
        e.printStackTrace();
    } 
}

它需要此权限publish_stream