2013-03-26 39 views
0

在我的應用程序中,我開始Mainactivity服務。每次打開應用程序時,我都會彈出一個提醒窗口。但是,我只想顯示一次彈出窗口。如何解決Pop up的數量?

如何存儲彈出的計數accros多個應用程序啓動?

回答

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 
} 

此代碼將展示一些東西只有一次,直到你不重新安裝應用程序或明確的應用數據

說明:

OK,我會解釋給你聽。 SharedPreferences就像應用程序中的一個私有空間,您可以在其中存儲原始數據(字符串,int,布爾...),這些數據將被保存,直到您不刪除應用程序。我上面的代碼是這樣工作的,當你啓動應用程序時,你有一個布爾值爲false,並且如果布爾值爲false - > if(!mboolean),你將只顯示彈出窗口。一旦顯示彈出窗口,您將布爾值設置爲true,然後系統會在下次檢查時看到它是真實的,並且不會再顯示彈出窗口,直到您重新安裝應用程序或清除應用程序管理器中的應用程序數據。

+0

你能PLZ告訴我,有沒有什麼標誌設置AlarmMa急於推我的懷疑,即,當流行一旦啓用標誌設置...像tat – 2013-03-26 12:10:15

+0

對不起,我不知道如何使用這個sharedprefrences代碼... – 2013-03-26 12:10:50

+0

我編輯我的答案與解釋,如果你有一些問題隨時問:) – 2013-03-26 12:14:45

1

當您按下彈出窗口時,放入此代碼。

pref = PreferenceManager 
      .getDefaultSharedPreferences(getApplicationContext()); 

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

當你的應用程序第一次開始,你推彈出,然後它在添加真實的偏好,不然它不可能做任何事情。

0

將其存放在SharedPreferences中。

E.g.將其保存在你的共享偏好,顯示彈出窗口時:

// 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();