[英]how to make sure the onDestroy method is called when the user exits
我在代碼中調用onDestroy()方法時遇到麻煩。 我的代碼的目的是當用戶使用屏幕底部的按鈕退出應用程序時編寫兩個txt文件。 這樣可以節省他們的進度。 然后將其加載到OnCreate()方法上,但是未調用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));
}
您不應該將該代碼放在onDestroy方法中。 相反,您應該在onPause方法上啟動后台服務。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.