在应用程序启动3次后显示AlertDialog
如何在启动3次后显示AltertDialog? 我只知道如何在应用程序中(我与Android和Sharedpreferences初学者)第一次启动做一些事情:在应用程序启动3次后显示AlertDialog
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
}
感谢的,菲利克斯
您可以通过将sharedPreferences更新为1并检查它是否等于3来实现,如果它显示alertDialog。
下面是一个粗略的例子。
在你的onCreate方法中加入这个。
int appLaunchedFor = getSharedPreferences("app_info", MODE_PRIVATE).getInt("counter", 0);
if(appLaunchedFor == 3){
//Launch AlertDialog;
//Now increament 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();
}
要做到这一点,最简单的方法是使用SharedPreferences ,因为它很简单,你在评论中说过你已经使用过它。
你可以通过继承Application
类,在MyApplication#onCreate()
内增加一个计数器并将其保存在SharedPreferences
中。
注意:这不是100%确定。如果用户清除应用程序的数据,您的柜台将会丢失。为了防止这种情况,您可以使用私人数据库,如SQLite和Realm。
“如果用户清除应用程序的数据“,除了那些保存到[外部存储](https://developer.android.com/guide/topics/data/data-storage.html#filesExternal)的数据外,每种数据都将丢失。由于“私人数据库”不能保存到外部存储器(这不是私有的),它们也将被删除。 – 0X0nosugar
@ 0X0nosugar,这不完全正确。 SQLite和Realm **都可以保存在外部存储中([SQLite source] [1],[Realm source] [2])。在那种情况下,他需要READ_EXTERNAL_STORAGE和WRITE_EXTERNAL_STORAGE权限。 [1]:https://stackoverflow.com/questions/14373863/how-to-store-sqlite-database-directly-on-sdcard [2]:https://stackoverflow.com/questions/29551664/如何移动我的Realm文件在SD卡 –
感谢您的答案,但我不知道我应该如何将其保存在sharedpreferences。我是Android的初学者 – Seilbahn
你到目前为止试过的felix? –
我是初学者,所以我只在第一次使用sharedpreferences时工作过一次。 – Seilbahn
每次显示时,增加并保存到sharedpref并在显示之前读取 – nomag