如何从相机应用程序上传照片到Facebook

时间:2011-10-31 11:35:18

标签: android facebook

我刚刚在android中使用了相机应用程序的代码。在此应用程序中,单击的照片将保存到SD卡中。我的代码用于保存,如下所示:$

Camera.PictureCallback jpegCallback = new PictureCallback() 
    {
        public void onPictureTaken(byte[] data, Camera camera) 
        {
            FileOutputStream outStream = null;
            try 
            {               
                outStream = new FileOutputStream(String.format("/sdcard/%d.jpg", System.currentTimeMillis()));  
                outStream.write(data);
                outStream.close();              
                sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
                Log.d(TAG, "on pictureTaken" + data.length);
            } 
            catch (FileNotFoundException e) 
            {
                e.printStackTrace();
            } 
            catch (IOException e)
            {
                e.printStackTrace();
            } 
            finally
            {}
            Log.d(TAG, "on pictureTaken-jpeg");                         
        }
    };

我只是通过使用FacebookSDK使用另一项活动将该图像从SD卡上传到Facebook,如下图所示。

public class Upload extends Activity  implements OnItemClickListener 
{

    /* Your Facebook Application ID must be set before running this example
     * See http://www.facebook.com/developers/createapp.php
     */
    public static final String APP_ID = "146770088755283";

    private LoginButton mLoginButton;
    private TextView mText;
    private ImageView mUserPic;
    private Handler mHandler;
    ProgressDialog dialog;

    final int AUTHORIZE_ACTIVITY_RESULT_CODE = 0;
    final int PICK_EXISTING_PHOTO_RESULT_CODE = 1;

    private ListView list;
    String[] main_items = {"Upload Photo"};
    String[] permissions = {"offline_access", "publish_stream", "user_photos", "publish_checkins", "photo_upload"};

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        if (APP_ID == null) 
        {
            Util.showAlert(this, "Warning", "Facebook Applicaton ID must be " +
                    "specified before running this example: see FbAPIs.java");
            return;
        }

        setContentView(R.layout.main);
        mHandler = new Handler();

        mText = (TextView) Upload.this.findViewById(R.id.txt);
        mUserPic = (ImageView)Upload.this.findViewById(R.id.user_pic);

        //Create the Facebook Object using the app id.
        Utility.mFacebook = new Facebook(APP_ID);
        //Instantiate the asynrunner object for asynchronous api calls.
        Utility.mAsyncRunner = new AsyncFacebookRunner(Utility.mFacebook);

        mLoginButton = (LoginButton) findViewById(R.id.login);

        //restore session if one exists
        SessionStore.restore(Utility.mFacebook, this);
        SessionEvents.addAuthListener(new FbAPIsAuthListener());
        SessionEvents.addLogoutListener(new FbAPIsLogoutListener());

        /*
         * Source Tag: login_tag
         */
        mLoginButton.init(this, AUTHORIZE_ACTIVITY_RESULT_CODE, Utility.mFacebook, permissions);

        if(Utility.mFacebook.isSessionValid()) 
        {
            requestUserData();
        }

        list = (ListView)findViewById(R.id.main_list);

        list.setOnItemClickListener(this);
        list.setAdapter(new ArrayAdapter<String>(this, R.layout.main_list_item, main_items));
    }

    @Override
    public void onResume() 
    {
        super.onResume();
        if(Utility.mFacebook != null && !Utility.mFacebook.isSessionValid())
        {
            mText.setText("You are logged out! ");
            mUserPic.setImageBitmap(null);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch(requestCode)
        {
            /*
             * if this is the activity result from authorization flow, do a call back to authorizeCallback
             * Source Tag: login_tag
             */
            case AUTHORIZE_ACTIVITY_RESULT_CODE: 
            {
                Utility.mFacebook.authorizeCallback(requestCode, resultCode, data);
                break;
            }
            /*
             * if this is the result for a photo picker from the gallery, upload the image after scaling it.
             * You can use the Utility.scaleImage() function for scaling
             */
            case PICK_EXISTING_PHOTO_RESULT_CODE: 
            { 
                if (resultCode == Activity.RESULT_OK) 
                {
                    Uri photoUri = data.getData();
                    if(photoUri != null) {
                        Bundle params = new Bundle();
                        try 
                        {
                            params.putByteArray("photo", Utility.scaleImage(getApplicationContext(), photoUri));
                        } catch  (IOException e) 
                        {
                            e.printStackTrace();
                        }
                        params.putString("caption", "FbAPIs Sample App photo upload");
                        Utility.mAsyncRunner.request("me/photos", params, "POST", new PhotoUploadListener(), null);
                    } 
                    else
                    {
                        Toast.makeText(getApplicationContext(), "Error selecting image from the gallery.", Toast.LENGTH_SHORT).show();
                    }
                } 
                else 
                {
                    Toast.makeText(getApplicationContext(), "No image selected for upload.", Toast.LENGTH_SHORT).show();
                }
                break;
            }
        }
    }

    public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) 
    {
        switch(position) 
        {

             /*
             * Source Tag: upload_photo
             * You can upload a photo from the media gallery or from a remote server
             * How to upload photo: https://developers.facebook.com/blog/post/498/
             */
            case 0: 
            {
                if(!Utility.mFacebook.isSessionValid()) 
                {
                    Util.showAlert(this, "Warning", "You must first log in.");
                }
                else 
                {
                    dialog = ProgressDialog.show(Upload.this, "", getString(R.string.please_wait), true, true);
                    new AlertDialog.Builder(this)
                        .setTitle(R.string.gallery_title)
                        .setMessage(R.string.gallery_msg)
                        .setPositiveButton(R.string.gallery_button, new DialogInterface.OnClickListener() 
                        {
                            public void onClick(DialogInterface dialog, int which) 
                            {
                                Intent intent = new Intent(Intent.ACTION_PICK, (MediaStore.Images.Media.EXTERNAL_CONTENT_URI));
                                startActivityForResult(intent, PICK_EXISTING_PHOTO_RESULT_CODE);
                            }

                        })
                        .setOnCancelListener(new DialogInterface.OnCancelListener() {
                            public void onCancel(DialogInterface d) {
                                dialog.dismiss();
                            }
                        })
                        .show();
                }
                break;
            }
        }
    }

    /*
     * callback for the feed dialog which updates the profile status
     */
    public class UpdateStatusListener extends BaseDialogListener {
        public void onComplete(Bundle values) {
            final String postId = values.getString("post_id");
            if (postId != null) {
                new UpdateStatusResultDialog(Upload.this, "Update Status executed", values).show();
            } else {
                Toast toast = Toast.makeText(getApplicationContext(), "No wall post made", Toast.LENGTH_SHORT);
                toast.show();
            }
        }

        public void onFacebookError(FacebookError error) {
            Toast.makeText(getApplicationContext(), "Facebook Error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
        }

        public void onCancel() {
            Toast toast = Toast.makeText(getApplicationContext(), "Update status cancelled", Toast.LENGTH_SHORT);
            toast.show();
        }
    }

    /*
     * callback for the apprequests dialog which sends an app request to user's friends.
     */
    public class AppRequestsListener extends BaseDialogListener {
        public void onComplete(Bundle values) {
            Toast toast = Toast.makeText(getApplicationContext(), "App request sent", Toast.LENGTH_SHORT);
            toast.show();
        }

        public void onFacebookError(FacebookError error) {
            Toast.makeText(getApplicationContext(), "Facebook Error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
        }

        public void onCancel() {
            Toast toast = Toast.makeText(getApplicationContext(), "App request cancelled", Toast.LENGTH_SHORT);
            toast.show();
        }
    }

    /*
     * callback for the photo upload
     */
    public class PhotoUploadListener extends BaseRequestListener {

        public void onComplete(final String response, final Object state) {
            dialog.dismiss();
            mHandler.post(new Runnable() {
                public void run() {
                    new UploadPhotoResultDialog(Upload.this, "Upload Photo executed", response).show();
                }
            });
        }

        public void onFacebookError(FacebookError error) {
            dialog.dismiss();
            Toast.makeText(getApplicationContext(), "Facebook Error: " + error.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

    public class FQLRequestListener extends BaseRequestListener {

        public void onComplete(final String response, final Object state) {
            mHandler.post(new Runnable() {
                public void run() {
                    Toast.makeText(getApplicationContext(), "Response: " + response, Toast.LENGTH_LONG).show();
                }
            });
        }

        public void onFacebookError(FacebookError error) {
            Toast.makeText(getApplicationContext(), "Facebook Error: " + error.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

    /*
     * Callback for fetching current user's name, picture, uid.
     */
    public class UserRequestListener extends BaseRequestListener {

        public void onComplete(final String response, final Object state) {
            JSONObject jsonObject;
            try {
                jsonObject = new JSONObject(response);

                final String picURL = jsonObject.getString("picture");
                final String name = jsonObject.getString("name");
                Utility.userUID = jsonObject.getString("id");

                mHandler.post(new Runnable() {
                    public void run() {
                        mText.setText("Welcome " + name + "!");
                        mUserPic.setImageBitmap(Utility.getBitmap(picURL));
                    }
                });

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

    }

    /*
     * The Callback for notifying the application when authorization
     *  succeeds or fails.
     */

    public class FbAPIsAuthListener implements AuthListener {

        public void onAuthSucceed() {
            requestUserData();
        }

        public void onAuthFail(String error) {
            mText.setText("Login Failed: " + error);
        }
    }

    /*
     * The Callback for notifying the application when log out
     *  starts and finishes.
     */
    public class FbAPIsLogoutListener implements LogoutListener {
        public void onLogoutBegin() {
            mText.setText("Logging out...");
        }

        public void onLogoutFinish() {
            mText.setText("You have logged out! ");
            mUserPic.setImageBitmap(null);
        }
    }

    /*
     * Request user name, and picture to show on the main screen.
     */
    public void requestUserData() {
        mText.setText("Fetching user name, profile pic...");
        Bundle params = new Bundle();
        params.putString("fields", "name, picture");
        Utility.mAsyncRunner.request("me", params, new UserRequestListener());
    }


    /**
     * Definition of the list adapter
     */
    public class MainListAdapter extends BaseAdapter {
        private LayoutInflater mInflater;

        public MainListAdapter() {
            mInflater = LayoutInflater.from(Upload.this.getBaseContext());
        }

        public int getCount() {
            return main_items.length;
        }

        public Object getItem(int position) {
            return null;
        }

        public long getItemId(int position) {
            return 0;
        }

        public View getView(int position, View convertView, ViewGroup parent) {

            View hView = convertView;
            if(convertView == null) {
                hView = mInflater.inflate(R.layout.main_list_item, null);
                ViewHolder holder = new ViewHolder();
                holder.main_list_item = (TextView) hView.findViewById(R.id.main_api_item);
                hView.setTag(holder);
            }

            ViewHolder holder = (ViewHolder) hView.getTag();

            holder.main_list_item.setText(main_items[position]);

            return hView;
        }   

    }


    class ViewHolder {
        TextView main_list_item;
    }

}

我想将该照片上传到脸谱而不保存到SD卡以及照片点击的同一活动。如果有人知道,请帮助我....

1 个答案:

答案 0 :(得分:0)

在您的情况下,这是不可能的。原因似乎是您使用本机相机捕捉快照。因此,默认情况下,您的快照将保存到默认位置的SD卡中。你无法阻止它。但是,您仍然可以使用从活动结果返回的数据删除图像。