用SharedPreferences实现的自动登录——————最简单的方法

本文详细介绍如何在Android应用中实现自动登录功能。通过布局文件设置账号密码输入框及自动登录复选框,结合SharedPreferences保存用户选择状态,实现下次启动应用时的自动登录。

1.第一点,你先要有个布局文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/edit_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:hint="请输入账号" />

    <EditText
        android:id="@+id/edit_pwd"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:hint="请输入密码"
        android:password="true" />

    <CheckBox
        android:id="@+id/check_box"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="自动登录" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="login"
        android:text="登录" />

</LinearLayout>

2.第二点,就是在你的activity中实现

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.view.Menu;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;

public class MainActivity extends Activity {

    private EditText edit_name;
	private EditText edit_pwd;
	private CheckBox check_box;
	private SharedPreferences sp;

	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        edit_name = (EditText) findViewById(R.id.edit_name);
        edit_pwd = (EditText) findViewById(R.id.edit_pwd);
        check_box = (CheckBox) findViewById(R.id.check_box);
        sp = getSharedPreferences("config", Context.MODE_PRIVATE);
        boolean flag = sp.getBoolean("flag_auto", false);
        check_box.setChecked(flag);
        if (flag) {
			Intent intent = new Intent(MainActivity.this,ShowActivity.class);
			startActivity(intent);
			finish();
		}
    }
	public void login(View view){
		Editor editor = sp.edit();
		if (check_box.isChecked()) {
			editor.putBoolean("flag_auto", true);
			editor.commit();
		}else{
			editor.putBoolean("flag_auto",false).commit();
		}
		Intent intent = new Intent(MainActivity.this,ShowActivity.class);
		startActivity(intent);
		finish();
	}

}

——————这样就好了,你第二次登录的时候,就可以自动登录了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值