Java 如何仅在第一次打开时将VARABLE设置为0
是否有办法将整数变量设置为0,但它仅在设备第一次打开应用程序时才执行此操作?创建共享首选项。在应用程序开始时查询共享首选项int值(例如)。如果是第一次启动,我们会得到默认的0值,其中我们会更改共享首选项值,这有助于我们跟踪它在应用程序的未来启动中不是第一次启动Java 如何仅在第一次打开时将VARABLE设置为0,java,android,android-studio,Java,Android,Android Studio,是否有办法将整数变量设置为0,但它仅在设备第一次打开应用程序时才执行此操作?创建共享首选项。在应用程序开始时查询共享首选项int值(例如)。如果是第一次启动,我们会得到默认的0值,其中我们会更改共享首选项值,这有助于我们跟踪它在应用程序的未来启动中不是第一次启动 SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE); Editor editor = pref.
SharedPreferences pref =
getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
Editor editor = pref.edit();
在splash(或任何必要的地方)中,检查共享首选项的特定键,如下所示:
//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当用户清除数据时,共享首选项被清除。创建共享首选项。在应用程序开始时查询共享首选项int值(例如)。如果是第一次启动,我们会得到默认的0值,其中我们会更改共享首选项值,这有助于我们跟踪它在应用程序的未来启动中不是第一次启动
SharedPreferences pref =
getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
Editor editor = pref.edit();
在splash(或任何必要的地方)中,检查共享首选项的特定键,如下所示:
//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当用户清除数据时,共享首选项将被清除。是的,在应用程序的首选项中存储该变量在后续启动时应初始化为什么?该变量应为应用程序上一次启动时的值。它是一个“点”变量。我希望第一次将其设置为零,而不是每次都将其设置为零。是的,将此变量存储在应用程序的首选项中。在后续启动时,此变量应初始化为什么?应为上次我们在应用程序上运行时的值。它是一个“点”变量。我希望它第一次设置为零,而不是每次都设置为零。