2015-05-29 112 views
1

我用它在應用類中定義的自定義異常處理程序:在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"); 
} 

應用喪生,但立即重新啓動。這發生在無窮遠處。我做錯了什麼?

回答

0

在我來說,我只是換行:

android.os.Process.killProcess(android.os.Process.myPid()); 
Runtime.getRuntime().exit(1); 

Runtime.getRuntime().exit(1); 
android.os.Process.killProcess(android.os.Process.myPid()); 
0

我認爲Android操作系統認爲它是一個活動崩潰。 OS將自動重新創建活動。

就你而言,這是主要活動。

相關問題