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

前端之家收集整理的这篇文章主要介绍了c# – MonoDroid:未处理的异常恢复前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试向我的应用程序添加一个默认处理程序,以便我可以从其他未处理的异常中恢复.

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

  1. using System;
  2. using Android.App;
  3. using Android.Content;
  4. using Android.Runtime;
  5. using Android.Views;
  6. using Android.Widget;
  7. using Android.OS;
  8.  
  9. namespace TestApp {
  10. [Android.App.Activity(Label = "TestApp",MainLauncher = true,Icon = "@drawable/icon")]
  11. public class MainActivity : Activity {
  12. protected override void OnCreate(Bundle bundle) {
  13. base.OnCreate(bundle);
  14. SetContentView(new LinearLayout(this));
  15.  
  16. //set up handlers for uncaught exceptions:
  17. //Java solution
  18. Java.Lang.Thread.DefaultUncaughtExceptionHandler = new ExceptionHandler(this);
  19. //MonoDroid solution #1
  20. AndroidEnvironment.UnhandledExceptionRaiser += AndroidEnvironment_UnhandledExceptionRaiser;
  21. //MonoDroid solution #2
  22. AppDomain.CurrentDomain.UnhandledException += delegate { new Alert(this,"AppDomain.CurrentDomain.UnhandledException","error"); };
  23.  
  24. //throw an exception to test
  25. throw new Exception("uncaught exception");
  26. }
  27.  
  28. void AndroidEnvironment_UnhandledExceptionRaiser(object sender,RaiseThrowableEventArgs e)
  29. {
  30. //found a suggestion to set the Handled flag=true,but it has no effect
  31. new Android.Runtime.RaiseThrowableEventArgs(e.Exception).Handled = true;
  32. new Alert(this,"AndroidEnvironment.UnhandledExceptionRaiser","error");
  33. }
  34. }
  35.  
  36. public class ExceptionHandler : Java.Lang.Object,Java.Lang.Thread.IUncaughtExceptionHandler {
  37. private Context _context;
  38. public ExceptionHandler(Context c) { _context = c; }
  39. public void UncaughtException(Java.Lang.Thread thread,Java.Lang.Throwable ex) {
  40. new Alert(_context,"java exception handler");
  41. }
  42. }
  43.  
  44. public class Alert {
  45. public Alert(Context c,string src,string title = "alert") {
  46. Android.App.AlertDialog.Builder builder = new Android.App.AlertDialog.Builder(c);
  47. builder.SetTitle(title);
  48. builder.SetMessage(src);
  49. builder.SetPositiveButton("Ok",delegate { });
  50. Android.App.AlertDialog alert = builder.Create();
  51. alert.Show();
  52. }
  53. }
  54. }

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

解决方法

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

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

猜你在找的C#相关文章