如何在Xamarin.Android中正确编写自定义UncaughtExceptionHandler

我想要实现的只是捕获我的应用程序上的exception,以便我可以将它们发送到服务器。 我想通过在StackOverflow中回答Java中的原生Android代码编写我的自定义UncaughtExceptionHandler ,我可以做到这一点。

这是我的CustomExceptionHandler类:

public class CustomExceptionHandler : Thread.IUncaughtExceptionHandler { public IntPtr Handle { get; private set; } public CustomExceptionHandler(Thread.IUncaughtExceptionHandler exceptionHandler) { Handle = exceptionHandler.Handle; } public void UncaughtException(Thread t, Throwable e) { // Submit exception details to a server ... // Display error message for local debugging purposes Debug.WriteLine(e); } public void Dispose() { throw new NotImplementedException(); } } 

然后我使用这个类在我的Activity中设置DefaultUncaughtExceptionHandler

 // Set the default exception handler to a custom one Thread.DefaultUncaughtExceptionHandler = new CustomExceptionHandler( Thread.DefaultUncaughtExceptionHandler); 

我不知道这种方法有什么问题,它确实构建了但是我在运行时得到了一个InvalidCastException

错误图片

我的CustomExceptionHandlerDefaultUncaughtExceptionHandler具有相同的Thread.IUncaughtExceptionHandler接口类型,但为什么我会收到此错误? 请赐教。 谢谢。

它再次袭来:D这是一个常见的错误。 如果实现Java接口,则必须inheritanceJava.Lang.Object

 public class CustomExceptionHandler : Java.Lang.Object, Thread.IUncaughtExceptionHandler { public void UncaughtException(Thread t, Throwable e) { // Submit exception details to a server ... // Display error message for local debugging purposes Debug.WriteLine(e); } }