Sharing data on Android with Intent - android

I'm having a problem with sharing content on android between apps, with Intent
I can successfully share plain text (on G+, Facebook and Facebook Messenger)
The code is the following:
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_TEXT,"Your score is: "+Integer.toString(mScore));
shareIntent.setType("text/plain");
startActivity(Intent.createChooser(shareIntent, getResources().getText(R.string.send_to)));
But when it comes to images things don't work.
Intent is created and I can actually choose between the apps to share the image with, but when the selected app tries to start, it just crashes and doesn't open.
No app works (tested with 9Gag, G+, Facebook, Facebook Messenger, Photos..)
The code I'm using is this:
Intent shareIntent = new Intent();
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, uriToImage);
shareIntent.setType("image/png");
startActivity(Intent.createChooser(shareIntent, getResources().getText(R.string.send_to)));
The image is stored on
/data/data/com.test.carloalberto.myapp/files/score.png
which is the right path where i previously saved the image.
Why do other apps crash when trying to share an image?
Thanks for reply.
EDIT: I stored the image in the public picture directory, but apps like fb messenger trying to share it still crash!
This is the new code:
File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String name = "score.jpg";
File file = new File(dir,name);
FileOutputStream ostream;
try {
if(!dir.exists()) {
Log.i("Share: onClick()","Creating directory "+dir);
dir.mkdirs();
}
Log.i("Share: onClick()","Final path: "+file.getAbsolutePath());
file.createNewFile();
ostream = new FileOutputStream(file);
Log.i("onClick(): Share action: ","Path: "+file.getAbsolutePath());
bitmap.compress(Bitmap.CompressFormat.JPEG,100,ostream);
ostream.close();
Uri uriToImage = Uri.parse(file.getAbsolutePath());
Log.i("onClick(): Share action, final uri ",uriToImage.toString());
Intent shareIntent = new Intent();
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, uriToImage);
shareIntent.setType("image/jpeg");
startActivity(Intent.createChooser(shareIntent,getResources().getText(R.string.send_to)));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
} catch (Exception e){
e.printStackTrace();
}
Now the file path is: /mnt/sdcard/Pictures/score.jpg, which should be public and accessible by all other applications.
(Obviously I also set the permissions in the manifest file)

/data/* path is not available to apps (security model of the filesystem every *nix user should be aware of).
The fact you are able to access this folder on your rooted device does not mean the app could do the same.
You could either store your image in publicly available directory (such as Pictures folder of the device, etc), or try to construct URI for your asset using the scheme:
android.resource://[package]/[res type]/[res name]

Try this.
private void shareIntent(String type,String text){
File filePath = getFileStreamPath("shareimage.jpg");
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_TEXT, text);
shareIntent.putExtra(Intent.EXTRA_STREAM,Uri.fromFile(new File(filePath)));
shareIntent.setType("image/*"); //"image/*" or "image/jpeg", etc
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(shareIntent, "send"));
}

Related

Instagram sharing issue: Always I get the message “Unable to load image”

I'm working on share functionality
I 've a problem with Instagram Share
Here is my code :
I'm trying share "account" image which is stored in "drawable" folder.This is just an example
try {
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("image/*");
shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Uri uri = Uri.parse("android.resource://com.example.swathi.booklender/drawable/account");
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
shareIntent.setPackage("com.instagram.android");
startActivity(shareIntent);
}catch (Exception e)
{
Toast.makeText(getActivity(),"No Activity available, install instagram",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
How to I get rid of this problem?
You can't share drawable directly
First create a file from drawable then share it
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("image/jpg");
File image = new File(getFilesDir(), "foo.jpg");
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(image));
startActivity(Intent.createChooser(shareIntent, "Share image via"));

Android ACTION_SEND event: "messaging failed to upload attachment"

I'm trying to implement a share button that captures a screenshot and shares it through the standard Android interface. I'm able to create the screenshot (and I can see it when I browse the SD card), but when I try to send it, the messages app gives the error: "messaging failed to upload attachment."
My code
File imageDir = new File(Environment.getExternalStorageDirectory(), "inPin");
if(!imageDir.exists()) { imageDir.mkdirs(); }
File closeupImageFile = new File(imageDir, "closeup.png");
File overviewImageFile = new File(imageDir, "overview.png");
View mapView = findViewById(R.id.floor_map);
saveScreenshotToFile(mapView, closeupImageFile);
ArrayList<Uri> imageUris = new ArrayList<Uri>();
imageUris.add(Uri.fromFile(closeupImageFile));
String message = String.format("I'm on %s %s", building.name, getCurrentFloor().name);
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, message);
sendIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageUris);
sendIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
sendIntent.setType("image/*");
startActivity(Intent.createChooser(sendIntent, "Share via"));
The saveScreenshotToFile method
private static void saveScreenshotToFile(View view, File saveFile) throws IOException {
view.setDrawingCacheEnabled(true);
view.buildDrawingCache(true);
Bitmap bitmap = view.getDrawingCache();
FileOutputStream out = new FileOutputStream(saveFile);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.close();
}
I'm using Android Marshmallow, API level 23, on the emulator—I don't know if this makes a difference, but I was able to share using other apps on the emulator and it worked fine.
You are sending File URIs, with which Intent.FLAG_GRANT_READ_URI_PERMISSION does not apply and should not be used, as explained in this video and its accompanying blog post. Other apps would need the storage permission to access your files.
From the blog post:
Instead, you can use URI permissions to grant other apps access to specific Uris. While URI permissions don’t work on file:// URIs as is generated by Uri.fromFile(), they do work on Uris associated with Content Providers. Rather than implement your own just for this, you can and should use FileProvider as explained in the File Sharing Training.
If you have to send MMS with any Image using Intent then use this code.
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.setClassName("com.android.mms", "com.android.mms.ui.ComposeMessageActivity");
sendIntent.putExtra("sms_body", "some text");
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///sdcard/image_4.png"));
sendIntent.setType("image/png");
startActivity(sendIntent);
OR
If you have to send MMS with Audio or Video file using Intent then use this.
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.setClassName("com.android.mms", "com.android.mms.ui.ComposeMessageActivity");
sendIntent.putExtra("address", "1213123123");
sendIntent.putExtra("sms_body", "if you are sending text");
final File file1 = new File(mFileName);
if(file1.exists()){
System.out.println("file is exist");
}
Uri uri = Uri.fromFile(file1);
sendIntent.putExtra(Intent.EXTRA_STREAM, uri);
sendIntent.setType("video/*");
startActivity(sendIntent);

sharing image with whatsapp in android

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.
This worked for me
Bitmap imgBitmap=BitmapFactory.decodeResource(getResources(),R.drawable.image);
String imgBitmapPath= MediaStore.Images.Media.insertImage(getContentResolver(),imgBitmap,"title",null);
Uri imgBitmapUri=Uri.parse(imgBitmapPath);
Intent shareIntent=new Intent(Intent.ACTION_SEND);
shareIntent.setType("image/*");
shareIntent.putExtra(Intent.EXTRA_STREAM,imgBitmapUri);
startActivity(Intent.createChooser(shareIntent,"share image using"));

how to save and share bitmap in android

I have activity with image view and share button,
the image retrieved from DB
I want to save the image at first then share it
every things is going fine , the image saved in internal memory and it's going to share but when the other app runs (like whatsapp or messaging) it says file not support
I have push other image to ddms manually and then share is works without any problem !! O.o
I think the problem is from saving the bitmap, even I checked the saved bitmap from the ddms and it was looks good
there is my codes:
save
try {
FileOutputStream out = new FileOutputStream(new File(getFilesDir(), "temp.png"));
imageview.setImageBitmap(b1);
b1.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
}
catch (Exception e) {}
share method
private void initShareIntent(String type,String _text)
{
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM,Uri.fromFile(new File(getFilesDir(), "temp.png")));
shareIntent.setType("image/PNG");
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(shareIntent, "send"));
}
Edit this
shareIntent.setType("image/*");
To this
shareIntent.setType("image/png");
I think it should work. Let me know if it works for you!!
[EDIT1] changed to png (instead of PNG) cause I think the case matters here. lol
[EDIT2] for multiple images try this (provided by GOOGLE :P)
ArrayList<Uri> imageUris = new ArrayList<Uri>();
imageUris.add(imageUri1); // Add your image URIs here
imageUris.add(imageUri2);
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND_MULTIPLE);
shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageUris);
shareIntent.setType("image/*");
startActivity(Intent.createChooser(shareIntent, "Share images to.."));

photo share intent in android

Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
shareIntent.setType("image/*");
Uri uri = Uri.parse(pathToImage);
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
return shareIntent;
i was used above code for sharing image on social sites.when i posting image on facebook only text is posted and image is not coming.how can we get the image and pathtoimage is string variable i am getting sever image path and stored in string variable.but it is not working.please give any solutions for my above question.?
Try this
Bitmap icon = mBitmap;
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
icon.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File f = new File(Environment.getExternalStorageDirectory() + File.separator + "temporary_file.jpg");
try {
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
} catch (IOException e) {
e.printStackTrace();
}
share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///sdcard/temporary_file.jpg"));
startActivity(Intent.createChooser(share, "Share Image"));
Refer more links
http://android-developers.blogspot.in/2012/02/share-with-intents.html
Android Share Via Dialog
Image post into facebook wall from android sdcard
This is the solution I came up with:
This function allows you to share to instagram, facebook or any other app if you know the package name. If the app is not installed it redirects to the Play Store. If you send "others" as parameters, you will display a list of apps that also support image sharing.
shareImageIntent(mActivity,"image/*", "/storage/emulated/0/Pictures/Instagram/IMG_20150120_095603.jpg", "Instagram Sharing test. #Josh","com.instagram.android"); // parameters - for facebook: "com.facebook.katana" , to display list of other apps you can share to: "others"
public void shareImageIntent(Activity a,String type, String mediaPath, String caption, String app){
Intent intent = mContext.getPackageManager().getLaunchIntentForPackage(app);
if ((intent != null)||(app.equals("others"))){
// Create the new Intent using the 'Send' action.
Intent share = new Intent(Intent.ACTION_SEND);
if(!app.equals("others"))
share.setPackage(app);
// Set the MIME type
share.setType(type);
// Create the URI from the media
File media = new File(mediaPath);
Uri uri = Uri.fromFile(media);
// Add the URI and the caption to the Intent.
share.putExtra(Intent.EXTRA_STREAM, uri);
share.putExtra(Intent.EXTRA_TEXT, caption);
// Broadcast the Intent.
//startActivity(Intent.createChooser(share, "Share to"));
a.startActivity(share);
}
else{
intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//intent.setData(Uri.parse("market://details?id="+"com.instagram.android"));
intent.setData(Uri.parse("market://details?id="+app));
a.startActivity(intent);
}
}
You can not use Intent to post to Facebook. They have specifically blocked this. You have to either use their SDK or copy it to the clipboard and have the user paste it after the facebook interface opens. I am having this same problem.

Categories

Resources