Monodroid:在遇到未处理的异常后,我该怎么办?

时间:2013-07-11 16:49:45

标签: android error-handling xamarin.android exit toast

对于我的Monodroid应用程序,我想在未处理的异常后执行以下操作:

  1. 将错误发送到服务器。
  2. 通知用户应用程序已崩溃(可能带有Toast消息)。
  3. 正常退出应用程序。
  4. 我已经实现了#1,但我正在努力实现#2和#3。

    Toast在未处理的异常后似乎不可用,我已被警告it's a bad idea to exit an app on a user's behalf.

    有人能指出我正确的方向吗?

    这是我的代码:

    using System;
    using Android.App;
    using Android.Runtime;
    using Android.Widget;
    
    namespace MyAppsNamespace
    {
        [Application]
        public class MyApplication : Application
        {
            public static MyApplication Current { get; private set; }
    
            public MyApplication (IntPtr handle, global::Android.Runtime.JniHandleOwnership transfer) : base(handle, transfer)
            {
                Current = this;
            }
    
            public override void OnCreate()
            {
                base.OnCreate();
                AndroidEnvironment.UnhandledExceptionRaiser += (sender, args) => LogException(args.Exception);
            }
    
            public static void LogException(Exception exception)
            {
                var phoneId = Guid.NewGuid(); // just for testing purposes
                var client = AppConfig.ErrorLoggingServiceClient;
                var response = client.Send<ErrorLoggingResponse>(new ErrorLoggingEntry
                    {
                        PhoneId = phoneId,
                        ErrorTime = DateTime.UtcNow,
                        Message = exception.Message,
                        StackTrace = exception.StackTrace
                    }); // This works fine (i.e. I've implemented #1)
                Toast.MakeText(Context, String.Format("An error occurred. Please call Prod Support at 1-800-555-1212. [Phone Id: '{0}']", phoneId), ToastLength.Short).Show(); // This has no impact.
            }
        }
    }
    

1 个答案:

答案 0 :(得分:2)

不确定Context中提到的上下文:

Toast.MakeText(Context, "ERROR", ToastLength.Short).Show();

你可以尝试

Toast.MakeText(YourMainApplication.this, "ERROR", ToastLength.Short).Show();

代替。