如何确保在用户退出时调用onDestroy方法

时间:2015-02-10 00:14:33

标签: android

我在代码中调用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));
}

1 个答案:

答案 0 :(得分:0)

您不应该将该代码放在onDestroy方法中。您应该在onPause方法上启动后台服务。