在我的 Android Java 应用程序中,我尝试在 WebView 上截取屏幕截图并将图像发送到 API 以验证功能。当前的功能适用于加载到 webview 的所有内容,但是当涉及到视频时,它会截取空白屏幕截图或仅截取没有视频的背景。
有人可以帮我弄清楚如何在 WebView 中对视频进行截图吗?
目前,我正在使用以下代码来截图。
public void takeScreenshot() {
String fileName = generateScreenshotFilename();
try {
// wait for the view to be fully drawn
Thread.sleep(500);
// create bitmap screen capture
View v1 = this.activity.getWindow().getDecorView().getRootView();
Bitmap bitmap = Bitmap.createBitmap(
v1.getWidth(), v1.getHeight(), Bitmap.Config.ARGB_8888
);
Canvas canvas = new Canvas(bitmap);
v1.draw(canvas);
// Start of API call
OkHttpClient client = new OkHttpClient();
MultipartBody.Builder requestBodyBuilder = new MultipartBody.Builder()
.setType(MultipartBody.FORM);
String macAddress = Constants.getMacAddress(this.activity);
if (bitmap != null) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream.toByteArray();
requestBodyBuilder.addFormDataPart("image", fileName,
RequestBody.create(byteArray, MEDIA_TYPE_PNG));
}
Request request = new Request.Builder()
.url(Constants.API_URL + "/capture/upload/snap/" + macAddress)
.post(requestBodyBuilder.build())
.build();
if (duplicatedScreenshotCall) {
return;
}
duplicatedScreenshotCall = true;
SendScreenshotAPI sendScreenshotAPI = new SendScreenshotAPI(client, request);
sendScreenshotAPI.execute();
// Check if the looper is already prepared for this thread
if (Looper.myLooper() == null) {
// Prepare the looper for the background thread
Looper.prepare();
}
new Handler().postDelayed(() -> duplicatedScreenshotCall = false, Constants.DOUBLE_PRESS_INTERVAL);
// Start the message loop for the background thread if it wasn't prepared before
if (Looper.myLooper() == null) {
Looper.loop();
}
} catch (Throwable e) {
e.printStackTrace();
}
}
我也使用了下面的代码,它也产生了上面的代码。上面的代码更可靠,因为 Android API 28
view.getDrawingCache()
已被弃用。
View v1 = this.activity.getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
DRM 内容查看者可能会在捕获屏幕之前使缓存失效。这样做是为了防止从最低级别捕获受 DRM 保护的材料。有些软件在这方面更加智能,但大多数都拒绝直接访问视图。