SharedPreference的应用

来源:互联网 发布:大数据交易中心 编辑:程序博客网 时间:2024/06/03 18:32

1.自动登录前检测保存帐号

 /**   * Auto login when sp user exists   *   * @return   */  public static boolean checkExistUser(Context mContext) {      SharedPreferences sp = mContext.getSharedPreferences(SP_ACCOUNT_INFO, Context.MODE_PRIVATE);      String account = sp.getString(CUR_ACCOUNT, null);      String nickname = sp.getString(CUR_NICKNAME, null);      String img = sp.getString(CUR_AVATAR, null);      if (account == null || nickname == null) {          return false;      } else {          currentUser = new Owner();          currentUser.setName(account);          currentUser.setNick(nickname);          currentUser.setImg(img == null ? "default" : img);          return true;      }  }

2.登录成功后保存或更新现有的帐号信息

   /**    * Remember current user when new account login    *    * @param user    */   public static void setCurrentUser(Context mContext, Owner user) {       currentUser = user;       SharedPreferences sp = mContext.getSharedPreferences(SP_ACCOUNT_INFO, Context.MODE_PRIVATE);       SharedPreferences.Editor editor = sp.edit();       editor.putString(CUR_ACCOUNT, currentUser.getName());       editor.putString(CUR_NICKNAME, currentUser.getNick());       editor.putString(CUR_AVATAR, currentUser.getImg());       editor.commit();   }

1.可在应用首页的onCreate方法中调用checkExistUser方法检测,如果返回为false则跳转至登录页面。
2.也可在登录页面的onCreate方法中调用checkExistUser方法检测,如果返回为true则直接跳转至应用首页。
3.退出帐号方法中写清空SharedPreference操作,以免退出后仍自动登录。

0 0