How to send image from app via messenger?

空扰寡人 提交于 2019-11-28 14:31:25

After spending a lot of time on this:

Check if permissions are given. Then:

Step 1: Create ImageView of the image you want to in the activity and then convert it itno bitmap

ImageView imageView = findViewById(R.id.image);
Bitmap bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();

//save the image now:
saveImage(bitmap);
//share it
send();

Step 2: Store the image in internal folder:

private static void saveImage(Bitmap finalBitmap) {

    String root = Environment.getExternalStorageDirectory().getAbsolutePath();
    File myDir = new File(root + "/saved_images");
    Log.i("Directory", "==" + myDir);
    myDir.mkdirs();

    String fname = "Image-test" + ".jpg";
    File file = new File(myDir, fname);
    if (file.exists()) file.delete();
    try {
        FileOutputStream out = new FileOutputStream(file);
        finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
        out.flush();
        out.close();

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

Step 3: Send the saved image:

public void send() {
    try {
        File myFile = new File("/storage/emulated/0/saved_images/Image-test.jpg");
        MimeTypeMap mime = MimeTypeMap.getSingleton();
        String ext = myFile.getName().substring(myFile.getName().lastIndexOf(".") + 1);
        String type = mime.getMimeTypeFromExtension(ext);
        Intent sharingIntent = new Intent("android.intent.action.SEND");
        sharingIntent.setType(type);
        sharingIntent.putExtra("android.intent.extra.STREAM", Uri.fromFile(myFile));
        startActivity(Intent.createChooser(sharingIntent, "Share using"));
    } catch (Exception e) {
        Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
    }
}

Now after sending you can delete the saved image if you don't want it in your storage. Check other link to do that.

Referring your linked post,You could modify the share intent.

 Intent share = new Intent(Intent.ACTION_SEND);
 share.setType("image/*");
 share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///assets/epic/adv.png"));
 this.startActivity(Intent.createChooser(share, "share_via"));

The intent launches the apps which handles Intent.ACTION_SEND. If you want specific app to be respond, make sure you are aware of the package name and you need set package name share.setPackage("");

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!