如何使用Android偏好设置创建一次性欢迎屏幕?

Ci3*_*Ci3 2 android version sharedpreferences

我想创建一个只在应用程序启动后显示一次的屏幕.之后,它只会显示主屏幕.我实现这个的方法只是检查首选项并根据标志设置当前布局.有没有以这种方式实施它的缺点?有没有更好的办法?

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //Here is the main layout
        setContentView(R.layout.main);      

        mPrefs = PreferenceManager.getDefaultSharedPreferences(this);

        // second argument is the default to use if the preference can't be found
        Boolean welcomeScreenShown = mPrefs.getBoolean(welcomeScreenShownPref, false);

        if (!welcomeScreenShown) {
            //Here I set the one-time layout
            setContentView(R.layout.popup_message);             
            SharedPreferences.Editor editor = mPrefs.edit();
            editor.putBoolean(welcomeScreenShownPref, true);
            editor.commit(); // Very important to save the preference
        }
    }
Run Code Online (Sandbox Code Playgroud)

Anu*_*shA 6

尝试应用程序版本代码.下面是我使用的示例代码;

    SharedPreferences sharedPreferences = getSharedPreferences("version", 0);
    int savedVersionCode = sharedPreferences.getInt("VersionCode", 0);

    int appVershionCode = 0;

    try {
        appVershionCode = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;

    } catch (NameNotFoundException nnfe) {
        Log.w(TAG, "$ Exception caz of appVershionCode : " + nnfe);
    }   

    if(savedVersionCode == appVershionCode){
        Log.d(TAG, "$$ savedVersionCode == appVershionCode");
    }else{
        Log.d(TAG, "$$ savedVersionCode != appVershionCode");

        SharedPreferences.Editor sharedPreferencesEditor = sharedPreferences.edit();
        sharedPreferencesEditor.putInt("VersionCode", appVershionCode);
        sharedPreferencesEditor.commit();

        Builder alertDialogBuilder = new Builder(this);
        alertDialogBuilder.setTitle("Version");
        alertDialogBuilder.setMessage("This is one time show dialog box ");

        alertDialogBuilder.setNeutralButton("Close", new OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                Log.d(TAG, "$$ onClick");

            }
        });

        alertDialogBuilder.show();
    }
Run Code Online (Sandbox Code Playgroud)