简体   繁体   中英

How to save high score in Android Game App

I am new in Java and writing android game app and I just learnt writing a simple shooting Game app. Now I want to save my highscore and I found that there is a what so called

sharedpreferences

which can be used to store the score. But I dont really understand how to use it. Can anyone help me?

Below is my Game class

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //turn title off
    requestWindowFeature(Window.FEATURE_NO_TITLE);

    //set to full screen
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);


    setContentView(new GamePanel(this));


}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_game, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

And all of the game activity I code it in my GamePanel.java class and inside this class I also count my score. So now I would like to store the score. How can I do it?

Use the android preferences :

SharedPreferences spref = getSharedPreferences("your_prefs_name", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = spref.edit();
editor.putString("deficitPercentage_key", prefVal); //
editor.commit();

the prefVal is the value to store

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM