2017-10-16 119 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

相關問題