SharedPreferences实现自动登录

来源:互联网 发布:天祥网络 编辑:程序博客网 时间:2024/06/06 07:24

最近在项目中有接触到需要自动登录的,但是短期还不需要数据库,然后这就难倒我了(毕竟还是个新手,哈哈)。

百度了一下,都是那种勾选记住密码丶自动登录才有的,但是我又不需要,然后研究了一下SharedPreferences,写下我的第一篇博客,也算记录我的成长。

至于效果图什么的就不上传了,因为这个比较简单嘛。

下面是实现的代码:

package com.dpttouch.shdong.login;


import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;


public class MainActivity extends AppCompatActivity implements View.OnClickListener {


    EditText user_naem, user_psw;
    Button loginl;
    SharedPreferences sp;
    SharedPreferences.Editor editor;
    //用来判断是否第一次登陆
    boolean isfirstrun;
    String name = "123";
    String psw = "123";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        user_naem = (EditText) findViewById(R.id.user_name);
        user_psw = (EditText) findViewById(R.id.user_psw);
        loginl = (Button) findViewById(R.id.login);
        loginl.setOnClickListener(this);
        //获取SharedPreferences的Context对象
        //第一个参数是文件保存的名称,第二个参数是执行的模式。这里设置为默认
        sp = getSharedPreferences("login", Context.MODE_PRIVATE);
        //设置为第一次登陆
        isfirstrun = sp.getBoolean("isfirstrun", true);
        //获取editor对象
         editor = sp.edit();
        if (!isfirstrun){
            startActivity(new Intent(this,FirstPager.class));
        }
    }

    @Override
    public void onClick(View v) {
        String ed_name = user_naem.getText().toString();
        String ed_psw = user_psw.getText().toString();
        if (ed_name.equals(name) && ed_psw.equals(psw)) {
            editor.putString("user_name",ed_name);
            editor.putString("user_name",ed_psw);
            editor.putBoolean("isfirstrun",false);
            editor.commit();
            startActivity(new Intent(this, FirstPager.class));
            finish();
        }
        else
            Toast.makeText(this,"用户名或密码错误",Toast.LENGTH_SHORT).show();
    }
}

0 0
原创粉丝点击