应用启动3次后显示AlertDialog一次

问题描述 投票:0回答:2

如何在启动 3 次后显示 AltertDialog? 我只知道如何在第一次启动应用程序时执行某些操作(我是 Android 和共享首选项的初学者):

if (settings.getBoolean("my_first_time", true)) {
     Log.d("Comments", "First time");

     // Action which is done at first launch
     // save first launch
     settings.edit().putBoolean("my_first_time", false).commit();
} else {
     //not first time          
}

谢谢,菲利克斯

android sharedpreferences android-alertdialog
2个回答
1
投票

您可以通过将sharedPreferences更新1并检查它是否等于3来做到这一点,如果等于则显示alertDialog。

这是一个粗略的例子。

在您的

onCreate
方法中,添加以下内容:

int appLaunchedFor = getSharedPreferences("app_info", MODE_PRIVATE).getInt("counter", 0);

if (appLaunchedFor == 3) {
    // Launch AlertDialog;

    // Now increment by 1 so that alertDialog will not launch again.
    getSharedPreferences("app_info", MODE_PRIVATE).edit().putInt("counter", ++appLaunchedFor).commit();
} else if (appLaunchedFor < 3) {
    getSharedPreferences("app_info", MODE_PRIVATE).edit().putInt("counter", ++appLaunchedFor).commit();
}

0
投票

最简单的方法是使用 SharedPreferences,因为它很简单,而且您在评论中说过您已经使用过它。

您可以通过子类化

Application
类、增加
MyApplication#onCreate()
内的计数器并将其保存在
SharedPreferences
中来实现这一点。

注意: 这并不是 100% 确定。如果用户清除应用程序的数据,您的计数器将会丢失。为了防止这种情况,您可以使用私有数据库,例如SQLiteRealm

© www.soinside.com 2019 - 2024. All rights reserved.