加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – MonoDroid:未处理的异常恢复

发布时间:2020-12-15 07:51:00 所属栏目:百科 来源:网络整理
导读:我正在尝试向我的应用程序添加一个默认处理程序,以便我可以从其他未处理的异常中恢复. 我发现Android / MonoDroid提供了三种机制,据我所知,应该可以实现这一点,但我无法让它们中的任何一种工作.这是我的代码: using System;using Android.App;using Android
我正在尝试向我的应用程序添加一个默认处理程序,以便我可以从其他未处理的异常中恢复.

我发现Android / MonoDroid提供了三种机制,据我所知,应该可以实现这一点,但我无法让它们中的任何一种工作.这是我的代码:

using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;

namespace TestApp {
    [Android.App.Activity(Label = "TestApp",MainLauncher = true,Icon = "@drawable/icon")]
    public class MainActivity : Activity {
        protected override void OnCreate(Bundle bundle) {
            base.OnCreate(bundle);
            SetContentView(new LinearLayout(this));

            //set up handlers for uncaught exceptions:
            //Java solution
            Java.Lang.Thread.DefaultUncaughtExceptionHandler = new ExceptionHandler(this);
            //MonoDroid solution #1
            AndroidEnvironment.UnhandledExceptionRaiser += AndroidEnvironment_UnhandledExceptionRaiser;
            //MonoDroid solution #2
            AppDomain.CurrentDomain.UnhandledException += delegate { new Alert(this,"AppDomain.CurrentDomain.UnhandledException","error"); };

            //throw an exception to test
            throw new Exception("uncaught exception");
        }

        void AndroidEnvironment_UnhandledExceptionRaiser(object sender,RaiseThrowableEventArgs e)
        {
            //found a suggestion to set the Handled flag=true,but it has no effect
            new Android.Runtime.RaiseThrowableEventArgs(e.Exception).Handled = true;
            new Alert(this,"AndroidEnvironment.UnhandledExceptionRaiser","error");
        }
    }

    public class ExceptionHandler : Java.Lang.Object,Java.Lang.Thread.IUncaughtExceptionHandler {
        private Context _context;
        public ExceptionHandler(Context c) { _context = c; }
        public void UncaughtException(Java.Lang.Thread thread,Java.Lang.Throwable ex) {
            new Alert(_context,"java exception handler");
        }
    }

    public class Alert {
        public Alert(Context c,string src,string title = "alert") {
            Android.App.AlertDialog.Builder builder = new Android.App.AlertDialog.Builder(c);
            builder.SetTitle(title);
            builder.SetMessage(src);
            builder.SetPositiveButton("Ok",delegate { });
            Android.App.AlertDialog alert = builder.Create();
            alert.Show();
        }
    }
}

任何帮助将不胜感激,谢谢!

解决方法

您可以在AppDomain.CurrentDomain.UnhandledException事件中捕获大多数异常.但是你不能在这个委托中调用AlertDialog,因为:
1.应用程序崩溃了.
2.至少调用UnhandledException事件.
3. alert.Show()执行异步(在UI线程中)

因此,您应该使用同步操作(例如,System.IO).您不应该使用本机UI操作,因为它们是异步的.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读