我基本上需要将计数值存储在某处,并在应用程序再次打开时检索。 请建议一个简单的方法 我还想向用户发送一条消息,要求他们在 30 分钟后再次点击该应用程序。 我已根据您的建议更改了代码,并且工作正常,但这些值仅在退出并重新打开应用程序时才会更新。它不会实时更新该值。
public class MainActivity extends AppCompatActivity {
private InterstitialAd mInterstitialAd;
//SharedPreferences.Editor editor = getSharedPreferences("PreferencesName", MODE_PRIVATE).edit();
private Button watchButton;
SharedPreferences sharedpreferences;
public static final String MyPREFERENCES = "myprefs";
public static final String value = "key";
// int myInt = prefs.getInt("myInt", 0);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
final int i = sharedpreferences.getInt(value, 0);
MobileAds.initialize(this,
"ca-app-pub-3940256099942544~3347511713");
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId("ca-app-pub-02434841XXXXXXXX/XXXXXXXXXX");
// mInterstitialAd.loadAd(new AdRequest.Builder().build());
watchButton = findViewById(R.id.button_send);
watchButton.setOnClickListener(new View.OnClickListener() {
// Listen for when user presses button
public void onClick(View v) {
mInterstitialAd.loadAd(new AdRequest.Builder().build());
// If a interstitial is ready, show it
if(mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
}
else
{
mInterstitialAd.loadAd(new AdRequest.Builder().build());
}
// Otherwise end this activity (go back to first activity)
}
});
mInterstitialAd.setAdListener(new AdListener() {
@Override
public void onAdClosed() {
// mInterstitialAd.loadAd(new AdRequest.Builder().build());
int count = i;
count += 1;
TextView tv_data=findViewById(R.id.disCount);
tv_data.setText(Integer.toString(count));
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt(value, count);
editor.apply();
//setContentView(R.layout.activity_main);
// Load the next interstitial.
}
});
}
}
最佳答案
您可以使用SharedPreferences :
SharedPreferences.Editor editor = getSharedPreferences("PreferencesName", MODE_PRIVATE).edit();
editor.putInt("myInt", 12345);
editor.apply();
并在需要时检索它:
SharedPreferences prefs = getSharedPreferences("PreferencesName", MODE_PRIVATE);
int myInt = prefs.getInt("myInt", 0); // 0 is default
关于java - 如何在 android studio 应用程序中存储整数变量并检索它。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50567362/