I saw other questions about this, tried their answers, but don't work.
I am trying to use the second method from developer.android.com.
(the second white bullet).
I save an image to applications internal memory, with appropriate permissions.
The image (bitmap) is saved successfully, but I can't attach it to a new intent, to share it.
Here is my code:
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("*/*");//Attach all types (images/text)
FileOutputStream fos;
try{
fos = openFileOutput(myfilename, Context.MODE_WORLD_READABLE);
mybitmap.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.flush();
//Image is stored successfully (checked data/data/mypackage/files/myfilename)
Uri uri = Uri.fromFile(getFileStreamPath(myfilename));
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
}
catch (Exception e){
// noth
//Log.e(TAG, e.getStackTrace().toString());
}
shareIntent.putExtra(Intent.EXTRA_TEXT, "some text also");
return shareIntent;
}
Applications say that can't attach media items.
Gmail seems to attach item, but it shows nothing when mail send!
Also the uri.getPath returns me:
/data/data/mypackage/files/myfilename,
which is correct
Any ideas?
Thank you!
Edit:
Modified code to use sd card. And still don't get it to work:
File imgDir;
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED))
imgDir = new File(
android.os.Environment.getExternalStorageDirectory(),
".MyAppName/Images");
else imgDir = MyActivity.this.getCacheDir();
if (!imgDir.exists()) imgDir.mkdirs();
File output = new File(imgDir, myFilename);
OutputStream imageFileOS;
try{
Uri uriSavedImage = Uri.fromFile(output);
imageFileOS = getContentResolver().openOutputStream(
uriSavedImage);
bitmapBookCover.compress(Bitmap.CompressFormat.PNG, 90,
imageFileOS);
imageFileOS.flush();
imageFileOS.close();
//Again image successfully saved
shareIntent.putExtra(Intent.EXTRA_STREAM, uriSavedImage);
}
catch (Exception e){
// noth
}
Please try usiing setData() instead of putExtra(), here android developer site - intent set data
Related
I'm getting an input stream from a webservice and converting it to byte array so i can create a temporary file and play it using MediaPlayer (it is a .mp3). The problem is that i want to share the song on whatsapp, but i get the "failed to send" message whenever i try.
This is how i get and play the song:
if (response.body() != null) {
byte[] bytes = new byte[0];
try {
bytes = toByteArray(response.body().byteStream());
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.reset();
try {
File tempMp3 = File.createTempFile("tempfile", "mp3", getContext().getCacheDir());
tempMp3.deleteOnExit();
FileOutputStream fos = new FileOutputStream(tempMp3);
fos.write(mp3);
fos.close();
FileInputStream fis = new FileInputStream(tempMp3);
mediaPlayer.setDataSource(fis.getFD());
mediaPlayer.prepare();
}
catch (IOException ex) {
String s = ex.toString();
ex.printStackTrace();
}
mediaPlayer.start();
This and a few similar ways is how i have tried to share it:
String sharePath = Environment.getExternalStorageDirectory().getPath()
+ "/tempfile.mp3";
Uri uri = Uri.parse(sharePath);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("audio/*");
share.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(share, "Share Sound File"));
The song is playing just fine and i have included the permission both for reading and writing in the external storage but i need help to share the song, be it as bytes or as file or as whatever works, please.
You will need to change from
File tempMp3 = File.createTempFile("tempfile", "mp3", getContext().getCacheDir());
to
File tempMp3 = new File(Environment.getExternalStorageDirectory() + "/"+ getString(R.string.temp_file) + getString(R.string.dot_mp3)); //<- this is "tempfile" and ".mp3"
then you can share it like this
String sharePath = tempMp3.getAbsolutePath();
Uri uri = Uri.parse(sharePath);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("audio/*");
share.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(share, getString(R.string.share_song_file)));
The main problem was that where you were storing the file could NOT be shared with other apps, was only accessible from your own, since the getCacheDir() method is used to create cache files rather than storing data in files persistently, and is sort of private to the application (and createTempFile() generates random numbers at the end of the file's name, so you wouldn't be able to hard code the correct path like that).
Also, this solution makes use of the permissions you included (accessing external storage).
I want to save my bitmap to cache directory.
I use this code:
try {
File file_d = new File(dir+"screenshot.jpg");
#SuppressWarnings("unused")
boolean deleted = file_d.delete();
} catch (Exception e) {
// TODO: handle exception
}
imagePath = new File(dir+"screenshot.jpg");
FileOutputStream fos;
try {
fos = new FileOutputStream(imagePath);
bitmap.compress(CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
Log.e("GREC", e.getMessage(), e);
} catch (IOException e) {
Log.e("GREC", e.getMessage(), e);
}
}
it s working fine. But if I want to save different img to same path, something goes wrong. I mean it is saved to same path but I see it old image, but when I click the image I can see the correct image which I saved second time.
Maybe its come from cache but I do not want to see old image because when I want to share that image with whatsapp old image seen , if i send the image it seems correct.
I want to share saved image on whatsapp like this code:
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(imagePath));
shareIntent.setType("image/jpeg");
startActivityForResult(Intent.createChooser(shareIntent, getResources().getText(R.string.title_share)),whtsapp_result);
How can I fix it?
thanks in advance.
Finally I solved my problem like this:
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, getImageUri(context,bitmap_));
shareIntent.setType("image/jpeg");
startActivityForResult(Intent.createChooser(shareIntent, getResources().getText(R.string.title_share)),whtsapp_result);
v
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "TitleC1", null);
return Uri.parse(path);
}
This is just a guess, but since you save a new image (with the old name, or another, that’s not relevant) you should fire a media scan to that path so that the media provider is updated with new content.
See here:
MediaScannerConnection.scanFile(context, new String[]{imagePath}, null, null);
Or even better, wait for the scan to be completed:
MediaScannerConnection.scanFile(context, new String[]{imagePath}, null, new OnScanCompletedListener() {
#Override
void onScanCompleted(String path, Uri uri) {
// Send your intent now.
}
});
In any case this should be called after the new file is saved. As I said, I have not tested and this is just a random guess.
I need to share an image (.png format) with transparent background, through sent_action intent.
I searched a lot and tried a lot of samples but couldn't find the solution.
The is this method in witch the image will get shared directly from the resources, but for some reason from some point it has stop working.
Uri url = Uri.parse("android.resource://"
+ getPackageName() + "/" + R.drawable.ic_launcher);
Intent share_intent = new Intent();
share_intent.setAction(Intent.ACTION_SEND);
share_intent.setType("image/png");
share_intent.putExtra(Intent.EXTRA_STREAM,
Uri.fromFile(new File(url.toString())));
startActivity(Intent.createChooser(share_intent, "choose app"));
and there is this function which works fine, the problem is it adds a black background to the image.
private void share3()
{
Bitmap bitmap;
OutputStream output;
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
File filepath = Environment.getExternalStorageDirectory();
File dir = new File(filepath.getAbsolutePath() + "/Gallery/");
dir.mkdirs();
File file = new File(dir, "ic_launcher" + ".png");
try {
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/png");
output = new FileOutputStream(file);
bitmap. compress(Bitmap.CompressFormat.PNG/*Bitmap.CompressFormat.PNG*/, 0, output);
output.flush();
output.close();
Uri uri = Uri.fromFile(file);
share.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(share, "choose app"));
} catch (Exception e) {
e.printStackTrace();
}
}
I need to share the image from "raw" folder in the resources and share it without background. What should I do?
I found the problem, It is telegram itself. Telegram adds a black background to .png images you share.
Try this ..its work for me to share image from drawable folder.
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/LatestShare.png";
OutputStream out = null;
File file = new File(path);
try {
out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
path = file.getPath();
Uri bmpUri = Uri.parse("file://" + path);
Intent shareIntent = new Intent();
shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
shareIntent.setType("image/png");
startActivity(Intent.createChooser(shareIntent, "Share with"));
I am writing an app to share image.
I wrote the code but getting problems.
What I am doing
1: Saving the image temporarily in Internal Stoarge
2: Passing the URI to share the image.
Image is successfully saved in internal storage but not getting share on whatsapp.
When I share it on whatsapp, Whatsapp get opens, I select recipient, whatsapp processes it and says "Retry".
Code:
public void shareImage(View V)
{
Bitmap icon = BitmapFactory.decodeResource(getResources(), R.drawable.download);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
icon.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator + "myDownloadedImage.jpg");
try
{
file.createNewFile();
FileOutputStream fo = new FileOutputStream(file);
fo.write(bytes.toByteArray());
fo.close();
} catch (IOException e) {
Toast.makeText(this, "Some error in Writing"+e.getMessage(), Toast.LENGTH_LONG).show();
e.printStackTrace();
}
Uri downloadLocation=Uri.fromFile(file);
share.putExtra(Intent.EXTRA_STREAM, downloadLocation);
startActivity(Intent.createChooser(share, "Share Image"));
}
Image succesfully get saved on internal storage but not getting shared on whatsapp.
The screenshot is below. We can see images are not shared successfully.
Use below code to fetch image and make uri:
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), "share_image_" + System.currentTimeMillis() + ".png");
file.getParentFile().mkdirs();
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
bmpUri = Uri.fromFile(file);
Now pass the bmpUri in:
shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
This should make your image share.
I've used the following code to save an image file to the external storage
drawView.setDrawingCacheEnabled(true);
String img = MediaStore.Images.Media.insertImage(getContentResolver(),drawView.getDrawingCache(),UUID.randomUUID().toString()+".jpeg", "doodle");
I want to return this saved file to Whatsapp using an intent. Can somebody please help me out with the code? I'm new to android and would really appreciate it! Thanks :)
Try this code
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"));