Search code examples
javaandroidsnapshot

How to take snapshot of screen not only app in Android with code


I've developed app that takes screenshot. But it only takes snapshot of app. I want to take snapshot out of app. I've researched answers but I don't find answer yet. Here is my code.

View view = getWindow().getDecorView().getRootView();
view.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
view.setDrawingCacheEnabled(false);
saveImageToAppFolder(bitmap);

saveImagetoAppFolder is function that saves image to app folder. That's not problem. Is there anyway to take snapshot of screen?


Solution

  • To take screen shot of the device screen, Only if you have root call the screencap binary like:

    Process sh = Runtime.getRuntime().exec("su", null,null);
    OutputStream  os = sh.getOutputStream();
    os.write(("/system/bin/screencap -p " + Environment.getExternalStorageDirectory()+ "/img.png").getBytes("ASCII"));
    os.flush();
    os.close();
    sh.waitFor()
    

    And to load that file into a bitmap,Use

    public static Bitmap decodeSampledBitmapFromFile(String path,
                                                         int reqWidth, int reqHeight) {
    
            // First decode with inJustDecodeBounds=true to check dimensions
            final BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(path, options);
    
            // Calculate inSampleSize
            options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
    
            // Decode bitmap with inSampleSize set
            options.inJustDecodeBounds = false;
            return BitmapFactory.decodeFile(path, options);
        }
    
        public static int calculateInSampleSize(
                BitmapFactory.Options options, int reqWidth, int reqHeight) {
            // Raw height and width of image
            final int height = options.outHeight;
            final int width = options.outWidth;
            int inSampleSize = 1;
    
            if (height > reqHeight || width > reqWidth) {
    
                final int halfHeight = height / 2;
                final int halfWidth = width / 2;
    
                // Calculate the largest inSampleSize value that is a power of 2 and keeps both
                // height and width larger than the requested height and width.
                while ((halfHeight / inSampleSize) > reqHeight
                        && (halfWidth / inSampleSize) > reqWidth) {
                    inSampleSize *= 2;
                }
            }
    
            return inSampleSize;
        }