本文實例講述了Android 5.0及以上編程實現屏幕截圖功能的方法。分享給大家供大家參考,具體如下:
在Android 5.0,API 21 之前想要截圖系統屏幕必須Root才能完成,5.0之后開放了接口,下面看我們是怎么實現的。
一. 涉及到的相關類
1. MediaProjectionManager
官方原話: Manages the retrieval of certain types of {@link MediaProjection} tokens.
這個類通過 Context#getSystemService 中MEDIA_PROJECTION_SERVICE 獲取,他的功能就是獲取MediaProjection
2. MediaProjection
官方原話:A token granting applications the ability to capture screen contents and/or record system audio. The exact capabilities granted depend on the type of MediaProjection.在這個類中我們能獲取到屏幕的內容
3. ImageReader
官方原話:The ImageReader class allows direct application access to image data
rendered into a {@link android.view.Surface}
通過這個類我們可以把Surface轉換成圖片
二. 上面三個類就可以完成我們截取屏幕圖片的操作,那么下面我們將解釋他們是怎么合作完成的
1. 首先獲取用戶授權,截圖屏幕需要用戶手動授權后才能操作
@TargetApi(Build.VERSION_CODES.LOLLIPOP)public void requestCapturePermission() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { //5.0 之后才允許使用屏幕截圖 return; } MediaProjectionManager mediaProjectionManager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE); startActivityForResult( mediaProjectionManager.createScreenCaptureIntent(), REQUEST_MEDIA_PROJECTION);} 這里必須使用startActivityForResult 因為在createScreenCaptureIntent() 方法中會返回用戶授權截取屏幕的結果,用戶根據下面彈窗允許或者拒絕

用戶選擇后在Activity 的onActivityResult 中操作返回的結果data
@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case REQUEST_MEDIA_PROJECTION: if (resultCode == RESULT_OK && data != null) { FloatWindowsService.setResultData(data); startService(new Intent(getApplicationContext(), FloatWindowsService.class)); } break; }}這里我是用FloatWindowsService在桌面上顯示一個懸浮按鈕,點擊截屏,下面我們看在FloatWindowsService 是如何實現截圖
2. 截取屏幕內容生成Bitmap
首先創建ImageReader實例
private void createImageReader() { mImageReader = ImageReader.newInstance(mScreenWidth, mScreenHeight, PixelFormat.RGBA_8888, 2); } 然后點擊事件中觸發startScreenShot()
private void startScreenShot() { mFloatView.setVisibility(View.GONE); Handler handler = new Handler(); handler.postDelayed(new Runnable() { public void run() { //獲取當前屏幕內容 startVirtual(); } }, 5); handler.postDelayed(new Runnable() { public void run() { //生成圖片保存到本地 startCapture(); } }, 30);} 在startVirtual() 方法中我們做一件事,就是獲取當前屏幕內容
public void startVirtual() { if (mMediaProjection != null) { virtualDisplay(); } else { setUpMediaProjection(); virtualDisplay(); }}與此同時需要獲取MediaProjection 實例,而mResultData 是授權后返回的結果
public void setUpMediaProjection() { if (mResultData == null) { Intent intent = new Intent(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_LAUNCHER); startActivity(intent); } else { //mResultData是在Activity中用戶授權后返回的結果 mMediaProjection = getMediaProjectionManager().getMediaProjection(Activity.RESULT_OK, mResultData); }} 最終得到當前屏幕的內容,注意這里mImageReader.getSurface()被傳入,屏幕的數據也將會在ImageReader中的Surface中
private void virtualDisplay() { mVirtualDisplay = mMediaProjection.createVirtualDisplay("screen-mirror", mScreenWidth, mScreenHeight, mScreenDensity, DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR, mImageReader.getSurface(), null, null);}最后把mImageReader得到的屏幕內容數據轉換成圖片,在AsyncTask中處理,
Image.Plane中的 buffer 數據并不是完全是Bitmap所需要的,需要注意下面3點
1. Image 設置的圖片格式與Bitmap設置的必須一致
2. 緩沖數據存在行間距,所以我們必須去除這些間距
3. Image 使用后必須調用image.close();關閉,否則再次使用會報錯
@Overrideprotected Bitmap doInBackground(Image... params) { if (params == null || params.length < 1 || params[0] == null) { return null; } Image image = params[0]; 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); bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height); image.close();最后把生成的bitmap保存起來,就ok了
GitHub源碼下載地址:https://github.com/goodbranch/ScreenCapture
APK文件下載地址:https://raw.githubusercontent.com/goodbranch/AndroidNote/master/note/screenshot/ScreenCapture.apk
希望本文所述對大家Android程序設計有所幫助。
新聞熱點
疑難解答