Android三種方式截取任意界面屏幕

1、使用MediaProjectionManagerandroid

Android5.0以後,開放截取屏幕的API,也就是利用MediaProjectionManager建立VirtualDisplay,傳入與ImageReader關聯的Surface,這樣就能夠從ImageReader中獲取到Image,而後把Image的像素數組拷貝到Bitmap,若是要保存爲圖片,就用獲得的Bitmap壓縮爲JPEG格式的圖片。shell

首先是使用startActivityForResult發起錄屏的請求:數組

private void startScreenShot(){
    WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
    if (windowManager != null) {
        DisplayMetrics displayMetrics = new DisplayMetrics();
        windowManager.getDefaultDisplay().getMetrics(displayMetrics);
        width = displayMetrics.widthPixels;
        height = displayMetrics.heightPixels;
        dpi = displayMetrics.densityDpi;
    }

    mediaProjectionManager = (MediaProjectionManager) getSystemService(MEDIA_PROJECTION_SERVICE);
    if (mediaProjectionManager != null) {
        startActivityForResult(mediaProjectionManager.createScreenCaptureIntent(), 123);
    }
}
複製代碼

在獲得用戶受權錄屏後,在onActivityResult中獲取MediaProjection-->VirtualDisplay-->ImagReader-->Image-->Bitmap:架構

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    MediaProjection mediaProjection = mediaProjectionManager.getMediaProjection(resultCode, data);
    if (mediaProjection != null){
        getBitmap(mediaProjection);
    }
}private void getBitmap(MediaProjection mediaProjection){
    ImageReader imageReader = ImageReader.newInstance(width, height, PixelFormat.RGBA_8888, 3);
    mediaProjection.createVirtualDisplay("screen_shot",
            width, height, dpi, DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
            imageReader.getSurface(), null, null);
    imageReader.setOnImageAvailableListener(new ImageReader.OnImageAvailableListener() {
        @Override
        public void onImageAvailable(ImageReader reader) {
            Image image = reader.acquireNextImage();
            int width = image.getWidth();
            int height = image.getHeight();
            final Image.Plane[] planes = image.getPlanes();
            final ByteBuffer buffer = planes[0].getBuffer();
            int pixelStride = planes[0].getPixelStride();
            int rowStride = planes[0].getRowStride();
            int rowPadding = rowStride - pixelStride * width;
            Bitmap bitmap = Bitmap.createBitmap(width+rowPadding/pixelStride, height, Bitmap.Config.ARGB_8888);
            bitmap.copyPixelsFromBuffer(buffer);
            String filePath = Environment.getExternalStorageDirectory().getPath() + "/hello.jpg";
            //bitmap保存爲圖片
            saveBitmap(bitmap, filePath);
            image.close();
        }
    }, null);

}private void saveBitmap(Bitmap bitmap, String filePath){
    try {
        FileOutputStream outputStream = new FileOutputStream(filePath);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
        outputStream.flush();
        outputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
複製代碼

優勢:不用系統簽名,不依賴系統底層API;app

缺點:彈出確認框,須要用戶受權錄屏;框架

2、使用SurfaceControlide

從上面分析可知,MediaProjectionManager錄屏依賴Surface,分析Surface源碼後,發現Surface實際上是調用SurfaceControl,也就是說能夠用SurfaceControl走捷徑去截屏。其實系統框架層的截屏也是調用SurfaceControl。可是,因爲SurfaceControl屬於系統API,對用戶不開放,咱們沒法直接調用。說到這裏,你們應該都想到,用反射機制來調用。學習

正確的調用方式是這樣的:ui

Bitmap bitmap = SurfaceControl.screenshot(width, height); 經過系統源碼,能夠知道它在Android.view.SurfaceControl路徑下。既然路徑、類、方法、參數都知道了,反射就沒問題:spa

//使用反射調用截屏
private void screenShotByReflect(){
	DisplayMetrics mDisplayMetrics = new DisplayMetrics();
	float[] dims = { mDisplayMetrics.widthPixels,
			mDisplayMetrics.heightPixels };
	try {
		Class<?> demo = Class.forName("android.view.SurfaceControl");
		Method method = demo.getDeclaredMethod("screenshot", int.class,int.class);
		mScreenBitmap = (Bitmap) method.invoke(null,(int) dims[0],(int) dims[1]);
	} catch (Exception e) {
		e.printStackTrace();
	}
}
複製代碼

在調用截屏以前,判斷屏幕是否發生旋轉:

private Bitmap takeScreenshot() {
	 mDisplay.getRealMetrics(mDisplayMetrics);
	 float[] dims = {mDisplayMetrics.widthPixels, mDisplayMetrics.heightPixels};
	float degrees = getDegreesForRotation(mDisplay.getRotation());
	boolean requiresRotation = (degrees > 0);
	//若是屏幕發生旋轉,經過matrix旋轉回來
	if (requiresRotation) {
		mDisplayMatrix.reset();
		mDisplayMatrix.preRotate(-degrees);
		mDisplayMatrix.mapPoints(dims);
		dims[0] = Math.abs(dims[0]);
		dims[1] = Math.abs(dims[1]);
	}
	//調用截屏
	screenShotByReflect();
	return mScreenBitmap;
}
複製代碼

優勢:不用彈框受權,不用系統簽名;

缺點:使用反射機制,若是系統API或者方法發生更改,致使沒法調用;

3、使用screencap的adb命令

命令行是這樣的:adb shell screencap -p file_path

在代碼中執行,就不用adb shell,直接screencap -p file_path,調用Runtime的進程來執行:

public static void screenShotByShell(String filePath){
	String shotCmd = "screencap -p " + filePath + " \n";
	try {
		Runtime.getRuntime().exec(shotCmd);
	} catch (IOException e) {
		e.printStackTrace();
	}
}
複製代碼

優勢:代碼簡單,直接獲取到圖片;

缺點:須要系統簽名;

以上三種截屏方式,你們能夠根據應用場景來使用。若是是用戶app,須要連續錄屏,建議採用MediaProjectionManager;若是是但願獲得單個Bitmap,那麼能夠用SurfaceControl;若是是系統app,而且但願獲得圖片,首選screencap的adb命令行。

學習以上技術有哪些門檻和條件?有沒有免費資料呢? 只要你心裏有明確的目標和渴望:我必定要進入大廠,必定要成爲Android架構師。那麼學歷,年限都不能阻擋你。正常來講BAT社招門檻是3年開發經驗,本科或者以上學歷,除非你技術特別厲害才能打破。

創做不易喜歡的話記得點擊+關注哦

相關文章
相關標籤/搜索