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();
    }
}
Tagged in : #Android

Discussions

Please note: We reserve the right to delete comments that contains snarky remarks, offensive or off-topic. To know more read our comments policy.