How to share an image with WhatsApp Android?

2019-08-13 03:42发布

问题:

I'm trying this code to send images to WhatsApp, but when it opens the WhatsApp screen and when I select the contact, I don't see any image. Can someone help me?

    Bitmap adv = BitmapFactory.decodeResource(getResources(), R.drawable.image3);
    Intent share = new Intent(Intent.ACTION_SEND);
    share.setType("image/jpg");
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    adv.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
    File f = new File(Environment.getExternalStorageDirectory()
            + File.separator + "temporary_file.jpg");
    try {
        f.createNewFile();
        new FileOutputStream(f).write(bytes.toByteArray());

    } catch (IOException e) {
        e.printStackTrace();
    }
    Uri imageUri = Uri.parse(f.getAbsolutePath());
    share.putExtra(Intent.EXTRA_STREAM, Uri.parse(Environment.getExternalStorageDirectory() + File.separator + "temporary_file.jpg"));
    //share.putExtra(Intent.EXTRA_STREAM,Uri.parse("file:///android_asset/image3.jpg"));
    if(isPackageInstalled("com.whatsapp",this)){
        share.setPackage("com.whatsapp");
        startActivity(Intent.createChooser(share, "Share Image"));

    }else{

        Toast.makeText(getApplicationContext(), "Please Install Whatsapp", Toast.LENGTH_LONG).show();
    }

}

private boolean isPackageInstalled(String packagename, Context context) {
    PackageManager pm = context.getPackageManager();
    try {
        pm.getPackageInfo(packagename, PackageManager.GET_ACTIVITIES);
        return true;
    } catch (PackageManager.NameNotFoundException e) {
        return false;
    }
}