您的位置:首页 > Web前端

简单利用SharedPreferences实现直接登录

2015-09-10 16:41 411 查看
通常情况下,用户使用手机App的时候,在填写用户名和密码登录之后,以后再打开软件时,都会直接登录到该账号,并不需要再次填写登录信息(一些安全系数较高的金融类软件,以及自行取消“自动登录”功能的情况除外)。

今天看公司项目,发现实现原理很简单,就是将账号信息通过SharedPreferences保存到本地,每次启动程序时候,取出其中的内容,判断是否是登录状态。于是我也简单的实现了这个功能。

一共两个界面:首先是输入用户名密码的界面,所有逻辑实现均在该页面实现,第二个页面只是一个空白的activity,直接新建,不用做任何处理,只是供跳转使用。

登陆界面的布局很简单:

<LinearLayout
android:id="@+id/l1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="用户名:"/>
<EditText
android:layout_width="80dp"
android:layout_height="40dp"
android:hint="¥¥¥¥¥"
android:id="@+id/et_username" />
</LinearLayout>

<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_centerHorizontal="true"
android:layout_below="@id/l1">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="密    码:" />
<EditText
android:layout_width="80dp"
android:layout_height="40dp"
android:hint="¥¥¥¥¥"
android:id="@+id/et_password" />
</LinearLayout>

<Button
android:layout_above="@id/l1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btn"
android:text="登陆"
/>

逻辑实现代码(activity)如下:

public class MainActivity extends Activity {

private Button btn_ok;
private EditText et_name , et_code;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
if (isLogin()){
Intent intent = new Intent(this , AfterLoginActivity.class);
startActivity(intent);
finish();
} else {
Toast.makeText(this , "输入用户名和密码后再登陆!!!",Toast.LENGTH_SHORT).show();
}
btn_ok.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
login();
}
});

}

private void login(){
if ("张三".equals(et_name.getText().toString()) && "333".equals(et_code.getText().toString())){
SharedPreferences sp  = getSharedPreferences("has",MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putBoolean("OK",true);
editor.commit();
Intent intent = new Intent(this , AfterLoginActivity.class);
startActivity(intent);
finish();
}
}

private void initView(){
btn_ok = (Button)findViewById(R.id.btn);
et_name = (EditText)findViewById(R.id.et_username);
et_code = (EditText)findViewById(R.id.et_password);
}

private boolean isLogin(){
boolean hasLogin = false;
SharedPreferences sp = this.getSharedPreferences("has",MODE_PRIVATE);
hasLogin = sp.getBoolean("OK",false);
return hasLogin;
}
}


这是个一次性程序,当你首次填写登陆信息(“张三”,“333”)之后,页面会直接跳转到AfterLoginActivity,并且本地的sharedpreferences也被修改为已经登陆的状态,当然,改完后,我没有进行修改为“未登陆”状态的机制,所以当你下次打开这个程序后,只会进入到第二页面,登录页面是进不去了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: