如何在退出时保存int?

时间:2017-10-29 21:27:28

标签: java android admob

我对Java和Android开发都很陌生。我正在使用其中一个Android Studio的Google AdMod广告活动模板,我希望能够在应用关闭时保存级别整数,并在重新开始备份时重新调用它。我发现了很多使用SharedPreferences的例子,但我不知道如何在这个项目中使用它。这可能很简单。

这是我的代码:

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();
}
}

欢迎任何帮助

2 个答案:

答案 0 :(得分:0)

以下是使用SharedPreferences的方法。

  1. 获取SharedPreferences的实例:

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

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

    preferences.getInt("level", 0);
    

答案 1 :(得分:0)

首先,您想获得SharedPreferences的实例:

SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);

现在你可以读一个数字了。 1将是您从未保存任何内容之前的默认数字。 level将是该Integer的名称:

Integer level = sharedPref.getInt("level",1);

为了保存它,您需要获取编辑器的实例然后放入新的级别。之后,您需要使用commit()或apply()。 Commit()将确保在程序执行下一个命令之前保存级别,而apply将在后台保存。我们再次需要一个sharedPreferences的实例。你可以制作一个新的或使用旧的。

    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();
}