7
我想添加一個默認處理程序到我的應用程序,所以我可以從其他未處理的異常中恢復。MonoDroid:未處理的異常恢復
我發現由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();
}
}
}
任何幫助將不勝感激,謝謝!
你有沒有得到這個工作?沒有調試我的應用程序時,我看到類似的問題。我可以告訴你''AndroidEnvironment'被調用並處理'AppDomain'之前的未捕獲的異常。 –
這不是「設置Handled flag = true」的方式,它應該是'e.Handled = true;'...:-B –