我想从应用程序崩溃时获取错误日志详细信息。应用程序可能有空指针异常或任何东西,当它出现时我想在一个文件中写这个。
创建了一个异常处理程序,如下所示
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Java.Lang;
using Java.IO;
using Android.Util;
namespace errorlogdemo
{
class ExceptionHandler: Java.Lang.Thread.IUncaughtExceptionHandler
{
private Java.Lang.Thread.IUncaughtExceptionHandler defaultUEH;
private Activity app = null;
private string localPath;
public ExceptionHandler(Activity app) {
this.defaultUEH = Java.Lang.Thread.DefaultUncaughtExceptionHandler;
this.app = app;
this.localPath = "/data/data/appname/files";
}
private void writeToFile(string stacktrace, string filename) {
try {
BufferedWriter bos = new BufferedWriter(new FileWriter(
localPath + "/" + filename));
bos.Write(stacktrace);
Log.Debug("Handler Error",stacktrace);
bos.Flush();
bos.Close();
} catch (Java.Lang.Exception e) {
e.PrintStackTrace();
}
}
#region IUncaughtExceptionHandler implementation
void Thread.IUncaughtExceptionHandler.UncaughtException (Thread thread, Throwable e)
{
Writer result = new StringWriter();
PrintWriter printWriter = new PrintWriter(result);
e.PrintStackTrace(printWriter);
string stacktrace = result.ToString();
printWriter.Close();
string filename = "log.stacktrace";
if (localPath != null) {
writeToFile(stacktrace, filename);
}
defaultUEH.UncaughtException(thread, e);
}
#endregion
}
}
从主要活动创建此处理程序的实例:
Java.Lang.Thread.IUncaughtExceptionHandler = new ExceptionHandler (this);
启动应用程序时,我有以下内容
Button button = null;
button.click+=delegate{
};
这会导致应用程序崩溃,但这次不会调用异常处理程序。为什么呢?
参考:http://schimpf.es/catch-uncaught-exceptions-to-avoid-app-crash/
答案 0 :(得分:0)
如果处理了异常,应用程序不会崩溃,请创建console log
并检查。