要獲取Android設備屏幕的顯示內容,可以使用Android的MediaProjection API。以下是一個簡單的示例代碼:
<uses-permission android:name="android.permission.READ_FRAME_BUFFER"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
private static final int REQUEST_CODE_MEDIA_PROJECTION = 1;
private MediaProjectionManager mMediaProjectionManager;
private MediaProjection mMediaProjection;
private VirtualDisplay mVirtualDisplay;
private ImageReader mImageReader;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMediaProjectionManager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);
startActivityForResult(mMediaProjectionManager.createScreenCaptureIntent(), REQUEST_CODE_MEDIA_PROJECTION);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_MEDIA_PROJECTION) {
if (resultCode == RESULT_OK) {
mMediaProjection = mMediaProjectionManager.getMediaProjection(resultCode, data);
// 獲取屏幕的寬度和高度
DisplayMetrics metrics = getResources().getDisplayMetrics();
int width = metrics.widthPixels;
int height = metrics.heightPixels;
// 創建一個ImageReader對象,用于捕捉屏幕內容
mImageReader = ImageReader.newInstance(width, height, PixelFormat.RGBA_8888, 2);
mVirtualDisplay = mMediaProjection.createVirtualDisplay("ScreenCapture",
width, height, metrics.densityDpi,
DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
mImageReader.getSurface(), null, null);
}
}
}
Image image = mImageReader.acquireLatestImage();
if (image != null) {
// 處理屏幕內容
// ...
// 釋放Image資源
image.close();
}
請注意,使用MediaProjection API需要用戶授權,因此需要在Activity中調用startActivityForResult方法來獲取用戶的授權。授權成功后,可以通過ImageReader對象獲取屏幕的內容。