Java 如何在退出时保存int?

Java 如何在退出时保存int?,java,android,admob,Java,Android,Admob,我对Java和Android开发都比较陌生。我正在使用Android Studio的Google AdMod广告活动模板之一,我希望能够在应用程序关闭时保存级别整数,并在再次启动时调用它。我发现了许多使用SharedReferences的例子,但我不知道如何在这个项目中使用它。这可能很简单 这是我的密码: package com.example.dthom.adsimulator; import com.google.android.gms.ads.AdListener; import com

我对Java和Android开发都比较陌生。我正在使用Android Studio的Google AdMod广告活动模板之一,我希望能够在应用程序关闭时保存级别整数,并在再次启动时调用它。我发现了许多使用
SharedReferences
的例子,但我不知道如何在这个项目中使用它。这可能很简单

这是我的密码:

package com.example.dthom.adsimulator;

import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.InterstitialAd;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
// Remove the below line after defining your own ad unit ID.
private static final String TOAST_TEXT = "Test ads are being shown. "
        + "To show live ads, replace the ad unit ID in 
res/values/strings.xml with your own ad unit ID.";

private static final int START_LEVEL = 1;
private int mLevel;
private Button mNextLevelButton;
private InterstitialAd mInterstitialAd;
private TextView mLevelTextView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Create the next level button, which tries to show an interstitial 
when clicked.
    mNextLevelButton = ((Button) findViewById(R.id.next_level_button));
    mNextLevelButton.setEnabled(false);
    mNextLevelButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            showInterstitial();
        }
    });

    // Create the text view to show the level number.
    mLevelTextView = (TextView) findViewById(R.id.level);
    mLevel = START_LEVEL;

    // Create the InterstitialAd and set the adUnitId (defined in 
values/strings.xml).
    mInterstitialAd = newInterstitialAd();
    loadInterstitial();

    // Toasts the test ad message on the screen. Remove this after defining 
your own ad unit ID.
    Toast.makeText(this, TOAST_TEXT, Toast.LENGTH_LONG).show();
}


@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_main, 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();

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

    return super.onOptionsItemSelected(item);
}

private InterstitialAd newInterstitialAd() {
    InterstitialAd interstitialAd = new InterstitialAd(this);
    interstitialAd.setAdUnitId(getString(R.string.interstitial_ad_unit_id));
    interstitialAd.setAdListener(new AdListener() {
        @Override
        public void onAdLoaded() {
            mNextLevelButton.setEnabled(true);
        }

        @Override
        public void onAdFailedToLoad(int errorCode) {
            mNextLevelButton.setEnabled(true);
        }

        @Override
        public void onAdClosed() {
            // Proceed to the next level.
            goToNextLevel();
        }
    });
    return interstitialAd;
}

private void showInterstitial() {
    // Show the ad if it's ready. Otherwise toast and reload the ad.
    if (mInterstitialAd != null && mInterstitialAd.isLoaded()) {
        mInterstitialAd.show();
    } else {
        Toast.makeText(this, "Ad did not load", Toast.LENGTH_SHORT).show();
        goToNextLevel();
    }
}

private void loadInterstitial() {
    // Disable the next level button and load the ad.
    mNextLevelButton.setEnabled(false);
    AdRequest adRequest = new AdRequest.Builder()
            .setRequestAgent("android_studio:ad_template").build();
    mInterstitialAd.loadAd(adRequest);
}

private void goToNextLevel() {
    // Show the next level and reload the ad to prepare for the level after.
    mLevelTextView.setText("Level " + (++mLevel));
    mInterstitialAd = newInterstitialAd();
    loadInterstitial();
}
}

欢迎提供任何帮助

以下是如何使用
SharedReferences

  • 获取
    SharedReferences
    的实例:

    SharedPreferences preferences = getSharedPreferences("preferences", MODE_PRIVATE);
    
  • 保存
    int

    preferences.edit().putInt("level", value).commit();
    
  • 检索
    int
    (您可以将
    0
    替换为默认级别):


  • 首先,您要获取SharedReferences的实例:

    SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
    
    现在你可以读一个数字了。如果您以前从未保存过任何内容,则默认数字为1。级别将是该整数的名称:

    Integer level = sharedPref.getInt("level",1);
    
    为了保存它,您需要获取编辑器的一个实例,然后将其放入新的级别。之后,您需要使用commit()或apply()。Commit()将确保在程序执行下一个命令之前保存该级别,而apply将在后台保存。我们再次需要SharedReferences的实例。你可以做一个新的或使用旧的

        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putInt("level",newlevel);
        editor.commit();
    
    如果要设置用户退出时的级别,请在onStop()中执行,然后在需要时再次读取:

    @Override
    protected void onStop() {
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putInt("level",newlevel);
        editor.commit();
        super.onStop();
    }
    

    根据android文档,它说您应该在onStop方法中释放资源和其他关机操作,即@Override protected void onStop(){//首先调用超类方法super.onStop();//此处为您的状态savepreferences方法}更多详细信息,请检查onStop方法。在这里使用SharedReferences:GET:Context=getActivity();SharedReferences SharedReferences=context.getSharedReferences(“preferenceKeyNameHere”,context.MODE_PRIVATE);-------------------------------------PUT:SharedReferences sharedPref=getActivity().getPreferences(Context.MODE\u PRIVATE);SharedPreferences.Editor=sharedPref.edit();editor.putInt(“preferenceKeyNameHere”,yourNumber);commit();用于存储项的键,用于检索项
    @Override
    protected void onStop() {
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putInt("level",newlevel);
        editor.commit();
        super.onStop();
    }