android使用共享首选项问题

时间:2014-06-04 01:34:26

标签: android sharedpreferences

static int existingCounter;

    Context mContext = SplashScreen.getContextOfApplication();
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);

    public static int cCounter() 
    {       
        MainMenu mm = new MainMenu();
        existingCounter = mm.getExistingCounter();;

    return existingCounter;
    }

    public void setSharedPreferences(int count) 
    {
        SharedPreferences preferences = mContext.getApplicationContext().getSharedPreferences("myCounter", 0);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putInt("existingCount", existingCounter);

        editor.commit();
    }

    //Get value from shared preferences
    public int getExistingCounter() 
    {
        SharedPreferences myPrefs = mContext.getApplicationContext().getSharedPreferences("myCounter", 0);
        myPrefs.getInt("existingCount", 0);

        return existingCounter ;
    }

大家好,上面是我的共享偏好。我想要实现的是当用户第一次启动应用程序时,我的应用程序将引导用户访问免责声明页面,并且在用户同意T& C之后,用户启动应用程序将不再显示免责声明页面。但是,我的当前代码仅在用户永不退出应用程序时有效。如果用户要退出应用并重新启动,我的应用仍会显示免责声明页面。请协助=)提前谢谢。下面是我设置共享偏好的部分:

case 3:
            cCounter();
            if(existingCounter==0)
            {
                changeMenuFrag(new AcknowledgePg());
                existingCounter++;
                setSharedPreferences(existingCounter);
            }
            else
            {
                changeMenuFrag(new GalleryMain());
            }           
            break;

1 个答案:

答案 0 :(得分:0)

在您完成欢迎屏幕后,启动应用程序时,在首选项中保存一个标记。在显示T& C屏幕之前检查此标志。如果标志存在(换句话说,如果它不是第一次),则不要显示它。而不是整数计数器使用布尔标志,并在您的主要活动中检查标志是真还是假,基于显示适当的活动。

SharedPreferences mPrefs;
final String welcomeScreenShownPref = "welcomeScreenShown";

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
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 you can launch another activity if you like


    SharedPreferences.Editor editor = mPrefs.edit();
    editor.putBoolean(welcomeScreenShownPref, true);
    editor.commit(); // Very important to save the preference}

}