如何保持登录Android版

时间:2015-04-15 07:53:43

标签: java android

以下是我的SavedSharePreference类:

public class SaveSharedPreference {
    static final String PREF_USER_NAME= "username";

    static SharedPreferences getSharedPreferences(Context ctx) {
        return PreferenceManager.getDefaultSharedPreferences(ctx);
    }

    public static void setUserName(Context ctx, String userName)
    {
        SharedPreferences.Editor editor = getSharedPreferences(ctx).edit();
        editor.putString(PREF_USER_NAME, userName);
        editor.commit();
    }

    public static String getUserName(Context ctx)
    {
        return getSharedPreferences(ctx).getString(PREF_USER_NAME, "");
    }
}

用户必须从MainActivity.java登录。下面的if / else语句位于onCreate方法中。

if(SaveSharedPreference.getUserName(MainActivity.this).length() == 0)
        {
            b = (Button)findViewById(R.id.Button01);
            et = (EditText)findViewById(R.id.username);
            pass= (EditText)findViewById(R.id.password);
            tv = (TextView)findViewById(R.id.tv);
        }
        else
        {
            // Call Next Activity
            Intent myIntent = new Intent(MainActivity.this, UserPage.class);
            myIntent.putExtra("username",et.getText().toString().trim());
            startActivity(myIntent);
        }

每次关闭应用程序并再次打开它时,我都需要再次登录。我应该如何修改代码以使其保持登录状态?

0 个答案:

没有答案
相关问题