To take a screenshot from an application, you can call the View’s getDrawingCache method, but this method does not have a status bar. You need to do this yourself.

There is also a way to call the system hidden screenshot method to take screenshots, this method is full screen screenshots. By calling the SurfaceControl. Screenshot ()/Surface. The screenshot screenshots (), use SurfaceControl in API Level is more than 17, 17 use less than or equal to the Surface, But the screenshot method is hidden, so use reflection to call that method. The parameters that this method needs to pass in are width and height, so you need to get the width and height of the entire screen. Three methods are commonly used.

Gets the screen width and height

Methods a

int screenWidth = getWindowManager().getDefaultDisplay().getWidth();
int screenHeight = getWindowManager().getDefaultDisplay().getHeight();

Copy the code

This method will indicate that it is outdated. The latter two methods are recommended.

Method 2

DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int screenWidth = dm.widthPixels;
int screenHeight = dm.heightPixels;

Copy the code

Methods three

Resources resources = this.getResources();
DisplayMetrics dm = resources.getDisplayMetrics();
int screenWidth = dm.widthPixels;
int screenHeight = dm.heightPixels;

Copy the code

Reflection calls the screenshot method

public Bitmap screenshot(a) {
    Resources resources = this.getResources();
    DisplayMetrics dm = resources.getDisplayMetrics();

    String surfaceClassName = "";
    if (Build.VERSION.SDK_INT <= 17) {
        surfaceClassName = "android.view.Surface";
    } else {
        surfaceClassName = "android.view.SurfaceControl";
    }
	
    try{ Class<? > c = Class.forName(surfaceClassName); Method method = c.getMethod("screenshot".new Class[]{int.class, int.class});
        method.setAccessible(true);
        return (Bitmap) method.invoke(null, dm.widthPixels, dm.heightPixels);
    } catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException | ClassNotFoundException e) {
        e.printStackTrace();
    }
    return null;
}

Copy the code

The final Bitmap object returned is the captured image.

Required permissions

<uses-permission android:name="android.permission.READ_FRAME_BUFFER"/>
Copy the code

Calling the screenshot method requires system permissions, so applications that do not have system signatures will report errors.