Android 截屏——调用adb命令&系统API

时间:2022-06-07 15:30:05


方法一:

 

在APK中调用“adb shellscreencap -pfilepath” 命令

该命令读取系统的framebuffer,需要获得系统权限:

 

(1).在AndroidManifest.xml文件中添加

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

(2).修改APK为系统权限,将APK放到源码中编译, 修改Android.mk

LOCAL_CERTIFICATE:= platform

public void takeScreenShot(){ 
String mSavedPath = Environment.getExternalStorageDirectory() + File.separator + "screenshot.png" ;
try {
Runtime. getRuntime().exec("screencap -p " + mSavedPath);
} catch (Exception e) {
e.printStackTrace();
}

方法二:

 

利用系统的API,实现Screenshot,这部分代码是系统隐藏的,需要在源码下编译,


(1).在AndroidManifest.xml文件中添加

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

(2).修改APK为系统权限,将APK放到源码中编译, 修改Android.mk

LOCAL_CERTIFICATE:= platform

public boolean takeScreenShot(String imagePath){                     
if(imagePath.equals("" )){
imagePath = Environment.getExternalStorageDirectory() + File.separator+"Screenshot.png";
}
Bitmap mScreenBitmap;
WindowManager mWindowManager;
DisplayMetrics mDisplayMetrics;
Display mDisplay;
                  
mWindowManager = (WindowManager) mcontext.getSystemService(Context.WINDOW_SERVICE);
mDisplay = mWindowManager.getDefaultDisplay();
mDisplayMetrics = new DisplayMetrics();
mDisplay.getRealMetrics(mDisplayMetrics);
                                 
float[] dims = {mDisplayMetrics.widthPixels , mDisplayMetrics.heightPixels };
mScreenBitmap = Surface. screenshot((int) dims[0], ( int) dims[1]);
                     
if (mScreenBitmap == null) {  
return false ;
}
try {
FileOutputStream out = new FileOutputStream(imagePath);
mScreenBitmap.compress(Bitmap.CompressFormat. PNG, 100, out);
} catch (Exception e) {
return false ;
}       
return true ;
}