How to share screenshot of activity? - java

I tried a code to take screenshot of an Activity then share it , which is works very well but just in Android lower than 6.0 , from 6.0 and higher when i click share button then choose social network a short dialog tell me " unable to load image "
Please i need your help my friends
This the code that i used it :
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bitmap bitmap = takeScreenshot();
saveBitmap(bitmap);
shareIt();
}
public Bitmap takeScreenshot() {
View rootView = findViewById(android.R.id.content).getRootView();
rootView.setDrawingCacheEnabled(true);
return rootView.getDrawingCache();
}
public void saveBitmap(Bitmap bitmap) {
imagePath = new File(Environment.getExternalStorageDirectory() + "/screenshot.png");
FileOutputStream fos;
try {
fos = new FileOutputStream(imagePath);
bitmap.compress(Bitmap.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);
}
}
private void shareIt() {
Uri uri = Uri.fromFile(imagePath);
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("image/*");
String shareBody = "In Tweecher, My highest score with screen shot";
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "My Tweecher score");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
sharingIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(sharingIntent, "Share via"));
}
});
displayResults();
}
EDIT :
I try to replace Uri uri = Uri.fromFile(imagePath); by Uri uri = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".my.package.name.provider", imagePath);
But it says app was stopped when i click Share button
Any help pleaaaase

If FileUriExposedException is the exception that is the cause for the issue:-
This exception is thrown when an application exposes a file:// Uri to another app.
This is only thrown for applications targeting Build.VERSION_CODES.N or higher. Applications targeting earlier SDK versions are allowed to share file:// Uri, but it's strongly discouraged.
These links might give a detailed answer to the above problem:-
https://developer.android.com/reference/android/os/FileUriExposedException
android.os.FileUriExposedException: file:///storage/emulated/0/test.txt exposed beyond app through Intent.getData()
Hope this helps.

Related

How to send image from app via messenger?

I want to send image from my app via messenger. I was looking on Stack Overflow and I found answer which works for WhatsApp. When I tried to change "com.whatsapp" to "com.facebook.orca", it stops working. Here is my code:
public void shareImageMessenger() {
Bitmap adv = BitmapFactory.decodeResource(getResources(), R.drawable.koza);
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_1.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_1.jpg"));
share.setPackage("com.facebook.orca");
startActivity(Intent.createChooser(share, "Share Image"));
}
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("");

Send MMS with Bitmap from code

I would like to send a Bitmap and some text by clicking on a button in a fragment and I would like to let the user choose the contact/number in his messaging app.
How I could do that ?
EDIT :
After trying something, I got an error in the message app (Messenger on the emulator) :
Messenger failed to load attachment.
Here is the code I used :
String path = Environment.getExternalStorageDirectory().getPath() + "/Improov/LatestShare.png";
File file = new File(path);
FileOutputStream out = null;
try {
out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
Uri photoURI = FileProvider.getUriForFile(getContext(), getContext().getApplicationContext().getPackageName() + ".com.example.mous.improov_flash", file);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra("sms_body", message);
intent.putExtra(Intent.EXTRA_STREAM, photoURI);
intent.setType("image/jpeg");
getActivity().startActivity(intent);
If you like to send MMS,
First, you should store your bitmap in sd card, then use the following intent to send the MMS,
Get the Uri for your stored bitmap
Uri uri = [uri for your stored bitmap];
Intent intent = new Intent(Intent.ACTION_SEND);
inetnt.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.putExtra("sms_body", [Text to be send]);
intent.putExtra(Intent.EXTRA_STREAM, uri);
intent.setType("image/jpeg");
getActivity.startActivity(intent);
For more detail read this official doc

Share screen shoot android studio(multi-times)

I have app and i am letting user to make screenshot and share it, all working fine just one problem..
When user for example make screenshot and press on Facebook icon > then he press cancel sharing ,next time when he want to do another share he will see the old screen shoot , how can make it take the last screenshot always??
** i have each image has different file name but the share always taking the last action that didn't finish.
(if user do share all will work fine ,next screen shoot will be the new one )
here is my code
public Bitmap takeScreenshot() {
View rootView = findViewById(android.R.id.content).getRootView();
rootView.setDrawingCacheEnabled(true);
return rootView.getDrawingCache();
}
public void saveBitmap(Bitmap bitmap) {
imagePath = new File(Environment.getExternalStorageDirectory() ,
"SCREEN"
+ System.currentTimeMillis() + ".png");
FileOutputStream fos;
try {
fos = new FileOutputStream(imagePath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (IOException e) {
Log.e("GREC", e.getMessage(), e);
}
}
private void shareIt() {
uri =Uri.fromFile(imagePath);
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("image/*");
String shareBody = "جرب تطبيق نكت عراقية مضحكة الان!";
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "تطبيق نكت
عراقية مضحكة");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
sharingIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(sharingIntent, "مشاركة بواسطة"));
}
You can do something like this.Remove the System.currentTimeMillis() from the name of your image so, that you do not have multiple copies of screenshots.So when you upload the image it always have the fresh screenshots.Now when you capture another screenshot you have to check is file exist if exist then delete it.
public void saveBitmap(Bitmap bitmap)
{
File file = new File(Environment.getExternalStorageDirectory(), "SCREEN.png");
if (file.exists()) {
file.delete();
}
imagePath = new File(Environment.getExternalStorageDirectory() , "SCREEN.png");
FileOutputStream fos;
try
{
fos = new FileOutputStream(imagePath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
}
catch (IOException e)
{
Log.e("GREC", e.getMessage(), e);
}
}

Share intent takes long time to appear

I'm trying to include image sharing in my application and everything is working but the share chooser takes long time to appear on devices
here is what i'm doing:
I have ImageView "items_details_image" and I want to share its image to be able to send it through whatsapp and other apps
void ShareImg() {
try {
Uri bmpUri = getLocalBitmapUri(items_details_image);
if (bmpUri != null) {
// Construct a ShareIntent with link to image
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
shareIntent.setType("image/*");
// Launch sharing dialog for image
startActivity(Intent.createChooser(shareIntent, "Share Image"));
} else {
// ...sharing failed, handle error
}
} catch (Exception e) {
}
}
here is how I get bitmap from Image URL
public Uri getLocalBitmapUri(ImageView imageView) {
// Extract Bitmap from ImageView drawable
Drawable drawable = imageView.getDrawable();
Bitmap bmp = null;
if (drawable instanceof BitmapDrawable){
bmp = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
} else {
return null;
}
// Store image to default external storage directory
Uri bmpUri = null;
try {
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), "share_image_" + System.currentTimeMillis() + ".png");
file.getParentFile().mkdirs();
FileOutputStream out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
bmpUri = Uri.fromFile(file);
} catch (IOException e) {
e.printStackTrace();
}
return bmpUri;
}
I don't know why it is taking longer than usual comparing it with other apps on the same device such as gallery or whatever
You are doing disk I/O on the main application thread, in getLocalBitmapUri(). This will freeze your UI as long as it takes to write your bitmap to disk.

Error when trying to share an image

So I take a screenshot of my activity, then save it to "screenshot.png". When trying to share it via, let's say, Whatsapp, I get an error: "could not send image". Same with gmail, pushbullet and basically all other apps. Therefore, I conclude that the file somehow exists, but it is either empty, or messed up... I don't know, honestly.
Here's the code:
Taking the activity screenshot:
public Bitmap takeScreenshot() {
View rootView = findViewById(android.R.id.content).getRootView();
rootView.setDrawingCacheEnabled(true);
return rootView.getDrawingCache();
}
Saving the screenshot:
public void saveBitmap(Bitmap bitmap) {
FileOutputStream fos;
String filePath = getApplicationContext().getFilesDir().getPath().toString() + "/screenshot.png";
File f = new File(filePath);
try {
fos = new FileOutputStream(f);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
Log.e("GREC", e.getMessage(), e);
} catch (IOException e) {
Log.e("GREC", e.getMessage(), e);
}
}
And finally, the sharing itself:
if (id == R.id.action_share){
Bitmap bitmap = takeScreenshot();
saveBitmap(bitmap);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/png");
share.putExtra(Intent.EXTRA_STREAM, Uri.parse("screenshot.png"));
startActivity(Intent.createChooser(share, "Teilen via"));
}
Where is my error? I don't get any errors in logcat, but I am unable to share the "screenshot".
Firstly, you should use :
share.putExtra(Intent.EXTRA_STREAM. Uri.fromFile(new File(getApplicationContext().getFilesDir().getPath().toString() + "/screenshot.png"));
But you would then get "Permission denied for the attachment" and you possibly would try but with no luck :(
share.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
So probably the best way to deal with this issue is to store the captured screenshot in media library and send the file from there.
public void share() {
String filePath=getApplicationContext().getFilesDir().getPath().toString() + "/screenshot.png";
String path;
try {
path = Images.Media.insertImage(getContentResolver(), filePath, "title", null);
Uri screenshotUri = Uri.parse(path);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/png");
share.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
share.putExtra(Intent.EXTRA_STREAM, screenshotUri);
startActivity(Intent.createChooser(share, "Teilen via"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Hope it would help!

Categories