2017-10-16 88 views
-4

如何在启动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   
} 

感谢的,菲利克斯

+2

你到目前为止试过的felix? –

+0

我是初学者,所以我只在第一次使用sharedpreferences时工作过一次。 – Seilbahn

+0

每次显示时,增加并保存到sharedpref并在显示之前读取 – nomag

回答

1

您可以通过将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(); 
} 
+0

我得到一个错误的第3行运算符==和SharedPreferences中的(String,int) 无法应用于(字符串)在第1行 – Seilbahn

+0

哦!在第一行中将'String'更改为'int'。 –

+0

但是现在int不能应用于字符串,并且在第2行中,您的运算符不能应用。谢谢你的帮助! – Seilbahn

0

要做到这一点,最简单的方法是使用SharedPreferences ,因为它很简单,你在评论中说过你已经使用过它。

你可以通过继承Application类,在MyApplication#onCreate()内增加一个计数器并将其保存在SharedPreferences中。

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

+0

“如果用户清除应用程序的数据“,除了那些保存到[外部存储](https://developer.android.com/guide/topics/data/data-storage.html#filesExternal)的数据外,每种数据都将丢失。由于“私人数据库”不能保存到外部存储器(这不是私有的),它们也将被删除。 – 0X0nosugar

+0

@ 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卡 –

+0

感谢您的答案,但我不知道我应该如何将其保存在sharedpreferences。我是Android的初学者 – Seilbahn

相关问题