为了账号安全,请及时绑定邮箱和手机立即绑定

在 Android 应用程序中保存不断变化的分数

在 Android 应用程序中保存不断变化的分数

潇潇雨雨 2022-12-15 10:51:59
我正在用 java 创建一个 android 应用程序,游戏中的分数一直在变化,每秒多次。我想创建一个保存文件以便在用户返回应用程序时能够跟踪分数,问题是我应该如何保存它?每当分数发生变化时,每秒多次写入保存文件似乎效率极低。我考虑过将它保存在 onDestroy() 方法中,但我听说不能保证它会被调用......那么,在不必每秒多次访问文件的情况下,保存乐谱的保证方法是什么?
查看完整描述

1 回答

?
肥皂起泡泡

TA贡献1829条经验 获得超6个赞

您可以使用 SharedPreferences 来存储属于应用程序的数据。


为 SharedPreferences 添加值


//Whenever you update the score call this function

void updateScore(int score){


    SharedPreferences mySharedPref = getSharedPreferences("give Any Name", Context.MODE_PRIVATE);

    SharedPreferences.Editor editor = mySharedPref.edit();

    editor.putInt("score", score);

    editor.apply();  //this function will commit asynchronously


}

如果您需要随时获取分数,请调用此函数。


//Whenever you update the score call this function

public int getScore(){


    SharedPreferences mySharedPref = getSharedPreferences("give Any Name", Context.MODE_PRIVATE);

    return mySharedPref.getInt("score", -1); //-1 is the default value that is returned if the value is not set using putInt


}


查看完整回答
反对 回复 2022-12-15
  • 1 回答
  • 0 关注
  • 48 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信