Skip to content

Instantly share code, notes, and snippets.

@sagar2093
Last active May 30, 2017 05:17
Show Gist options
  • Save sagar2093/261a6e692a2a1fee2fca266291d0f737 to your computer and use it in GitHub Desktop.
Save sagar2093/261a6e692a2a1fee2fca266291d0f737 to your computer and use it in GitHub Desktop.
Taking screenshot programmatically in android
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();//inside acitivity
//View v1 = getActivity().getWindow().getDecorView().getRootView(); //inside fragment
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();
openScreenshot(imageFile);
} catch (Throwable e) {
// Several error may come out with file handling or OOM
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);
}
https://stackoverflow.com/questions/2661536/how-to-programmatically-take-a-screenshot-in-android?rq=1
http://www.viralandroid.com/2016/01/how-to-take-screenshot-programmatically-in-android.html
https://stackoverflow.com/questions/20136121/android-how-to-take-screenshot-programatically
https://stackoverflow.com/questions/30196965/how-to-take-a-screenshot-of-current-activity-and-then-share-it
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment