Skip to content

Instantly share code, notes, and snippets.

@bulentsiyah
Last active May 17, 2018 08:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bulentsiyah/beac9bcad49c45177a9769f607c04f13 to your computer and use it in GitHub Desktop.
Save bulentsiyah/beac9bcad49c45177a9769f607c04f13 to your computer and use it in GitHub Desktop.
How to programmatically take a screenshot in Android? -- http://www.bulentsiyah.com/how-to-programmatically-take-a-screenshot-in-android/
How to programmatically take a screenshot in Android?
Reference: http://stackoverflow.com/a/5651242
Here is the code that allowed my screenshot to be stored on sd card and used later for whatever your needs are:
First, add proper permission to save file:
And this is the code (running in an Activity):
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();
openScreenshot(imageFile);
} catch (Throwable e) {
// Several error may come out with file handling or OOM
e.printStackTrace();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment