简体   繁体   English

应用重启后如何记分?

[英]How to remember score after app has been restarted?

I am making a two player game where I am able to have a rematch. 我正在做一个两人游戏,我可以重新比赛。 I am also keeping track of the scores of each player. 我也在跟踪每个玩家的分数。 This is what my code for a rematch looks like: 这是我的重赛代码如下所示:

public void rematch(View view) {
    Intent i = getBaseContext().getPackageManager()
            .getLaunchIntentForPackage( getBaseContext().getPackageName() );

    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    finish();
    startActivity(i);

}

The above code is called when the user clicks a rematch button. 当用户单击重新匹配按钮时,将调用上述代码。 I basically just restart the application because it's easier than resetting all the variables I have. 我基本上只是重新启动应用程序,因为它比重置我拥有的所有变量都容易。 Anyways, to keep track of the scores, I am overriding the onStop() method like this: 无论如何,为了跟踪得分,我像这样重写了onStop()方法:

@Override
protected  void onStop() {
    super.onStop();

    // We need an Editor object to make preference changes.
    // All objects are from android.context.Context
    SharedPreferences settings = getSharedPreferences(SCORES_NAME, 0);
    SharedPreferences.Editor editor = settings.edit();

    editor.putInt("scoreOne", p1Score);
    editor.putInt("scoreTwo", p2Score);

    editor.commit();
}

I am using shared preferences. 我正在使用共享首选项。 Then, in my onCreate method, I get these shared preferences like this: 然后,在我的onCreate方法中,我得到了这些共享的首选项,如下所示:

// Remember scores from previous games
    SharedPreferences settings = getSharedPreferences(SCORES_NAME, 0);
    p1Score = settings.getInt("scoreOne", 0);
    p2Score = settings.getInt("scoreTwo", 0);
    updateScores();

SCORES_NAME is public static final String SCORES_NAME = "MyScores"; SCORES_NAMEpublic static final String SCORES_NAME = "MyScores";

This all isn't working. 这一切都不起作用。 My scores after the game restarts are always back to 0. I was thinking of putting extras onto the intent in rematch() but I'm not sure how to access this intent in my onCreate() method. 我在游戏重新开始后的得分总是回到0。我正在考虑在rematch()的意图中添加额外内容,但是我不确定如何在我的onCreate()方法中访问此意图。 Any help is greatly appreciated! 任何帮助是极大的赞赏!

You need to override onSaveInstanceState(Bundle savedInstanceState) and write the application state values you want to change to the Bundle parameter like this: 您需要重写onSaveInstanceState(Bundle savedInstanceState)并将要更改的应用程序状态值写入Bundle参数,如下所示:

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
  super.onSaveInstanceState(savedInstanceState);
  // Save UI state changes to the savedInstanceState.
  // This bundle will be passed to onCreate if the process is
  // killed and restarted.
  savedInstanceState.putInt("scoreOne", p1Score);
  savedInstanceState.putInt("scoreTwo", p2Score);

  // etc.
}

The Bundle is essentially a way of storing a NVP ("Name-Value Pair") map, and it will get passed in to onCreate() and also onRestoreInstanceState() where you'd extract the values like this: Bundle本质上是一种存储NVP(“名称-值对”)映射的方法,它将被传递给onCreate()以及onRestoreInstanceState() ,您可以在其中提取如下值:

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
  super.onRestoreInstanceState(savedInstanceState);
  // Restore UI state from the savedInstanceState.
  // This bundle has also been passed to onCreate.
  int p1Score = settings.getInt("scoreOne", 0);
    int p2Score = settings.getInt("scoreTwo", 0);
}

You would usually use this technique to store instance values for your application (selections, unsaved text, etc.). 通常,您将使用此技术来存储应用程序的实例值(选择,未保存的文本等)。

Problem here is that you made the assumption that the new activity's onCreate() will be called after your first activity's onStop() has completed execution. 这里的问题是您假设在第一个活动的onStop()完成执行后将调用新活动的onCreate()

That's probably not an assumption you want to make, because they are two not completely related things. 这可能不是您要做出的假设,因为它们是两个不完全相关的事物。

Send the values you need to the newly created activity in the intent 将您需要的值发送到意图中的新创建的活动

public void rematch(View view) {
    Intent i = getBaseContext().getPackageManager()
            .getLaunchIntentForPackage( getBaseContext().getPackageName() );

    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    // Those next values will be there for sure in the new activity.
    i.putExtra("scoreOne", p1Score);
    i.putExtra("scoreTwo", p2Score);
    finish();
    startActivity(i);
}

And in the onCreate of your Activity can extract those values as follows 并且在您的Activity的onCreate中可以按以下方式提取这些值

public void onCreate(Bundle savedInstance) {
    super.onCreate();
    ..

    int p1Score = getIntent().getIntExtra("scoreOne", 0);
    int p2Score = getIntent().getIntExtra("scoreTwo", 0);
}

You need to take the code from onStop and execute it before your call to finish() from the rematch method. 您需要从onStop获取代码并执行代码,然后再从rematch方法调用finish() Like this: 像这样:

private void saveScores() {
    SharedPreferences settings = getSharedPreferences(SCORES_NAME, 0);
    SharedPreferences.Editor editor = settings.edit();

    editor.putInt("scoreOne", p1Score);
    editor.putInt("scoreTwo", p2Score);

    editor.commit();
}

And then call this function from rematch : 然后从rematch调用此函数:

(...)
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

saveScores();

finish();
startActivity(i);

However, @elmorabea's solution is better is you are now only using SharedPreferences to pass values between activities. 但是,@ elmorabea的解决方案更好,因为您现在仅使用SharedPreferences在活动之间传递值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 达到一定分数后如何更改等级? (Java、NetBeans) - How do I change my level after a certain score has been reached? (Java, NetBeans) 为什么 glassfish 服务器只在重新启动后才加载一个 bean? - Why does the glassfish server only load a bean after it has been restarted? 清除应用数据后如何注销Google? - How to log out of Google after app data has been cleared? 重启服务器后,Spring Security还记得我吗? - Is Spring Security Remember Me will work after server was restarted? 应用重启后如何让服务继续工作 - How to make service continues to work after the app is restarted 用户在测验应用中获得1分后,得分不会增加。 我该如何解决? - Score not increasing after the user has scored 1 in Quiz App. How do i fix? 显示分数后关闭活动 - Close Activity once score has been shown 应用程序重新启动后主题重置回系统 - Theme resets back to system after app is restarted 关闭并重新打开应用程序后,CountDownTimer重新启动 - CountDownTimer getting restarted after closing and reopening the app 重新启动应用程序后,无法弄清楚如何重新打开标记。 - Can't figure out how to have my markers re-open once the application has been restarted.
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM