I have image in assets folder and need to share it with whatsapp application
I tried this code , it keeps give me sharing failed try again ! what's wrong ?!
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/*");
share.setPackage("com.whatsapp");
// share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File("file:///assets/epic/adv.png")));
share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///assets/epic/adv.png"));
this.startActivity(Intent.createChooser(share, "share_via"));
This code for share image via whatsapp worked fine for me .
public void shareImageWhatsApp() {
Bitmap adv = BitmapFactory.decodeResource(getResources(), R.drawable.adv);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
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();
}
share.putExtra(Intent.EXTRA_STREAM,
Uri.parse( Environment.getExternalStorageDirectory()+ File.separator+"temporary_file.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 (NameNotFoundException e) {
return false;
}
}
You have several problems.
First, file:///assets/
is not a valid Uri
on any version of Android. Your own application can refer to its own assets via file:///android_asset/
.
Second, only you can access your own assets via file:///android_asset/
-- you cannot pass such a Uri
to third-party apps. Either copy the file from assets into internal storage and use FileProvider
, or you can try my StreamProvider
and try to share the data straight out of assets/
.
Third, there is no guarantee that com.whatsapp
exists on the device, or that com.whatsapp
will support ACTION_SEND
of file:///
Uri
values with a MIME type of image/*
, and so you may crash with an ActivityNotFoundException
.
Fourth, the user might want to share this image via some other means than WhatsApp. Please allow the user to share where the user wants, by removing the setPackage()
call from your Intent
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With