I'm getting an error while sending a screenshot - java

As soon as the user clicks the button, I ask him to take a screenshot and send it to another friend.
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
View rootView = getWindow().getDecorView().findViewById(android.R.id.content);
Bitmap bitmap = getScreenShot(rootView);
File file = store(bitmap,"File-Name");
shareImage(file);
}
});
public static Bitmap getScreenShot(View view) {
View screenView = view.getRootView();
screenView.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(screenView.getDrawingCache());
screenView.setDrawingCacheEnabled(false);
return bitmap;
}
public static File store(Bitmap bm, String fileName){
final String dirPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Screenshots";
File dir = new File(dirPath);
if(!dir.exists())
dir.mkdirs();
File file = new File(dirPath, fileName);
try {
FileOutputStream fOut = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();
} catch (Exception e) {
e.printStackTrace();
}
return file;
}
private void shareImage(File file){
Uri uri = Uri.fromFile(file);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.setType("image/*");
intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "");
intent.putExtra(android.content.Intent.EXTRA_TEXT, "");
intent.putExtra(Intent.EXTRA_STREAM, uri);
try {
startActivity(Intent.createChooser(intent, "Share Screenshot"));
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "No App Available", Toast.LENGTH_SHORT).show();
}
}
I see that the bitmap value is "" when I debug. I also have these in my error message.
Error Log Image
I used them in my manifest file.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_path" />
</provider>
Could you please help me?

You should use this code
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
View rootView = getWindow().getDecorView().findViewById(android.R.id.content);
Bitmap bitmap = getScreenShot(rootView);
File file = store(bitmap, "name.png");
if (file.exists()) {
shareImage(file);
} else {
Log.e("file exist", "NO");
}
}
});
public static Bitmap getScreenShot(View view) {
View screenView = view.getRootView();
screenView.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(screenView.getDrawingCache());
screenView.setDrawingCacheEnabled(false);
return bitmap;
}
public File store(Bitmap bm, String fileName) {
final String dirPath = getExternalCacheDir().getAbsolutePath() + "/Screenshots";
File dir = new File(dirPath);
if (!dir.exists())
dir.mkdirs();
File file = new File(dirPath, fileName);
try {
FileOutputStream fOut = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();
} catch (Exception e) {
e.printStackTrace();
}
return file;
}
private void shareImage(File file) {
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(file.getPath()));
shareIntent.setType("image/*");
startActivity(Intent.createChooser(shareIntent, "Share Screenshot"));
}

Use this to capture a bitmap from a view. Your method will not work anymore using the drawing cache.
public drawBitmap(View view, int width, int height) {
Bitmap bm = Bitmap.createBitmap(width,
height,
Bitmap.Config.ARGB_8888)
Canvas canvas = Canvas(bm)
canvas.drawColor(previewBgColor)
view.draw(canvas)
// Store bitmap in dest file,
File dstFile = File("path/to/file")
storeBitmap(dstFile, bm)
}
public String storeBitmap(File file, Bitmap bmp) {
FileOutputStream stream;
try {
stream = FileOutputStream(file, false)
bmp.compress(Bitmap.CompressFormat.JPEG,99,it)
} catch (e: Exception) {
} finally {
stream.close()
}
return file.path
}
If the file exception persists let us know. I am assuming it's giving that error because the bitmap file returns ""? The docs here should be enough to get you through.

I was able to solve the problem with such a structure. Thank you very much to P Fuster for all his help.
We add these permissions first to the manifests file.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
then we add them to the onCreate method in mainActivity.
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
Now let's give the click effect of our button.
share_friends.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
View rootView = getWindow().getDecorView().findViewById(android.R.id.content);
Bitmap bitmap = getScreenShot(rootView);
File file = store(bitmap, "name.png");
if (file.exists()) {
shareImage(file);
System.out.println(file.getPath());
} else {
Log.e("file exist", "NO");
}
}
});
Functions used in the button
public static Bitmap getScreenShot(View view) {
View screenView = view.getRootView();
screenView.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(screenView.getDrawingCache());
screenView.setDrawingCacheEnabled(false);
return bitmap;
}
public File store(Bitmap bm, String fileName) {
final String dirPath = Environment.getExternalStorageDirectory().getPath() + "/Screenshots";
File dir = new File(dirPath);
if (!dir.exists())
dir.mkdirs();
File file = new File(dirPath, fileName);
try {
FileOutputStream fOut = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();
} catch (Exception e) {
e.printStackTrace();
}
return file;
}
private void shareImage(File file) {
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setType("image/*");
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
shareIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(shareIntent, "Share Screenshot"));
}
the problem was solved like this.

Related

Error when saving relative layout as bitmap using layout.getDrawingCache() returning null

How to handle full-sized photo using MediaStore.EXTRA_OUTPUT? First, I need to put the picture AS FULL-SIZED NOT THUMBNAIL on a layout and put text below it like this:
The idea I am using is that I am using layout.getDrawingCache to make it as bitmap.
Below is my camera button:
private void SelectImage(){
final CharSequence[] items={"Camera", "Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(PickupDrop.this);
builder.setTitle("Add Image");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if (items[i].equals("Camera")) {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if(cameraIntent.resolveActivity(getPackageManager())!= null){
File imageFile = null;
try {
imageFile = getImageFile();
} catch (Exception e) {
e.printStackTrace();
}
if(imageFile!= null){
imageUri =FileProvider.getUriForFile(context, "com.example.android.fileprovider", imageFile);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
cameraIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivityForResult(cameraIntent,REQUEST_CAMERA);
}
}
} else if (items[i].equals("Cancel")) {
dialogInterface.dismiss();
}
}
});
builder.show();
}
The getImageFile() method:
private File getImageFile(){
String imageName = "test";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File imageFile = null;
try {
imageFile = File.createTempFile(imageName,".jpg",storageDir);
} catch (IOException e) {
e.printStackTrace();
}
currentImagePath = imageFile.getAbsolutePath();
return imageFile;
}
As you can see above, I am using EXTRA_OUTPUT with fileprovider to get FULL-SIZED bitmap.
Below is my manifests, provider.
Manifest:
<application ...
<provider
android:authorities="com.example.android.fileprovider"
android:name="androidx.core.content.FileProvider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_path"/>
</provider>
file_path.xml:
<?xml version="1.0" encoding="utf-8"?>
<external-path
name="my images"
path="Android/data/com.example.luckypasabayapp/files/Pictures"/>
My onActivityResult method:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode,data);
if(resultCode== Activity.RESULT_OK){
if(requestCode==REQUEST_CAMERA){
Bitmap bitmap = BitmapFactory.decodeFile(currentImagePath);
populateScreenshot(bitmap);
}
}
}
Now here is where my problem occurs when I try to save the relative layout screenshot to my storage:
public void populateScreenshot(Bitmap bitmapFromPhone){
LayoutInflater inflater = LayoutInflater.from(PickupDrop.this);
View v = inflater.inflate(R.layout.information_dialog, null);
ImageView imageView_profilePic = v.findViewById(R.id.imageview_image);
TextView txt_item_data = v.findViewById(R.id.txt_item_data);
Button btn_cancel = v.findViewById(R.id.btn_cancel);
Button btn_download = v.findViewById(R.id.btn_download);
screenShot = v.findViewById(R.id.screenShot);
screenShot.setDrawingCacheEnabled(true);
screenShot.buildDrawingCache();
final AlertDialog alertDialog = new AlertDialog.Builder(PickupDrop.this)
.setView(v)
.create();
alertDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
#Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
// Prevent dialog close on back press button
return keyCode == KeyEvent.KEYCODE_BACK;
}
});
//alertDialog.setCanceledOnTouchOutside(false);
//SETTING THE IMAGEVIEW OF LAYOUT TAKEN FROM CAMERA
imageView_profilePic.setImageBitmap(bitmapFromPhone);
btn_download.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//GETTING THE RELATIVELAYOUT AS BITMAP
Bitmap bitmap = screenShot.getDrawingCache();
File filePath = Environment.getExternalStorageDirectory();
File dir = new File(filePath.getAbsolutePath()+"/qrcode/");
dir.mkdirs();
File file = new File(dir, "str_specialNumber" + ".png");
try {
outputStream = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//HERE IS WHERE THE ERROR OCCURS, IT SAYS BITMAP IS NULL!!!
bitmap.setHasAlpha(true);
bitmap.compress(Bitmap.CompressFormat.PNG, 100,outputStream);
Toast.makeText(PickupDrop.this,"SCREENSHOT Downloaded",Toast.LENGTH_LONG).show();
try {
outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
//notify gallery for a new picture
galleryAddPic(filePath.getAbsolutePath()+"/qrcode/"+"str_specialNumber"+".png");
}
});
alertDialog.show();
}
Here in bitmap.setHasAlpha(true); it says bitmap is null from screenshot.getDrawingCache I don't understand why.
How do I handle the EXTRA_OUTPUT properly to be able to do whatever I want with the bitmap?
You can give this answer a try :)
If you want to take the screenshot of any view or your RelativeLayout you can create this method takeScreenShot() : it will return a Bitmap
in #Param or parameter in this method, you can pass RelativeLayout
public static Bitmap takeScreenShot(#NonNull View view) {
view.setDrawingCacheEnabled(true);
view.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_AUTO);
view.buildDrawingCache();
if (view.getDrawingCache() == null) return null;
Bitmap snapshot;
try {
snapshot = Bitmap.createBitmap(view.getDrawingCache());
view.setDrawingCacheEnabled(false);
view.destroyDrawingCache();
} catch (Exception e) {
snapshot = null;
}
return snapshot;
}
tell me if this helps you :)

When sharing an image with Intent, it gives an error when converting from byte[] to Uri

I have an application that uses API. I'm using the code below to share the image I got from the API.
byte[] byte;
final Bitmap[] bitmap = new Bitmap[1];
Glide.with(FilmActivity.this)
.asBitmap()
.load(imageLink)
.into(new CustomTarget<Bitmap>() {
#Override
public void onResourceReady(#NonNull Bitmap resource, #Nullable Transition<? super Bitmap> transition) {
bitmap[0] = resource;
byte = getBytes(bitmap[0]);
}
#Override
public void onLoadCleared(#Nullable Drawable placeholder) {
}
});
private byte[] getBytes(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 0, stream);
return stream.toByteArray();
}
I am using the following code to share byte[] type data.
try {
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, name);
String s = new String(byte, "UTF-8");
Uri uri = Uri.parse(s);
sendIntent.putExtra(Intent.EXTRA_STREAM, uri);
sendIntent.setType("image/*");
sendIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(sendIntent, "Share"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
But it doesn't work. I get the following error.
java.lang.RuntimeException: Failure from system
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1677)
at android.app.Activity.startActivityForResult(Activity.java:4586)
at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:676)
at android.app.Activity.startActivityForResult(Activity.java:4544)
at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:663)
at android.app.Activity.startActivity(Activity.java:4905)
at android.app.Activity.startActivity(Activity.java:4873)
at com.example.filmler.activity.FilmActivity$4.onClick(FilmActivity.java:205)
Why are converting it to byte and sharing?
Why do you want to convert it? You can just save the bitmap like this:
String location = MediaStore.Images.Media.insertImage(getContentResolver(), bitmap,new Random().nextInt(), null);
And then you can pass it to the intent like this:
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(location));
Edit
If you do not want to save it on the device, you can do it this way.
Save the bitmap to cache.
File cacheDir = getBaseContext().getCacheDir();
File f = new File(cacheDir, "pic");
try {
FileOutputStream out = new FileOutputStream(
f);
pic.compress(
Bitmap.CompressFormat.JPEG,
100, out);
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Get the image and share it.
File cacheDir = getBaseContext().getCacheDir();
File f = new File(cacheDir, "pic");
Add it to intent
Uri uri = fromFile(f);
sendIntent.putExtra(Intent.EXTRA_STREAM, uri);

Get imageview from Adapter in Fragment

I have Image view list in adapter on click of image I show full screen image. Where I have one button outside of adapter in fragment.
Now I want to get that image in fragment onClick of button to share that image.
Below code this in adapter where my images are getting download.
I have using Android-Universal-Image-Loader library to show images.
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if(callback != null) {
Bitmap bitmap = ((BitmapDrawable) img_main_bg.getDrawable()).getBitmap();
callback.onItemClicked(bitmap);
}
spinner.setVisibility(View.GONE);
}
How do I get image in fragment?
I already tried interface but onLoadingComplete downloading multiple image at time so I can't get right image on that.
you can do it following way
first make click listener in that ask for permission to save image
imageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
imgView = imageView;
boolean hasPermission = (ContextCompat.checkSelfPermission(ImagePagerActivity.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED);
if (!hasPermission) {
ActivityCompat.requestPermissions(ImagePagerActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
112);
}else
{
showDialog();
}
}
});
if permission is applied then save image first then share it
private void showDialog()
{
new AlertDialog.Builder(ImagePagerActivity.this,R.style.MyAlertDialogStyle)
.setTitle("Select your option")
.setPositiveButton("Save",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
imgView.buildDrawingCache();
Bitmap bm = imgView
.getDrawingCache();
OutputStream fOut = null;
try {
File root = new File(
Environment
.getExternalStorageDirectory()
+ File.separator
+ "Beauty"
+ File.separator);
if (!root.exists())
root.mkdirs();
File sdImageMainDirectory = new File(
root,
System.currentTimeMillis()
+ ".jpg");
fOut = new FileOutputStream(
sdImageMainDirectory);
bm.compress(
Bitmap.CompressFormat.PNG,
100, fOut);
fOut.flush();
fOut.close();
Toast.makeText(
ImagePagerActivity.this,
"File saved at Beauty folder",
Toast.LENGTH_SHORT)
.show();
} catch (Exception e) {
Toast.makeText(
ImagePagerActivity.this,
"Error occured. Please try again later.",
Toast.LENGTH_SHORT)
.show();
e.printStackTrace();
}
}
})
.setNegativeButton("Share",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
try {
imgView.buildDrawingCache();
Bitmap bm = imgView
.getDrawingCache();
OutputStream fOut = null;
File root = new File(
Environment
.getExternalStorageDirectory()
+ File.separator
+ " Beauty"
+ File.separator);
if (!root.exists())
root.mkdirs();
File sdImageMainDirectory = new File(
root, "1.jpg");
fOut = new FileOutputStream(
sdImageMainDirectory);
bm.compress(
Bitmap.CompressFormat.PNG,
100, fOut);
fOut.flush();
fOut.close();
Intent shareIntent = new Intent(
Intent.ACTION_SEND);
Uri phototUri = Uri
.fromFile(sdImageMainDirectory);
shareIntent.setData(phototUri);
shareIntent
.setType("image/png");
shareIntent.putExtra(
Intent.EXTRA_STREAM,
phototUri);
startActivityForResult(Intent
.createChooser(
shareIntent,
"share using"),
2);
} catch (Exception ce) {
ce.printStackTrace();
}
}
})
.show();
}

share audio on Android studio

Don't share mp3 audio in my app (in raw/suono.mp3) on whatapp app
final Button pulsante2 =(Button) findViewById(R.id.pulsante2);
pulsante2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
suono2=MediaPlayer.create(getApplicationContext(),R.raw.suono2);
suono2.start();
}
});
//tasto premuto piu a lungo
pulsante2.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("audio/*");
Uri uri = Uri.parse("android.resource://" + getPackageName()
+ "/raw/" + R.raw.suono2);
share.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(share, "Share Sound File"));
return true;
}
});
what app say me can't load file please reload
InputStream inputStream;
FileOutputStream fileOutputStream;
try {
inputStream = getResources().openRawResource(R.raw.suono2);
fileOutputStream = new FileOutputStream(
new File(Environment.getExternalStorageDirectory(), "sound.mp3"));
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
fileOutputStream.write(buffer, 0, length);
}
inputStream.close();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}

How can I take a screenshot of my screen and save it on Internal Storage? Android

I am implementing a button which lets you take a screenshot, but I want to save it on the Android Internal Storage not in the External Storage (SD Card).
I tried this:
private String saveToInternalStorage(Bitmap bitmapImage){
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to /data/data/yourapp/app_data/imageDir
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
// Create imageDir
File mypath=new File(directory,"profile.jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
// Use the compress method on the BitMap object to write image to the OutputStream
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (Exception e) {
e.printStackTrace();
} finally {
fos.close();
}
return directory.getAbsolutePath();
}
I've started this method with an OnClick method of a button:
private void takeScreenshot(View v) {
v = getWindow().getDecorView().getRootView();
v.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v.getDrawingCache());
v.setDrawingCacheEnabled(false);
saveToInternalStorage(bitmap)
}
But this didn't work. Instead, when I click the button, an error message appears on my cell phone: "Application has stopped".
Hope you can help me.
I think you need to use openFileOutput to get a FileOutputStream, try following the example in the doc https://developer.android.com/training/basics/data-storage/files.html
What's the error in the logcat?
/**
* This function captures any Android views to a bitmap shapshot
* and save it to a file path
* and optionally open it with android pciture viewer
*/
public void CaptureView(View view, String filePath, boolean bOpen) {
view.setDrawingCacheEnabled(true);
Bitmap b = view.getDrawingCache();
try {
b.compress(CompressFormat.JPEG, 95, new FileOutputStream(filePath));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (bOpen) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" + filePath), "image/*");
startActivity(intent);
}
}
Usage:
File sdcard = Environment.getExternalStorageDirectory();
String path = sdcard + "/demo.jpg";
CaptureView(someViewInstace, path, false);
You can use Context.getFilesDir() method to get the path to the internal storage:
String path = yourActivity.getFilesDir() + "/" + name);
Add permission in manifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
add this line manifest file application tag
android:requestLegacyExternalStorage="true"
In activity
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int permission = ActivityCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(
MainActivity.this,
PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE);
} else {
takeScreenshot();
}
}
});
}
private void takeScreenshot() {
Date now = new Date();
android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);
try {
// image naming and path to include sd card appending name you choose for file
String mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg";
// create bitmap screen capture
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
File imageFile = new File(mPath);
FileOutputStream outputStream = new FileOutputStream(imageFile);
int quality = 100;
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
outputStream.flush();
outputStream.close();
Toast.makeText(MainActivity.this, "Successfully saved", Toast.LENGTH_SHORT).show();
//**if you want to open this screenshot
openScreenshot(imageFile);
} catch (Throwable e) {
e.printStackTrace();
}
}
private void openScreenshot(File imageFile) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(imageFile);
intent.setDataAndType(uri, "image/*");
startActivity(intent);
}
}

Categories