0

在我的应用程序中,我正在 Mainactivity 中启动一项服务。每次打开应用程序时,我都会显示一个提醒弹出窗口。但是,我只想显示弹出窗口 1 次。

如何在多个应用程序启动时存储弹出窗口的计数?

4

3 回答 3

2
boolean mboolean = false;

SharedPreferences settings = getSharedPreferences("PREFS_NAME", 0);
mboolean = settings.getBoolean("FIRST_RUN", false);
if (!mboolean) {
 // do the thing for the first time 
  SharedPreferences settings = getSharedPreferences("PREFS_NAME", 0);
                    SharedPreferences.Editor editor = settings.edit();
                    editor.putBoolean("FIRST_RUN", true);
                    editor.commit();                    
} else {
 // other time your app loads
}

此代码只会显示一次,直到您不重新安装应用程序或清除应用程序数据

解释:

好的,我给你解释一下。SharedPreferences 就像您的应用程序的私有空间,您可以在其中存储原始数据(字符串、整数、布尔值...),这些数据将一直保存到您不删除应用程序为止。我上面的代码是这样工作的,你有一个布尔值,当你启动应用程序时它是假的,只有当布尔值是假的时候你才会显示你的弹出窗口 --> if (!mbolean)。一旦你显示了你的弹出窗口,你在 sharedPreferences 中将布尔值设置为 true,系统下次会在那里检查,看看它是否为 true,并且不会再次显示弹出窗口,直到你重新安装应用程序或从应用程序管理器中清除应用程序数据.

于 2013-03-26T12:07:08.070 回答
1

推送弹出窗口时输入此代码。

pref = PreferenceManager
            .getDefaultSharedPreferences(getApplicationContext());

    if (!pref.getBoolean("popupfirst", false)) {
        Editor editPref = pref.edit();
        editPref.putBoolean("popupfirst", true);
        editPref.commit();
    }

当您的应用程序第一次启动并且您推送弹出窗口时,它会将 true 添加到 Preference 中,否则它无法执行任何操作。

于 2013-03-26T12:09:19.130 回答
0

将其存储在SharedPreferences中。

例如,在显示弹出窗口时将其保存在您的共享首选项中:

// Get the shared preferences
SharedPreferences prefs = getSharedPreferences("com.example.app", Context.MODE_PRIVATE);

// Edit the shared preferences
Editor editor = prefs.edit();

// Save '1' in a key named: 'alert_count'
editor.putInt("alert_count", 1);

// Commit the changes
editor.commit();

之后,当您启动应用程序时,您可以再次提取它,以检查它之前启动了多少次:

// Get the shared preferences
SharedPreferences prefs = getSharedPreferences("com.example.app", Context.MODE_PRIVATE);


// Get the value of the integer stored with key: 'alert_count'
int timesLaunched = prefs.getInt("alert_count", 0); // 0 is the default value

if(timesLaunched <= 0){
    // Pop up has not been launched before
} else {
    // Pop up has been launched 'timesLaunched' times
}

理想情况下,当您保存在 SharedPreferences 中启动的次数时,您可以先提取它,然后增加当前值。像这样:

SharedPreferences prefs = getSharedPreferences("com.example.app", Context.MODE_PRIVATE);

// Get the current value of how many times you launched the popup
int timesLaunched = prefs.getInt("alert_count", 0); // 0 is the default value
Editor editor = prefs.edit();
editor.putInt("alert_count", timesLaunched++);
editor.commit();
于 2013-03-26T12:11:22.380 回答