我用它在應用類中定義的自定義異常處理程序:在MainActivityAndroid不能殺死應用程序。應用程序重新啓動
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler()
{
@Override
public void uncaughtException(Thread thread, Throwable ex)
{
StringWriter stackTrace = new StringWriter();
ex.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);
File root = android.os.Environment.getExternalStorageDirectory();
String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());
File dir = new File(root.getAbsolutePath() + "/.helper/crashes/");
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, "log.txt");
try {
BufferedWriter buf = new BufferedWriter(new FileWriter(file, true));
buf.append(currentDateTimeString + ":" + errorReport.toString());
buf.newLine();
buf.close();
} catch (IOException e) {
e.printStackTrace();
}
android.os.Process.killProcess(android.os.Process.myPid());
Runtime.getRuntime().exit(1);
}
});
在OnCreate中我模擬例外:
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.activity_root);
throw new NullPointerException("Example");
}
應用喪生,但立即重新啓動。這發生在無窮遠處。我做錯了什麼?