sharedpreferences自动登录

sharedpreferences可以做些什么呢 ?

我们在使用QQ或微信的时候,有没有发现这样一个功能:当我们第一次进入软件的时候,会跳转到登录、注册界面;而当我们在实现了这一步后再次进入软件,则不会出现此界面了,是不是感觉很方便呢。今天我们将要讲的sharedpreferences就可以实现此功能,除此之外,它还可以解决重复打卡重复签到 的功能。

getSharedPreferences()方法

使用getSharedPreferences(String name,int mode)方法可以获取sharedpreferences对象,下面介绍一下此方法的两个参数的意思。

  • name:为本组件的配置文件名( 自己定义,也就是一个文件名)。
  • mode:为操作模式,有三种类型。
mode作用
MODE_PRIVATE则该配置文件只能被自己的应用程序访问
MODE_WORLD_READABLE该配置文件除了自己访问外还可以被其它应该程序读取
MODE_WORLD_WRITEABLE该配置文件除了自己访问外还可以被其它应该程序读取和写入

自动登录的实现

public public class MainActivity extends Activity {
	SharedPreferences share;
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	        setContentView(R.layout.activity_main);
	        Button login_button = (Button) this.findViewById(R.id.login);
	        ButtonListener bl = new ButtonListener(this);
	        login_button.setOnClickListener(bl);
	        FirstOrNot();
	  }
         
	public void FirstOrNot(){
		/**
	      *   得到SharePerferences对象
	      *   getPreferences(String name,int mode)参数:
	      *   name:为本组配置的文件名
	      *   mode:为操作模式,具体自行查看
	      */
		 share = getPreferences(MODE_WORLD_READABLE);
	     //得到登录程序的次数
	     int count = share.getInt("count", 0);
	     if(count>0){
	      //如果不是第一次登录,直接跳转到MenuActivity界面
	      Intent intent = new Intent();
	      intent.setClass(this, MenuActivity.class);
	      this.startActivity(intent);
	     }
	     Editor editor = share.edit();   //得到editor对象
	     editor.putInt("count", ++count);  //修改数据
	     //提交修改
	     editor.commit();
	        }
    
}
		```
	
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

steven_moyu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值