2015-02-10 93 views
0

我無法在代碼中調用onDestroy()方法。 我的代碼的目的是當用戶通過使用屏幕底部的按鈕退出應用程序時編寫兩個txt文件。這可以節省他們的進展。 然後將它加載到OnCreate()方法 然而,OnDestroy()方法不會被調用 有沒有辦法在手機上按下退出按鈕時發生這種情況? 代碼的主體不包括在內,因爲它對我的問題並不重要。謝謝。 這裏是我的代碼如何確保在用戶退出時調用onDestroy方法

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_card_question); 
    try{ 
     FileInputStream fis = openFileInput("correct.txt"); 
     //InputStreamReader isr = new InputStreamReader(fIn); 
     StringBuffer sb= new StringBuffer(); 
     BufferedReader br= new BufferedReader(new InputStreamReader(fis)); 
     String strLine = null; 
     int x=0; 


     while((strLine=br.readLine())!=null){ 
      arrayCorrect[x]=strLine; 
      x++; 

     } 


     //Log.i("File Reading stuff", "success = " + "hell"); 

    } catch (IOException ioe) 
    {//ioe.printStackTrace(); 
    } 
    try{ 
     FileInputStream fis = openFileInput("incorrect.txt"); 
     //InputStreamReader isr = new InputStreamReader(fIn); 
     StringBuffer sb= new StringBuffer(); 
     BufferedReader br= new BufferedReader(new InputStreamReader(fis)); 
     String strLine = null; 
     int x=0; 


     while((strLine=br.readLine())!=null){ 
      arrayIncorrect[x]=strLine; 
      x++; 

     } 


     //Log.i("File Reading stuff", "success = " + "hell"); 

    } catch (IOException ioe) 
    {//ioe.printStackTrace(); 
    } 
@Override 
public void onDestroy() { 
    super.onDestroy(); // Always call the superclass 
    try{ 
     FileOutputStream fOut = openFileOutput("correct.txt", 
       MODE_WORLD_READABLE); 
     OutputStreamWriter osw = new OutputStreamWriter(fOut); 

     // Write the string to the file 
     for(int x=0; x<arrayCorrect.length; x++) { 
      osw.write(arrayCorrect[x] + "\n"); 
     } 

    /* ensure that everything is 
    * really written out and close */ 
     osw.flush(); 
     osw.close(); 
    } 
    catch(IOException ioe){ 
     ioe.printStackTrace(); 
    } 
    try{ 
     FileOutputStream fOut = openFileOutput("incorrect.txt", 
       MODE_WORLD_READABLE); 
     OutputStreamWriter osw = new OutputStreamWriter(fOut); 

     // Write the string to the file 
     for(int x=0; x<arrayIncorrect.length; x++) { 
      osw.write(arrayIncorrect[x] + "\n"); 
     } 

    /* ensure that everything is 
    * really written out and close */ 
     osw.flush(); 
     osw.close(); 
    } 
    catch(IOException ioe){ 
     ioe.printStackTrace(); 
    } 

    // startActivity(new Intent(getApplication(),second.class)); 
} 
+0

在'onStop()'做,它會被稱爲soo很多次,但'onDestroy()'將最終被調用,但並不總是,但是當它們被活動破壞時被調用。在那裏檢查值,檢查它們是否被觸發 – Elltz 2015-02-10 00:23:30

+0

我猜測在super.onDestroy()之後編寫的任何代碼都不會被調用,因爲onDestroy完全完成了應用程序。任何之後調用的內容都會被忽略。 – 2015-02-10 00:26:06

+0

當按下退出按鈕時,不會調用'onDestroy'生命週期,因爲您的活動未被破壞。 'onStop' /'onResume'是你應該爲你的情況處理的回調。 – alijandro 2015-02-10 00:27:31

回答

0

你不應該把這段代碼放在onDestroy方法中。您應該在onPause方法上啓動後臺服務。

相關問題