简体   繁体   中英

Sharing Image via Intent failed

I am trying to capture image and then share it with apps.

private static final int CAMERA_REQUEST = 1888;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_result);

        Intent cameraIntent = new Intent(
               android.provider.MediaStore.ACTION_IMAGE_CAPTURE);

        startActivityForResult(cameraIntent, CAMERA_REQUEST);
        //start the camera and capture an image
}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {

        Uri imageUri = data.getData();
        //convert captured Image from Intent form to URI

        Intent shareIntent = new Intent();
        shareIntent.setAction(Intent.ACTION_SEND);
        shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
        shareIntent.setType("image/jpeg");
        startActivity(shareIntent);
        //share the image

    }
}

But when I run this code, the image doesn't get shared. Is there a bug in my code?

Is there any other way to share an image without saving it in memory?

Intent sharingIntent = new Intent(Intent.ACTION_SEND);
Uri screenshotUri = Uri.parse("android.resource://com.android.test/*");
try {
    InputStream stream = getContentResolver().openInputStream(screenshotUri);
} catch (FileNotFoundException e) {
    e.printStackTrace();
}
sharingIntent.setType("image/jpeg");
sharingIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
startActivity(Intent.createChooser(sharingIntent, "Share image using")); 

I would like to thank Alexander for helping find the solution.

Here is the working code -

private static final int CAMERA_REQUEST = 1888;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_result);
        Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(cameraIntent, CAMERA_REQUEST);
}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
        final Intent intent = new Intent(android.content.Intent.ACTION_SEND);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
               .putExtra(Intent.EXTRA_STREAM,
                Uri.parse(MediaStore.Images.Media.insertImage(getContentResolver(),
                        (Bitmap) data.getExtras().get("data"), "title", null)
               ))
               .setType("image/jpeg");
        startActivity(intent);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM