Xamarin 中的调用目标引发了异常

2023-12-05

这是代码(运行它看看有什么问题) => https://github.com/x0axz/CustomRenderer

在我的 Xamarin 应用程序中,有一个适用于 Android 的自定义相机渲染器,它是从ViewModel通过MessagingCenter.Send<object>(this, "A");.

运行良好。唯一的问题是,在第一页上它拍摄图片,但是当我导航到另一个页面时,那里有另一个命令,MessagingCenter.Send<object>(this, "A");,拍照,但是这次返回错误调用 Camera.release() 后相机正在被使用.

下面是 ViewModel 和 Camera Renderer 的代码。

FirstCameraViewModel.cs

private void FirstCamera(object sender, EventArgs e)
{
    try
    {
        MessagingCenter.Send<object>(this, "A");
    }
    catch
    {
        Console.WriteLine(error.InnerException.StackTrace);
        Console.WriteLine(error.InnerException.Message);
    }
    finally
    {
        timer_countdown = new Timer();
        timer_countdown.Interval = 1000;
        timer_countdown.Elapsed += OnTimedEvent;
        timer_countdown.Enabled = true;
        timer_countdown.AutoReset = true;
        timer_countdown.Start();
    }
}

private void OnTimedEvent(object source, ElapsedEventArgs e)
{
    Seconds++;

    if (Seconds == 5)
    {
        MainThread.BeginInvokeOnMainThread(async () =>
        {
            await NavigationService.NavigateToAsync<SecondCameraViewModel>();
        });
    }
}

SecondCameraViewModel.cs,在此页面中返回错误

private void SecondCamera(object sender, EventArgs e)
{
    try
    {
        MessagingCenter.Send<object>(this, "A");
    }
    catch
    {
        Console.WriteLine(error.InnerException.StackTrace);
        Console.WriteLine(error.InnerException.Message);
    }
    finally
    {
        timer_countdown = new Timer();
        timer_countdown.Interval = 1000;
        timer_countdown.Elapsed += OnTimedEvent;
        timer_countdown.Enabled = true;
        timer_countdown.AutoReset = true;
        timer_countdown.Start();
    }
}

private void OnTimedEvent(object source, ElapsedEventArgs e)
{
    Seconds++;

    if (Seconds == 5)
    {
        MainThread.BeginInvokeOnMainThread(async () =>
        {
            await NavigationService.NavigateToAsync<IndexViewModel>();
        });
    }
}

UPDATE

相机预览.cs

public sealed class CameraPreview : ViewGroup, ISurfaceHolderCallback, Camera.IPictureCallback
{
    SurfaceView surfaceView;
    ISurfaceHolder holder;
    Camera.Size previewSize;
    IList<Camera.Size> supportedPreviewSizes;
    Camera camera;
    IWindowManager windowManager;

    public bool IsPreviewing { get; set; }

    public Camera Preview
    {
        get { return camera; }
        set
        {
            camera = value;
            if (camera != null)
            {
                supportedPreviewSizes = Preview.GetParameters().SupportedPreviewSizes;
                RequestLayout();
            }
        }
    }

    public CameraPreview(Context context)
        : base(context)
    {
        surfaceView = new SurfaceView(context);
        AddView(surfaceView);

        windowManager = Context.GetSystemService(Context.WindowService).JavaCast<IWindowManager>();

        IsPreviewing = false;
        holder = surfaceView.Holder;
        holder.AddCallback(this);

        MessagingCenter.Subscribe<object>(this, "A", (e) =>
        {
            camera.TakePicture(null, null, this);
        });
    }

    protected override void OnMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        int width = ResolveSize(SuggestedMinimumWidth, widthMeasureSpec);
        int height = ResolveSize(SuggestedMinimumHeight, heightMeasureSpec);
        SetMeasuredDimension(width, height);

        if (supportedPreviewSizes != null)
        {
            previewSize = GetOptimalPreviewSize(supportedPreviewSizes, width, height);
        }
    }

    protected override void OnLayout(bool changed, int l, int t, int r, int b)
    {
        var msw = MeasureSpec.MakeMeasureSpec(r - l, MeasureSpecMode.Exactly);
        var msh = MeasureSpec.MakeMeasureSpec(b - t, MeasureSpecMode.Exactly);

        surfaceView.Measure(msw, msh);
        surfaceView.Layout(0, 0, r - l, b - t);
    }

    public void SurfaceCreated(ISurfaceHolder holder)
    {
        try
        {
            if (Preview != null)
            {
                Preview.SetPreviewDisplay(holder);
            }
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine(@"           ERROR: ", ex.Message);
        }
    }

    public void SurfaceDestroyed(ISurfaceHolder holder)
    {
        if (Preview != null)
        {
            Preview.StopPreview();
        }
    }

    public void SurfaceChanged(ISurfaceHolder holder, Android.Graphics.Format format, int width, int height)
    {
        var parameters = Preview.GetParameters();
        parameters.SetPreviewSize(previewSize.Width, previewSize.Height);
        RequestLayout();

        switch (windowManager.DefaultDisplay.Rotation)
        {
            case SurfaceOrientation.Rotation0:
                camera.SetDisplayOrientation(90);
                break;
            case SurfaceOrientation.Rotation90:
                camera.SetDisplayOrientation(0);
                break;
            case SurfaceOrientation.Rotation270:
                camera.SetDisplayOrientation(180);
                break;
        }

        Preview.SetParameters(parameters);
        Preview.StartPreview();
        IsPreviewing = true;
    }

    Camera.Size GetOptimalPreviewSize(IList<Camera.Size> sizes, int w, int h)
    {
        const double AspectTolerance = 0.1;
        double targetRatio = (double)w / h;

        if (sizes == null)
        {
            return null;
        }

        Camera.Size optimalSize = null;
        double minDiff = double.MaxValue;

        int targetHeight = h;
        foreach (Camera.Size size in sizes)
        {
            double ratio = (double)size.Width / size.Height;

            if (Math.Abs(ratio - targetRatio) > AspectTolerance)
                continue;
            if (Math.Abs(size.Height - targetHeight) < minDiff)
            {
                optimalSize = size;
                minDiff = Math.Abs(size.Height - targetHeight);
            }
        }

        if (optimalSize == null)
        {
            minDiff = double.MaxValue;
            foreach (Camera.Size size in sizes)
            {
                if (Math.Abs(size.Height - targetHeight) < minDiff)
                {
                    optimalSize = size;
                    minDiff = Math.Abs(size.Height - targetHeight);
                }
            }
        }

        return optimalSize;
    }

    public void OnPictureTaken(byte[] data, Camera camera)
    {
        camera.StopPreview();

        FileOutputStream outStream = null;
        File dataDir = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDcim);
        if (data != null)
        {
            try
            {
                TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
                var s = ts.TotalMilliseconds;
                outStream = new FileOutputStream(dataDir + "/" + s + ".jpg");
                outStream.Write(data);

                outStream.Close();
            }
            catch (FileNotFoundException e)
            {
                System.Console.Out.WriteLine(e.Message);
            }
            catch (IOException ie)
            {
                System.Console.Out.WriteLine(ie.Message);
            }
        }
        camera.StartPreview();
    }
}

CameraPreviewRenderer.cs

public class CameraPreviewRenderer : ViewRenderer<Mobile.App.CameraPreview, CameraPreview>
{
    CameraPreview cameraPreview;

    public CameraPreviewRenderer(Context context) : base(context)
    {
    }

    protected override void OnElementChanged(ElementChangedEventArgs<Mobile.App.CameraPreview> e)
    {
        base.OnElementChanged(e);

        if (e.OldElement != null)
        {
            // Unsubscribe
            cameraPreview.Click -= OnCameraPreviewClicked;
        }
        if (e.NewElement != null)
        {
            if (Control == null)
            {
                cameraPreview = new CameraPreview(Context);
                SetNativeControl(cameraPreview);
            }
            Control.Preview = Camera.Open((int)e.NewElement.Camera);

            // Subscribe
            cameraPreview.Click += OnCameraPreviewClicked;
        }
    }

    void OnCameraPreviewClicked(object sender, EventArgs e)
    {
        if (cameraPreview.IsPreviewing)
        {
            cameraPreview.Preview.StopPreview();
            cameraPreview.IsPreviewing = false;
        }
        else
        {
            cameraPreview.Preview.StartPreview();
            cameraPreview.IsPreviewing = true;
        }
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            Control.Preview.Release();
        }
        base.Dispose(disposing);
    }
}

您必须取消订阅 MessagingCenter。

共享项目中的CameraPreview.cs

public event EventHandler Subscribe;
        public event EventHandler Unsubscribe;

        public void OnSubscribe()
        {
            if (Subscribe != null)
            {
                Subscribe(this, EventArgs.Empty);
            }
        }
        public void OnUnsubscribe()
        {
            if (Unsubscribe != null)
            {
                Unsubscribe(this, EventArgs.Empty);
            }
        }

主页.xaml

<local:CameraPreview Camera="Rear" x:Name="CameraPreview"  HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" />

MainPage.xaml.cs

protected override void OnAppearing()
        {
            base.OnAppearing();
            CameraPreview.OnSubscribe();
        }

        protected override void OnDisappearing()
        {
            base.OnDisappearing();
            CameraPreview.OnUnsubscribe();
        }

FirstCameraPage.xaml

<local:CameraPreview x:Name="CameraPreview"
                        Camera="Rear" 
                        HorizontalOptions="CenterAndExpand" 
                        VerticalOptions="FillAndExpand" 
                        WidthRequest="250"/>

FirstCameraPage.xaml.cs

protected override void OnAppearing()
        {
            base.OnAppearing();
            CameraPreview.OnSubscribe();
        }

        protected override void OnDisappearing()
        {
            base.OnDisappearing();
            CameraPreview.OnUnsubscribe();
        }

android项目中的CameraViewRenderer.cs

protected override void OnElementChanged(ElementChangedEventArgs<CustomRenderer.CameraPreview> e)
        {
            base.OnElementChanged(e);

            if (e.OldElement != null)
            {
                // Unsubscribe
                cameraPreview.Click -= OnCameraPreviewClicked;
            }
            if (e.NewElement != null)
            {
                if (Control == null)
                {
                    cameraPreview = new CameraPreview(Context);
                    SetNativeControl(cameraPreview);
                }
                Control.Preview = Camera.Open();
                e.NewElement.Subscribe += (sender, e) =>
                {
                    Control.Subscribe();
                };
                e.NewElement.Unsubscribe += (sender, e) =>
                {
                    Control.Unsubscribe();
                };

                // Subscribe
                cameraPreview.Click += OnCameraPreviewClicked;
            }
        }

android项目中的CameraPreview.cs,添加以下方法。

internal void Subscribe()
        {
            MessagingCenter.Subscribe<object>(this, "A", (e) =>
            {
                this.Preview.TakePicture(null, null, this);
            });
        }

        internal void Unsubscribe()
        {
            MessagingCenter.Unsubscribe<object>(this, "A");
        }

并从构造函数中删除 MessagingCenter 订阅

public CameraPreview (Context context)
            : base (context)
        {
            surfaceView = new SurfaceView (context);
            AddView (surfaceView);

            windowManager = Context.GetSystemService (Context.WindowService).JavaCast<IWindowManager> ();

            IsPreviewing = false;
            holder = surfaceView.Holder;
            holder.AddCallback (this);

            //MessagingCenter.Subscribe<object>(this, "A", (e) =>
            //{
            //  this.Preview.TakePicture(null, null, this);
            //});
        }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Xamarin 中的调用目标引发了异常 的相关文章

  • 在 Android 中调整可绘制对象的大小

    我正在为进度对话框设置一个可绘制对象 pbarDialog 但我的问题是我想每次调整可绘制的大小 但不知道如何调整 这是一些代码 Handler progressHandler new Handler public void handleM
  • 人脸 API DetectAsync 错误

    我想创建一个简单的程序来使用 Microsoft Azure Face API 和 Visual Studio 2015 检测人脸 遵循 https social technet microsoft com wiki contents ar
  • 两个静态变量同名(两个不同的文件),并在任何其他文件中 extern 其中一个

    在一个文件中将变量声明为 static 并在另一个文件中进行 extern 声明 我认为这会在链接时出现错误 因为 extern 变量不会在任何对象中看到 因为在其他文件中声明的变量带有限定符 static 但不知何故 链接器 瑞萨 没有显
  • WcfSvcHost 的跨域异常

    对于另一个跨域问题 我深表歉意 我一整天都在与这个问题作斗争 现在已经到了沸腾的地步 我有一个 Silverlight 应用程序项目 SLApp1 一个用于托管 Silverlight SLApp1 Web 的 Web 项目和 WCF 项目
  • 为什么这个字符串用AesCryptoServiceProvider第二次解密时不相等?

    我在 C VS2012 NET 4 5 中的文本加密和解密方面遇到问题 具体来说 当我加密并随后解密字符串时 输出与输入不同 然而 奇怪的是 如果我复制加密的输出并将其硬编码为字符串文字 解密就会起作用 以下代码示例说明了该问题 我究竟做错
  • 有关 ListView 自定义行布局项目上的 onClick() 事件的帮助

    我有一个 ListView 其行由我格式化 每行都有 ImageView 和 TextView 的混合 我还实现了自己的适配器 并且能够通过它绘制每一行 现在 我想要这样的东西 用户单击 ImageView 不是行上的其他任何位置 但只有此
  • 两个类可以使用 C++ 互相查看吗?

    所以我有一个 A 类 我想在其中调用一些 B 类函数 所以我包括 b h 但是 在 B 类中 我想调用 A 类函数 如果我包含 a h 它最终会陷入无限循环 对吗 我能做什么呢 仅将成员函数声明放在头文件 h 中 并将成员函数定义放在实现文
  • 实例化类时重写虚拟方法

    我有一个带有一些虚函数的类 让我们假设这是其中之一 public class AClassWhatever protected virtual string DoAThingToAString string inputString retu
  • 如何修改 Skobbler 注释而不重新添加它

    我必须修改 SKAnnotation 的图像 注释生成器代码 private SKAnnotation getAnnotationFromView int id int minZoomLvl View view SKAnnotation a
  • 如何在当前 Visual Studio 主机内的 Visual Studio 扩展中调试使用 Roslyn 编译的代码?

    我有一个 Visual Studio 扩展 它使用 Roslyn 获取当前打开的解决方案中的项目 编译它并从中运行方法 程序员可以修改该项目 我已从当前 VisualStudioWorkspace 成功编译了 Visual Studio 扩
  • 如何在 Linq to SQL 中使用distinct 和 group by

    我正在尝试将以下 sql 转换为 Linq 2 SQL select groupId count distinct userId from processroundissueinstance group by groupId 这是我的代码
  • C 函数 time() 如何处理秒的小数部分?

    The time 函数将返回自 1970 年以来的秒数 我想知道它如何对返回的秒数进行舍入 例如 对于100 4s 它会返回100还是101 有明确的定义吗 ISO C标准没有说太多 它只说time 回报 该实现对当前日历时间的最佳近似 结
  • 在 KitKat 4.4.2 中获取 SDard 路径和大小

    我在 Google Play 上有一个设备信息应用程序 在该应用程序中我有存储信息 我知道 Android 4 4 在访问外部 SD 卡方面发生了一些变化 内部似乎没有给我带来问题 我的问题是 如何可靠地获取 KitKat 上 SD 卡的大
  • javafx android 中的文本字段和组合框问题

    我在简单的 javafx android 应用程序中遇到问题 问题是我使用 gradle javafxmobile plugin 在 netbeans ide 中构建了非常简单的应用程序 其中包含一些文本字段和组合框 我在 android
  • 单元测试时 Android Studio 2.0 中测试状态终止且没有任何失败消息

    Issue 我昨天在 Ubuntu 上从 1 5 升级到了 Android Studio 2 0 当我在 Android Studio 2 0 中进行单元测试时 即使所有测试都已通过 它也会显示 终止测试 状态 有时它只显示部分测试通过 我
  • Android应用程序可以像旧的普通java小程序一样嵌入到网页中吗?

    我对 android 平台一无所知 也无法在互联网上找到这个基本问题的答案 更新 好的 我本身无法嵌入 Android 应用程序 但是我可以在 Android Webbrowser 中嵌入 Java 的东西吗 不可以 您无法将 Androi
  • 指针和内存范围

    我已经用 C 语言编程有一段时间了 但对 C 语言还是很陌生 有时我对 C 处理内存的方式感到困惑 考虑以下有效的 C 代码片段 const char string void where is this pointer variable l
  • 类型或命名空间“MyNamespace”不存在等

    我有通常的类型或命名空间名称不存在错误 除了我引用了程序集 using 语句没有显示为不正确 并且我引用的类是公共的 事实上 我在不同的解决方案中引用并使用相同的程序集来执行相同的操作 并且效果很好 顺便说一句 这是VS2010 有人有什么
  • 如何确定 CultureInfo 实例是否支持拉丁字符

    是否可以确定是否CultureInfo http msdn microsoft com en us library system globalization cultureinfo aspx我正在使用的实例是否基于拉丁字符集 我相信你可以使
  • 使用 WGL 创建现代 OpenGL 上下文?

    我正在尝试使用 Windows 函数创建 OpenGL 上下文 现代版本 基本上代码就是 创建窗口类 注册班级 创建一个窗口 choose PIXELFORMATDESCRIPTOR并设置它 创建旧版 OpenGL 上下文 使上下文成为当前

随机推荐

  • gradle 设置:com.google.android.gms.internal.zzbgl 未找到

    我读过类似的问答here and here关于这个问题 所有解决方案都是使用最新的插件 这个问题已经过时了 我需要再次使用最新版本进行新配置 我已经检查了插件兼容性 并且当我发布此问题时所有版本都是最新的 但尚未成功 错误 无法访问 zzb
  • 了解别名模板

    我问了一个question其中有几个对代码的引用 template
  • 如何处理 MongoDB 中的过时连接

    在 Mongo 中自动刷新过时连接的最佳方法是什么 回收 mongod 服务后 我从 Liferay Portlet 中得到此异常 com mongodb MongoException Network can t call somethin
  • Python for-in 循环前面有一个变量[重复]

    这个问题在这里已经有答案了 我看到一些代码 例如 foo x for x in bar if x occupants gt 1 这是什么意思 它是如何工作的 目前的答案都很好 但不要谈论它们只是如何句法糖我们已经习惯了某种模式 让我们从一个
  • 打印给定月份/年份的日历

    我正在做一个 Java 作业 它涉及在用户指定月份和年份后打印日历 我无法使用 Calendar 或 GregorianCalendar 类 我的问题是日历无法正确打印月份的第一天是星期六 我已经查看了我的代码大约一个小时了 我不确定出了什
  • TLS 1.2 在 cURL 中不起作用

    我在卷曲使用 TLS1 2 的 HTTPS url 时遇到问题 在卷曲操作中 我将登录数据发布到网站并将其保存在 cookiefile 中 我收到的错误消息是这样的 error 14077438 SSL routines SSL23 GET
  • 使用 Python 读取 RTF 文件时出现欧元符号问题

    我需要使用 Python 和 pyRTF 生成 RTF 文档 一切正常 我对重音字母没有问题 它甚至接受欧元符号而没有错误 但不是 我得到这个标志 我用这种方式对字符串进行编码 x encode iso 8859 15 我用谷歌搜索了很多
  • 将大型 VB6 应用程序升级到 .NET。对VB迁移合作伙伴的看法

    我有一个非常大的 VB6 代码库 其中包含大量第 3 方控件 想要将其移至 NET 重写它是毫无疑问的 客户认为花钱获得同样的东西没有任何价值 使用内置升级向导迁移到 NET 基本上是不可能的 有没有人尝试过 VB Migration Pa
  • Windows 上的插入器

    是否可以替换系统函数 就像在 Linux 和 Solaris 上使用 LD PRELOAD 一样 例如通过设置环境变量 LD PRELOAD path to mymalloc so 我将替换 malloc 函数 而不是在已安装在系统库中的
  • 循环#includes是如何解决的?

    在c中 假设我们有2个文件 1 h include lt 2 h gt blah blah 我们有 2小时 include lt 1 h gt code 这是怎么解决的 通常 您使用与文件名相对应的 ifndef define 来保护包含文
  • 当数据可以包含逗号时,按逗号分割字符串

    我有一个 CSV 文件 不是我设计的 现在无法更改 也永远无法更改它 其中包含如下行 Surname Firstname yes no somestring whatever etc 正如你在这里看到的 第一个 不是我想要分割字符串的逗号
  • MediaPlayer 在 Android 5.0 (Lollipop) 中抛出错误

    我编写了一个使用 HTTP 连接传输 MP3 的媒体应用程序 这在 Android 版本 2 x 4 x 上运行良好 但现在在 5 x 中生成错误 该应用程序循环播放包含 MP3 的播放列表对象 每个 MP3 都有自己唯一的 HTTP 地址
  • 在AWS lambda中创建utils.py

    I had a def hello 功能在我的home file py文件 我创建了一个home common utils py文件并将函数移到那里 现在 我想将其导入到我的文件中file py 我是这样导入的 from utils imp
  • iPhone中有系统级后台队列进程吗?

    我需要保存一个大文件 有时需要很长时间才能完成 用户可能只是关闭应用程序 我想知道iPhone SDK是否可以接手这个未完成的大任务 看来iPhone自带的邮件系统可以后台发送 我准备了一封电子邮件 单击 发送 然后立即关闭邮件应用程序 在
  • 使用 Excel VBA 创建工作表并根据特定列中的唯一项目移动数据

    我熟悉编程 但不熟悉 VBA 或 Excel 对象模型 我发现处理起来非常令人沮丧 我拥有的是一张带有列标题的数据 根据数据类型的不同 标题的数量也不同 因此我需要找到一个特定的列 在所有工作表中 该列并不总是位于同一位置 因此我无法对其进
  • Python 简单指数平滑

    我从 www nasdaq com 下载了 TESLA 股票 下载 CSV 文件后 我意识到我需要使用 Microsoft Excel 2016 转换 CSV 我使用 数据 选项卡 并单击文本到列 现在标题很清楚了 它们是 日期 收盘价 成
  • 在 Woocommerce 中获取自定义产品属性

    在 Woocommerce 中 我试图获取产品自定义属性值 但失败得很惨 我什么也没得到 所以我尝试 global woocommerce post product res get post meta product gt id print
  • CMake 设置默认搜索路径?

    我只是不想每次需要库时都设置环境变量 更不用说搜索的路径根本不标准化 至少在 Windows 上 一般来说 Find cmake 不会指定任何与 Windows 相关的位置 有没有某种方法可以使 CMake 搜索指定目录 强制配置错误的 F
  • 在Java中求多项式的根

    我需要找到一个 近似的 数值的 解勒让德多项式 我尝试了几个Java库 但没有一个有我正在寻找的东西 最接近的是commons math 它甚至有用于在拉盖尔求解器 但它没有公开该方法 是否有现有的解决方案或者我需要实施自己的解决方案 您可
  • Xamarin 中的调用目标引发了异常

    这是代码 运行它看看有什么问题 gt https github com x0axz CustomRenderer 在我的 Xamarin 应用程序中 有一个适用于 Android 的自定义相机渲染器 它是从ViewModel通过Messag