如何在第一次打开时将Vairable设置为0

时间:2018-01-21 00:23:44

标签: java android android-studio

我有没有办法将整数变量设置为0,但它只会在设备第一次打开应用程序时执行此操作?

1 个答案:

答案 0 :(得分:2)

创建共享首选项。在应用程序的开头查询共享首选项int值(例如)。如果它是第一次启动,我们会得到默认的0值,我们更改共享首选项值,这有助于我们跟踪它不是第一次在应用程序的未来启动时启动。

SharedPreferences pref = 
getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE); 
Editor editor = pref.edit();

在你的飞溅中(或在任何需要的地方)检查共享偏好的特定键,如下所示:

//Check for the key "tracker", if it does not exist consider the default value as 0
int appStartTracker = pref.getInt("tracker", 0);
if(appStartTracker == 0){
    // It means you started the app for the first time. Do what you have to
    // and set the preference to 1 or increment the appStartTracker to keep 
    //track of how many times the app has been started.
    appStartTracker++;
    editor.putInt("tracker", appStartTracker); 
    editor.commit(); 
}else{
    // Not a first time start.
    //Do the following if you need to keep track of total app starts else ignore
    appStartTracker++;
    editor.putInt("tracker", appStartTracker); 
    editor.commit(); 
    Log.d("TAG", "App has been started for the " + appStartTracker +"time");
}

P.S当用户清除数据时,共享首选项被清除。