如何在程序退出之前确保保存文件已完成写入?

时间:2017-06-04 02:18:05

标签: java android libgdx

我正在使用Libgdx编写游戏,我发现在Android上,当按下主页按钮并返回时,我的游戏会增加分配给它的内存量每次大约1.5 - 2 MB 。我试图找出发生这种情况的原因,但我一直无法找到它。无论如何,我决定关闭我的程序,而不是让它通过使用

保留在android的内存中
System.exit(0);

通过这样做,内存被清除,我不必担心增加。我知道这不太理想,但我真的无法追查这个问题。

问题是现在我的保存文件在程序退出之前没有完成所有内容的编写。

在我的保存课程中:

public class Save
{
    //GameData class holds all of my values that need to be saved.
    public static GameData data =  new GameData();

    public static void saveData() thorws IOException
    {
        FileHandle file = Gdx.files.local("saveData.sav");

        OutputStream out = null;
        try
        {
            file.writeBytes(serialize(data), false;)
        }
        catch(Exception ex)
        {
            System.out.println(ex.toString());
        }
        finally
        {
            if (out != null)
            {
                try
                {
                    out.close();
                }
                catch(Exception ex)
                {
                }
            }
        }
    }

    private static byte[] serialize(Object obj) throws IOException
    {
        ByteArrayOutputStream b = new ByteArrayOutputStream();
        ObjectOutputStream o = new ObjectOutputStream(b);
        o.writeObject(obj);
        return b.toByteArray();
    }
}

在我的主课堂中:

public class MainGame extends ApplicationAdapter
{
    public void create()
    {
        resume();
    }

    public void render()
    {
        //.....
    }

    public void resize()
    {
        //......
    }

    public void pause()
    {
         //set things that need to be saved

        //save
        try
        {
             Save.saveData();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

        //now I set my arraylists and pretty much everything else to null           
        //that can be set to null.  I was hoping this would fix the memory
        //increasing issue.  It helped but didn't fix it completely.

        //call dispose
        dispose();
    }

    public void resume()
    {
        //loads various things and determines if the game is to load from
        //save due to home being pressed or just load normally.
    }

    public void dispose()
    {
        //dispose of a few things

        //exit
        System.exit(0);
    }
}

如何确保程序只在所有数据输出完毕后退出? 我自己尝试了一些不起作用的东西,所以我希望有人可以提供帮助。

0 个答案:

没有答案