我正在尝试封装从我的主要活动中获取 Android 屏幕的屏幕截图。我有一个实现的类
ImageReader.IOnImageAvailableListner
但
imageReader.SetOnImageAvailableListener(this, null)
在类中抛出一个强制转换异常(但不是编译异常)。我发现避免这种情况的唯一方法是让我的活动本身实现IOnImageAvailableListner
。似乎 Xamarin/Mono 的某些部分确实需要参数SetOnImageAvailableListner
是实现IOnImageAvailableListner
.
这是我班的相关部分:
public class Screenshooter : ImageReader.IOnImageAvailableListener
{
public void TakeScreenshot(Context context,
Result resultCode,
Intent data,
IOnScreenshot onScreenshotCallback)
{
_context = context;
_onScreenshot = onScreenshotCallback;
_imageAvailableCount = 0;
var size = new Point();
((Activity) context).WindowManager.DefaultDisplay.GetSize(size);
_width = size.X;
_height = size.Y;
_imageReader = ImageReader.NewInstance(_width, _height, ImageFormatType.Rgb565, 2);
MediaProjectionManager mediaProjectionManager = (MediaProjectionManager) context.GetSystemService(Context.MediaProjectionService);
if (_mediaProjection == null)
{
_mediaProjection =mediaProjectionManager.GetMediaProjection((int) resultCode, data);
if (_mediaProjection == null)
{
// Log.e(TAG, "MediaProjection null. Cannot take the screenshot.");
logger.Error("MediaProjection null. Cannot take the screenshot.");
return;
}
}
try
{
_virtualDisplay = _mediaProjection.CreateVirtualDisplay("Screenshotter", _width, _height, (int) context .Resources.DisplayMetrics.DensityDpi, (DisplayFlags) DisplayManager.VirtualDisplayFlagAutoMirror, _imageReader.Surface, null, null);
///////////// THIS IS THE LINE THAT FAILS ////////////
_imageReader.SetOnImageAvailableListener(this, null);
///////////////////////////////////////////////////////////
}
catch (Exception ex)
{
logger.Error($"Error in {nameof(TakeScreenshot)}", ex);
throw;
}
return;
}
//IOnImageAvailableListener Members
public void OnImageAvailable(ImageReader reader)
{
// do stuff
}
...
}
我在请求屏幕截图的活动中实例化它:
public class MainActivity : Activity
{
private void TakeScreenshot()
{
StartActivityForResult(((MediaProjectionManager) GetSystemService(MediaProjectionService)).CreateScreenCaptureIntent(),
REQUEST_CODE);
}
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
Screenshooter.GetInstance().takeScreenShot(this, resultCode, data, callback);
}
截图完成后调用的回调代码省略。
我到处都能看到这种模式的 Java android 代码示例。(具体来说,我一直在看这个例子:https ://github.com/omerjerk/Screenshotter )
我是 Android 和 Xamarin 的新手,但在 C# 方面拥有丰富的经验。
这是 Xamarin 中的错误吗?有解决办法吗?
谢谢