StackTips

How to Programmatically Take a Screenshot in Android?

stacktips avtar

Written by

Editorial,  2 min read,  2.82K views, updated on Sept. 17, 2023

The following code snippet will help you to take a screenshot programmatically in Android. First you need to add the write file permission to save the captured screenshot.

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Add the following Java code to capture the screenshot of running in an Activity.

private void captureScreenshot() {
    try {
        // image saving sd card path
        String mPath = Environment.getExternalStorageDirectory().toString() + "/" + System.currentTimeMillis() + ".jpg";

        // create bitmap screen capture
        View view = getWindow().getDecorView().getRootView();
        view.setDrawingCacheEnabled(true);
		
        Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
        view.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();
		
    } catch (Throwable e) {
        e.printStackTrace();
    }
}