Android 捕获错误和用户信息
我有一个问题,因为我的应用程序在后台运行,有时会出现关闭它的错误。如何捕获任何活动或服务中的错误,以便播放声音并在通知栏上添加信息?要解决此问题,您可以使用uncaughtExceptionHandler接口Android 捕获错误和用户信息,android,Android,我有一个问题,因为我的应用程序在后台运行,有时会出现关闭它的错误。如何捕获任何活动或服务中的错误,以便播放声音并在通知栏上添加信息?要解决此问题,您可以使用uncaughtExceptionHandler接口 public class ExceptionHandler implements UncaughtExceptionHandler{ Utils utils ; Context context; private final String LINE_SEPARATOR = "\n"; p
public class ExceptionHandler implements UncaughtExceptionHandler{
Utils utils ;
Context context;
private final String LINE_SEPARATOR = "\n";
public ExceptionHandler(Context con) {
// TODO Auto-generated constructor stub
context = con;
}
@Override
public void uncaughtException(Thread arg0, Throwable arg1) {
// TODO Auto-generated method stub
StringWriter stackTrace = new StringWriter();
arg1.printStackTrace(new PrintWriter(stackTrace));
StringBuilder errorReport = new StringBuilder();
errorReport.append("************ CAUSE OF ERROR ************\n\n");
errorReport.append(stackTrace.toString());
errorReport.append("\n************ DEVICE INFORMATION ***********\n");
errorReport.append("Brand: ");
errorReport.append(Build.BRAND);
errorReport.append(LINE_SEPARATOR);
errorReport.append("Device: ");
errorReport.append(Build.DEVICE);
errorReport.append(LINE_SEPARATOR);
errorReport.append("Model: ");
errorReport.append(Build.MODEL);
errorReport.append(LINE_SEPARATOR);
errorReport.append("Id: ");
errorReport.append(Build.ID);
errorReport.append(LINE_SEPARATOR);
errorReport.append("Product: ");
errorReport.append(Build.PRODUCT);
errorReport.append(LINE_SEPARATOR);
errorReport.append("\n************ FIRMWARE ************\n");
errorReport.append("SDK: ");
errorReport.append(Build.VERSION.SDK);
errorReport.append(LINE_SEPARATOR);
errorReport.append("Release: ");
errorReport.append(Build.VERSION.RELEASE);
errorReport.append(LINE_SEPARATOR);
errorReport.append("Incremental: ");
errorReport.append(Build.VERSION.INCREMENTAL);
errorReport.append(LINE_SEPARATOR);
//after this you can do whatever you want , like i start an activity and show error log there
Intent i = new Intent(context,ExceptionActivity.class);
i.putExtra("exception",errorReport.toString());
context.startActivity(i);
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(10);
}
}
再加上这一行
Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));
在每个活动中(未捕获异常可能引发的地方)在Oncreate方法中使用未捕获异常处理程序
Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread thread, Throwable ex) {
ex.printStackTrace();
Log.e(TAG, "Uncaught Exception "+ex);
//Habdle your exception here.
System.exit(2);
android.os.Process.killProcess(android.os.Process.myPid());
}
});
没有代码和/或logcat??为这种情况创建Try catch。请将代码包装在Try{}块中,然后在catch块上处理错误