记录Xamarin未处理(Android未捕获)异常

9
我想记录未处理的异常,但是我看到了关于是否以及如何做到这一点的矛盾信息。
我知道Xamarin会触发AndroidEnvironment.UnhandledExceptionRaiserAppDomain.CurrentDomain.UnhandledException事件,我可以订阅该事件,但我认为Android正在杀死我的进程,我无法访问Android.Utils.Log或文件系统。
如果您查看Xamarin的AdvancedAppLifecycleDemos/HandlingCrashes/App.cs,会有一个有力的论据表明您无法记录此异常。
    /// <summary>
    /// When app-wide unhandled exceptions are hit, this will handle them. Be aware however, that typically
    /// android will be destroying the process, so there's not a lot you can do on the android side of things,
    /// but your xamarin code should still be able to work. so if you have a custom err logging manager or 
    /// something, you can call that here. You _won't_ be able to call Android.Util.Log, because Dalvik
    /// will destroy the java side of the process.
    /// </summary>
    protected void HandleUnhandledException(object sender, UnhandledExceptionEventArgs args)
    {
        Exception e = (Exception)args.ExceptionObject;

        // log won't be available, because dalvik is destroying the process
        //Log.Debug (logTag, "MyHandler caught : " + e.Message);
        // instead, your err handling code shoudl be run:
        Console.WriteLine("========= MyHandler caught : " + e.Message);
    }

那么未处理的异常如何被记录?

嗨,Adam!你看到这个帖子了吗?https://forums.xamarin.com/discussion/13784/catching-global-exceptions-in-android 请注意Console.Writeline似乎不起作用,但是Android.Util.Log.Debug有效。 - Gerald Versluis
我没有特别看到那个线程,但我仍然认为Android.Util.Log可能会或可能不会工作,因为Android正在积极地杀死您的进程(如https://github.com/xamarin/monodroid-samples/tree/master/AdvancedAppLifecycleDemos/HandlingCrashes中所述)。 - Adam
1
你考虑过使用Xamarin.Insights吗?它可以在mainactivity/appdelegate初始化后捕获你未处理和已处理的异常,但在Android平台上,Insights会减慢多线程应用程序的速度,这似乎存在一些权衡。 - ClintL
2个回答

9

Xamarin Insights,HockeyApp或其他崩溃日志记录器在应用程序完成进程之前以某种方式保存崩溃数据。一旦应用程序重新启动(它们无法立即发送数据,因为该进程正在被终止),它们会将数据发送到服务器。所以完全可以实现。虽然我不确定它们是将崩溃数据保存到设备存储(最可能)还是本地SQLite数据库。

这是HockeyApp用于捕获未处理异常的代码。它可能会给您一些想法:

AndroidEnvironment.UnhandledExceptionRaiser += (sender, args) =>
{
    TraceWriter.WriteTrace(args.Exception);
    args.Handled = true;
};

AppDomain.CurrentDomain.UnhandledException += (sender, args) => 
    TraceWriter.WriteTrace(args.ExceptionObject);

// Wire up the unobserved task exception handler
TaskScheduler.UnobservedTaskException +=  (sender, args) =>
    TraceWriter.WriteTrace(args.Exception);

我建议尝试通过任何一种方法将文本文件写入本地存储。

0

Xamarin Insights 是您所需要的:https://xamarin.com/insights

使用 Xamarin Insights,您可以查看任何崩溃的完整概述,并确定应用程序中发生的问题和警告类型。

当 Xamarin Studio 5.10 最终版本发布时,Insights 也将被集成 (阅读更多)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接