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

Ada*_*dam 8 android xamarin.android xamarin

我想记录未处理的异常,但我看到有关这是否以及如何可能的相互矛盾的信息.

我知道Xamarin引发了一个AndroidEnvironment.UnhandledExceptionRaiser或者AppDomain.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);
    }
Run Code Online (Sandbox Code Playgroud)

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

xle*_*eon 8

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);
Run Code Online (Sandbox Code Playgroud)

我建议尝试在任何这些方法中将文本文件写入本地存储