有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何检查应用程序是否第一次启动

我如何在应用程序第一次启动时让某些事情发生,然后在其他时间让其他事情发生

我需要保存一个Int,但是在第一次保存时它必须是0,之后我必须在我的savedInstanceState包中找到它


共 (2) 个答案

  1. # 1 楼答案

    要检查应用程序的第一次运行,您可以参考以下代码并相应地执行

    公共类MyActivity扩展活动{

    SharedPreferences prefs = null;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Perhaps set content view here
    
        prefs = getSharedPreferences("com.mycompany.myAppName", MODE_PRIVATE);
    }
    
    @Override
    protected void onResume() {
        super.onResume();
    
        if (prefs.getBoolean("firstrun", true)) {
            // Do first run stuff here then set 'firstrun' as false
            // using the following line to edit/commit prefs
            prefs.edit().putBoolean("firstrun", false).commit();
        }
    }
    

    }

  2. # 2 楼答案

    您只需在SharedReference中保存一个值,如下所示

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        SharedPreferences mDefaultPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        if (mDefaultPreferences.getBoolean("first_launch", true))
        {
           mDefaultPreferences.edit().putBoolean("first_launch", false).commit();
           //Put the code here of your first launch
        }
        else
        {
           //Not the first launch
    
        }
    
    }