java - 如何在仅首次打开时将变量设置为 0

标签 java android android-studio

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

最佳答案

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

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 当用户清除数据时,共享首选项也会被清除。

关于java - 如何在仅首次打开时将变量设置为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48362491/

相关文章:

android - 我应该使用 Google Volley 而不是 AsyncTask

android-studio - 如何在生成签名的 apk 之前运行测试?

android - Android Studio 1.4 中新的 content_xxxxx.xml 布局文件

java - 使用 POI 读取/写入非常大的 pptx 文件

java - 接收从适配器到 Fragment 的回调

具有最高优先级的Java线程不会被执行

java - 无法尝试实现从查询中获取随机结果到 Firestore

安卓工作室 : auto build like Eclipse

java - Android 从 url 播放 mp3

java - 在没有jdk或jre的机器上运行.jar文件