If you want to take screenshots in the application, you can directly call the getDrawingCache method of View, but if you take screenshots, you have to implement them yourself.
There is also a method that can call the hidden screenshot method of the system to take screenshot. This method screenshot is a whole screen.
By calling () / () screenshot, use SurfaceControl in API Level greater than 17, and use Surface less than or equal to 17, but the screenshot method is hidden, so you need to call this method with reflection.
The parameters that this method needs to pass in are width and height, so you need to obtain the width and height of the entire screen. There are three commonly used methods.
Get screen width and height
Method 1
int screenWidth = getWindowManager().getDefaultDisplay().getWidth(); int screenHeight = getWindowManager().getDefaultDisplay().getHeight();
This method will indicate that it is outdated, and the following two are recommended.
Method 2
DisplayMetrics dm = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm); int screenWidth = ; int screenHeight = ;
Method 3
Resources resources = (); DisplayMetrics dm = (); int screenWidth = ; int screenHeight = ;
Reflection call screenshot method
public Bitmap screenshot() { Resources resources = (); DisplayMetrics dm = (); String surfaceClassName = ""; if (.SDK_INT <= 17) { surfaceClassName = ""; } else { surfaceClassName = ""; } try { Class<?> c = (surfaceClassName); Method method = ("screenshot", new Class[]{, }); (true); return (Bitmap) (null, , ); } catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException | ClassNotFoundException e) { (); } return null; }
The last Bitmap object returned is to obtain the image.
Permissions required
<uses-permission android:name=".READ_FRAME_BUFFER"/>
Calling the screenshot method requires system permission, so an application that cannot be signed by the system will report an error.
This is the article about Android using reflection mechanism to call screenshot methods and obtain screen width and height. For more related contents of Android reflection calls screenshot methods, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!