分享在Facebook上发布多个图像 [英] Sharing multiple images on facebook post

查看:176
本文介绍了分享在Facebook上发布多个图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想与Facebook上的状态一起分享多张图片,但我无法发布所有的人。我创建从SD卡的图像阵列列表和转换每一个的字节对象。下面是code上传。任何人都可以请让我知道我所欠缺的code或实现这个需求什么更好的方法我在哪里。

下面写上分享按钮点击code:

 公共无效loginToFacebook(){        字符串hashKey = showHashKey(MainActivity.this);
        Log.d(hashKey,>>>中+ hashKey);        米preFS = GET preferences(MODE_PRIVATE);
        字符串的access_token = M prefs.getString(的access_token,NULL);
        长到期= M prefs.getLong(access_expires,0);        如果(ACCESS_TOKEN!= NULL){
            facebook.setAccessToken(的access_token);            如果(facebook.isSessionValid()){
                会话的会话= facebook.getSession();
                postToWall();
            }
            Log.d(FB会话,+ facebook.isSessionValid());
        }
        如果(到期!= 0){
            facebook.setAccessExpires(到期);
        }
        如果(!facebook.isSessionValid()){
            facebook.authorize(这一点,新的String [] {publish_stream},
                    新DialogListener(){
                        @覆盖
                        公共无效onCancel(){
                            //函数来处理事件取消
                            Log.e(脸部onCancel, - > OK);
                        }                        @覆盖
                        公共无效的onComplete(束值){
                            //函数来处理完成事件
                            //编辑preferences和更新Facebook的acess_token
                            共享preferences.Editor编辑= M prefs.edit();
                            editor.putString(的access_token
                                    facebook.getAccessToken());
                            editor.putLong(access_expires
                                    facebook.getAccessExpires());
                            editor.commit();
                            postToWall();
                            //制作节目的访问令牌按钮可见
                        }                        @覆盖
                        公共无效onerror的(DialogError错误){
                            Log.e(脸部的onError, - >中+误差);
                            //函数来处理错误                        }                        @覆盖
                        公共无效onFacebookError(FacebookError fberror){
                            //函数来处理Facebook的错误
                            Log.e(脸部onFacebookError, - >中+ fberror);                        }                    });
        }
    } 公共字符串showHashKey(上下文的背景下){
        串hashkey =;
        尝试{
            PackageInfo信息= context.getPackageManager()。getPackageInfo(
                    com.example.demofacebook,PackageManager.GET_SIGNATURES); // 你的
            //包
            // 名称
            // 这里
            对(签字签名:info.signatures){
                消息摘要MD = MessageDigest.getInstance(SHA);
                md.update(signature.toByteArray());
                // Log.v(KeyHash:Base64.en codeToString(md.digest()
                // Base64.DEFAULT));
                hashkey = Base64.en codeToString(md.digest(),Base64.DEFAULT);
            }
        }赶上(ē的NameNotFoundException){
        }赶上(抛出:NoSuchAlgorithmException E){
        }
        返回hashkey;
    }@覆盖
    公共无效的onActivityResult(INT申请code,INT结果code,意图数据){
        super.onActivityResult(要求code,结果code,数据);
        facebook.authorizeCallback(要求code,结果code,数据);
        如果(数据!= NULL){
            如果(facebook.getSession()!= NULL){
                。Session.getActiveSession()的addCallback(statusCallback);
                Session.getActiveSession()的onActivityResult(MainActivity.this,
                        要求code,结果code,数据);
            }
        }
        // Session.getActiveSession()的onActivityResult(这一点,要求code,
        //结果code,数据);
        // Session.getActiveSession()的onActivityResult(这一点,要求code,
        //结果code,数据);        // publishFeedDialog();
    }    公共无效postToWall(){
        publishStory();
    }    @覆盖
    保护无效的onSaveInstanceState(捆绑outState){
        // TODO保存当前会话
        super.onSaveInstanceState(outState);
        会话的会话= Session.getActiveSession();
        Session.saveSession(会话,outState);
    }    私有类SessionStatusCallback实现Session.StatusCallback {        @覆盖
        公共无效呼叫(会话的会话,SessionState会的状态,
                例外的例外){
            //检查session打开与否,如果开放和放大器;点击份额
            //按钮出版的故事
            如果(会话= NULL&放大器;!&安培; state.isOpened()){
                Log.d(FbShare,会话被打开);
                如果(session.getPermissions()。包含(publish_actions)){
                    Log.d(FbShare,启动股);
                    publishAction();
                }其他{
                    Log.d(FbShare,会话不具有权限);
                    publishStory();
                }
            }其他{
                Log.d(FbShare,无效FB会议);
            }
        }
    }    私人无效publishStory(){        会话的会话= Session.getActiveSession();
        如果(会话= NULL&放大器;!&安培; session.getState()isOpened()){
            checkSessionAndPost();
        }其他{
            Log.d(FbShare,会话为空);
            //会话=新的Session(ShareActivity.this);
            会话=新Session.Builder(本).setApplicationId(APP_ID)
                    。建立();
            Session.setActiveSession(会话);
            session.addCallback(statusCallback);            Log.d(FbShare,会话信息 - +会话);
            尝试{
                Log.d(FbShare,读会议开幕);
                session.openForRead(新Session.OpenRequest(MainActivity.this));
            }赶上(抛出UnsupportedOperationException除外){
                exception.printStackTrace();
                Log.d(FbShare,异常捕获);
                Toast.makeText(MainActivity.this,
                        无法在Facebook上发布你的分数,
                        Toast.LENGTH_LONG).show();
            }
        }
    }    私人无效checkSessionAndPost(){        会话的会话= Session.getActiveSession();
        session.addCallback(statusCallback);
        Log.d(FbShare
                会话的权限是 - + session.getPermissions());
        如果(session.getPermissions()。包含(publish_actions)){
            publishAction();
        }其他{
            session.requestNewPublishPermissions(新Session.NewPermissionsRequest(
                    MainActivity.this,权限));
        }
    }
//文件路径是从SD卡图像的数组列表
    私人无效publishAction(){
        最终捆绑PARAMS =新包();
        的FileInputStream流= NULL;
        字节[] imgData = NULL;
        尝试{
            params.putString(名,你好周三测试11月20日);
            params.putString(标题,测试11月20日);
            params.putString(链接,);
            的String []字节串=新的String [3];
            的for(int i = 0; I< filePaths.size();我++){
                Log.i(已通过FILE,====+ filePaths.get(I));
                Log.i(图象文件,====+图片+第(i + 1));
                流=新的FileInputStream(filePaths.get(I));
                位图位图= BitmapFactory.de codeStream(流);
                ByteArrayOutputStream BOS =新ByteArrayOutputStream();
                bitmap.com preSS(比较pressFormat.JPEG,100,BOS);
                imgData = bos.toByteArray();
                字节串[I] = filePaths.get(ⅰ)的ToString();
                params.putByteArray(图片+ I + 1,imgData);
            }
            // params.putStringArray(图像,字节串);
        }赶上(FileNotFoundException异常五){
            e.printStackTrace();
        }        // params.putString(
        //描述,
        //);        // params.putString(图片,+ imgData);
        // params.putByteArray(图片2,imgData);
        // params.putByteArray(图片3,imgData);
        // params.putStringArrayList(图片报,文件路径);        新主题(新的Runnable接口(){
            @燮pressWarnings(未使用)
            @覆盖
            公共无效的run(){
                尝试{
                    最后弦乐反应= facebook.request(ME /照片,
                            PARAMS,POST);
                    runOnUiThread(新的Runnable(){
                        @覆盖
                        公共无效的run(){
                            Toast.makeText(getApplicationContext(),
                                    后上传成功,
                                    Toast.LENGTH_SHORT).show();
                            Utility.dismissCustomProgressDialog();
                        }
                    });
                }赶上(FileNotFoundException异常五){
                    e.printStackTrace();
                    Utility.dismissCustomProgressDialog();
                }赶上(MalformedURLException的E){
                    e.printStackTrace();
                    Utility.dismissCustomProgressDialog();
                }赶上(IOException异常五){
                    e.printStackTrace();
                    Utility.dismissCustomProgressDialog();
                }
            }
        }){
        }。开始();    }


解决方案

您正在混合使用Session和Facebook(这是在SDK的推出V3.0)(也就是现在的德precated)这两个管理您的访问令牌,并帮助你做出请求。这使得你的逻辑很难破译。请坚持ONLY会话,并删除所有使用德precated code(在Facebook类的所有内容)的。

其次,还有一个辅助方法,可以帮助你上传照片,它在Request类:<一href=\"https://developers.facebook.com/docs/reference/android/3.0/Request#newUploadPhotoRequest(Session,%20Bitmap,%20Callback)\" rel=\"nofollow\">https://developers.facebook.com/docs/reference/android/3.0/Request#newUploadPhotoRequest(Session,%20Bitmap,%20Callback).它也重载采取任何位图或文件。

如果您要上传多张照片,你可以创建多个请求,并把它们添加到批处理,如:

 请求R1 = Request.newUploadPhotoRequest(...);
请求R2 = Request.newUploadPhotoRequest(...);
RequestBatch批次=新RequestBatch(R1,R2);
batch.executeAsync();

最后,我/照片端点仅接受源(图像),消息和地方参数,并且不接受标题或链接。看到这里详细文档 https://developers.facebook.com/docs/reference / API /用户/#照片

I want to share multiple images along with the status on the Facebook, but i am not able to post all of them. I am creating an array-list of the images from the sdcard and converting each one to the byte object. Below is the code for the upload. Can anyone please let me know where i am lacking in the code or any better way to implement the requirement.

Below is the code written on the share button click:

public void loginToFacebook() {

        String hashKey = showHashKey(MainActivity.this);
        Log.d("hashKey", ">>> " + hashKey);

        mPrefs = getPreferences(MODE_PRIVATE);
        String access_token = mPrefs.getString("access_token", null);
        long expires = mPrefs.getLong("access_expires", 0);

        if (access_token != null) {
            facebook.setAccessToken(access_token);

            if (facebook.isSessionValid()) {
                Session session = facebook.getSession();
                postToWall();
            }
            Log.d("FB Sessions", "" + facebook.isSessionValid());
        }
        if (expires != 0) {
            facebook.setAccessExpires(expires);
        }
        if (!facebook.isSessionValid()) {
            facebook.authorize(this, new String[] { "publish_stream" },
                    new DialogListener() {
                        @Override
                        public void onCancel() {
                            // Function to handle cancel event
                            Log.e("Face onCancel", "-> ok");
                        }

                        @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",
                                    facebook.getAccessToken());
                            editor.putLong("access_expires",
                                    facebook.getAccessExpires());
                            editor.commit();
                            postToWall();
                            // Making show access tokens button visible
                        }

                        @Override
                        public void onError(DialogError error) {
                            Log.e("Face onError", "-> " + error);
                            // Function to handle error

                        }

                        @Override
                        public void onFacebookError(FacebookError fberror) {
                            // Function to handle Facebook errors
                            Log.e("Face onFacebookError", "-> " + fberror);

                        }

                    });
        }
    }



 public String showHashKey(Context context) {
        String hashkey = "";
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(
                    "com.example.demofacebook", PackageManager.GET_SIGNATURES); // Your
            // package
            // name
            // here
            for (Signature signature : info.signatures) {
                MessageDigest md = MessageDigest.getInstance("SHA");
                md.update(signature.toByteArray());
                // Log.v("KeyHash:", Base64.encodeToString(md.digest(),
                // Base64.DEFAULT));
                hashkey = Base64.encodeToString(md.digest(), Base64.DEFAULT);
            }
        } catch (NameNotFoundException e) {
        } catch (NoSuchAlgorithmException e) {
        }
        return hashkey;
    }

@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        facebook.authorizeCallback(requestCode, resultCode, data);
        if (data != null) {
            if (facebook.getSession() != null) {
                Session.getActiveSession().addCallback(statusCallback);
                Session.getActiveSession().onActivityResult(MainActivity.this,
                        requestCode, resultCode, data);
            }
        }
        // Session.getActiveSession().onActivityResult(this, requestCode,
        // resultCode, data);
        // Session.getActiveSession().onActivityResult(this, requestCode,
        // resultCode, data);

        // publishFeedDialog();
    }

    public void postToWall() {
        publishStory();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        // TODO Save current session
        super.onSaveInstanceState(outState);
        Session session = Session.getActiveSession();
        Session.saveSession(session, outState);
    }

    private class SessionStatusCallback implements Session.StatusCallback {

        @Override
        public void call(Session session, SessionState state,
                Exception exception) {
            // Check if Session is Opened or not, if open & clicked on share
            // button publish the story
            if (session != null && state.isOpened()) {
                Log.d("FbShare", "Session is opened");
                if (session.getPermissions().contains("publish_actions")) {
                    Log.d("FbShare", "Starting share");
                    publishAction();
                } else {
                    Log.d("FbShare", "Session dont have permissions");
                    publishStory();
                }
            } else {
                Log.d("FbShare", "Invalid fb Session");
            }
        }
    }

    private void publishStory() {

        Session session = Session.getActiveSession();
        if (session != null && session.getState().isOpened()) {
            checkSessionAndPost();
        } else {
            Log.d("FbShare", "Session is null");
            // session = new Session(ShareActivity.this);
            session = new Session.Builder(this).setApplicationId(APP_ID)
                    .build();
            Session.setActiveSession(session);
            session.addCallback(statusCallback);

            Log.d("FbShare", "Session info - " + session);
            try {
                Log.d("FbShare", "Opening session for read");
                session.openForRead(new Session.OpenRequest(MainActivity.this));
            } catch (UnsupportedOperationException exception) {
                exception.printStackTrace();
                Log.d("FbShare", "Exception Caught");
                Toast.makeText(MainActivity.this,
                        "Unable to post your score on facebook",
                        Toast.LENGTH_LONG).show();
            }
        }
    }

    private void checkSessionAndPost() {

        Session session = Session.getActiveSession();
        session.addCallback(statusCallback);
        Log.d("FbShare",
                "Session Permissions Are - " + session.getPermissions());
        if (session.getPermissions().contains("publish_actions")) {
            publishAction();
        } else {
            session.requestNewPublishPermissions(new Session.NewPermissionsRequest(
                    MainActivity.this, permissions));
        }
    }
// filePaths is arraylist of the images from sdcard
    private void publishAction() {
        final Bundle params = new Bundle();
        FileInputStream stream = null;
        byte[] imgData = null;
        try {
            params.putString("name", "Hello Wednesday test 20 Nov");
            params.putString("caption", "test 20 Nov");
            params.putString("link", "");
            String[] byteStrings = new String[3];
            for (int i = 0; i < filePaths.size(); i++) {
                Log.i("PASSED FILE", "==== " + filePaths.get(i));
                Log.i("PICTURE FILE", "==== " + "picture" + (i + 1));
                stream = new FileInputStream(filePaths.get(i));
                Bitmap bitmap = BitmapFactory.decodeStream(stream);
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                bitmap.compress(CompressFormat.JPEG, 100, bos);
                imgData = bos.toByteArray();
                byteStrings[i] = filePaths.get(i).toString();
                params.putByteArray("picture" + i + 1, imgData);
            }
            // params.putStringArray("images" , byteStrings);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        // params.putString(
        // "description",
        // "");

        // params.putString("picture", ""+imgData);
        // params.putByteArray("picture2", imgData);
        // params.putByteArray("picture3", imgData);
        // params.putStringArrayList("picture", filePaths);

        new Thread(new Runnable() {
            @SuppressWarnings("unused")
            @Override
            public void run() {
                try {
                    final String response = facebook.request("me/photos",
                            params, "POST");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(),
                                    "Post uploaded successfully",
                                    Toast.LENGTH_SHORT).show();
                            Utility.dismissCustomProgressDialog();
                        }
                    });
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                    Utility.dismissCustomProgressDialog();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                    Utility.dismissCustomProgressDialog();
                } catch (IOException e) {
                    e.printStackTrace();
                    Utility.dismissCustomProgressDialog();
                }
            }
        }) {
        }.start();

    }

解决方案

You're mixing the use of Session (which was introduced in v3.0 of the SDK) and Facebook (which is now deprecated), both of which manage your access token and help you make requests. This makes your logic very difficult to decipher. Please stick to ONLY Session, and remove all use of deprecated code (everything in the Facebook class).

Secondly, there's a helper method that helps you upload photos, it's in the Request class: https://developers.facebook.com/docs/reference/android/3.0/Request#newUploadPhotoRequest(Session,%20Bitmap,%20Callback). It's also overloaded to take either a Bitmap or a File.

If you want to upload multiple photos, you can create multiple requests, and add them to a batch, like:

Request r1 = Request.newUploadPhotoRequest(...);
Request r2 = Request.newUploadPhotoRequest(...);
RequestBatch batch = new RequestBatch(r1, r2);
batch.executeAsync();

Lastly, the me/photos endpoint only accepts the "source" (the image), "message", and "place" parameters, and does not accept "caption" or "link". See the detailed documentation here https://developers.facebook.com/docs/reference/api/user/#photos

这篇关于分享在Facebook上发布多个图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆