SharedPreferences the Android store data and automatically log Log

Use SharedPreferences stored login information

Android SharedPreferences one embodiment for storing data suitable for storing small amounts of data, often used to store configuration information, such as login information.

Stored data

public static int MODE = Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE;
······
SharedPreferences sp = getSharedPreferences("userInfo", MODE);
SharedPreferences.Editor editor = sp.edit();
editor.putString("USER_NAME", name).commit();
editor.putString("ID", String.valueOf(id)).commit();

Take data

SharedPreferences preferences = getSharedPreferences("userInfo", Activity.MODE_PRIVATE);
String username= preferences.getString("USER_NAME", "");
String id= preferences.getString("ID", "");

Userinfo create a class of entities.

public class UserInfo {
    private String userName;
    private String id;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
}

Then create UserManage store user information management classes.

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.util.Log;

public class UserManage {

    private static UserManage instance;

    private UserManage() {

    }

    public static UserManage getInstance() {

        if (instance == null) {

            instance = new UserManage();

        }

        return instance;

    }

    /**

     * 保存自动登录的用户信息

     */

    public void saveUserInfo(Context context, String username, String password) {

        SharedPreferences sp = context.getSharedPreferences("userInfo", Context.MODE_PRIVATE);//Context.MODE_PRIVATE表示SharePrefences的数据只有自己应用程序能访问。

        SharedPreferences.Editor editor = sp.edit();

        editor.putString("USER_NAME", username);//     edit.putString("键名","值");

        editor.putString("ID", id);

        // editor.commit();
        editor.apply();

    }

    public static String takeName(Context context){
        SharedPreferences sharedPreferences=context.getSharedPreferences("usesrInfo",0);
        String  name=sharedPreferences.getString("USER_NAME",null);
        return name;
    }


    /**

     * 获取用户信息model

     *

     * @param context

     * @param

     * @param

     */

    public UserInfo getUserInfo(Context context) {

        SharedPreferences sp = context.getSharedPreferences("userInfo", Context.MODE_PRIVATE);

        UserInfo userInfo = new UserInfo();

        userInfo.setUserName(sp.getString("USER_NAME", ""));

        userInfo.setId(sp.getString("ID", ""));

        return userInfo;

    }

    /**

     * userInfo中是否有数据

     */

    public boolean hasUserInfo(Context context) {

        UserInfo userInfo = getUserInfo(context);

        if (userInfo != null) {

            if ((!TextUtils.isEmpty(userInfo.getUserName())) && (!TextUtils.isEmpty(userInfo.getId()))) {//有数据

                return true;

            } else {

                return false;

            }
        }

        return false;

    }

    public static void clear(Context context) {

        SharedPreferences preferences = context.getSharedPreferences("userInfo", Context.MODE_PRIVATE);

        SharedPreferences.Editor editor = preferences.edit();

        editor.clear();

        editor.commit();
    }

}

If the login is successful store the user login user name and ID retrieved from the database, because often use these two data later in the operation of the operation requires a database, if the process behind the operation of a user to modify the user name can call SharePrefences store data method restocking look, the stored data will be replaced.
SharedPreferences determine whether the data is stored, when the user enters the second APP, to determine if there is data on the home page jumps to APP, if no data is stored on the login page jump. I was the judge in MainActivity.java.

//自动登录判断,SharePrefences中有数据,则跳转到主页,没数据则跳转到登录页
if (UserManage.getInstance().hasUserInfo(this))
        {
            //有数据跳转首页
        } else {
           //无数据跳转登录页
        }

Log operations,
create ActivityCollector class

//管理所有的活动,这个是对于用户退出登录
public class ActivityCollector {
    public static List<Activity> activityList=new ArrayList<>();

    public static void addActivity(Activity activity){
        activityList.add(activity);
    }

    public static void remove(Activity activity){
        activityList.remove(activity);
    }

    public static void finishAll(){
        for (Activity activity:activityList){
            if (!activity.isFinishing()){  //判断activity是否销毁
                activity.finish();   //销毁activity
            }
        }
    }

}

Creating BaseActivity.java parent

public class BaseActivity  extends AppCompatActivity {
    private MyForceExitReceiver receiver;  //声明一个自己的广播接收者内部类

    private MyBaseActiviy_Broad oBaseActiviy_Broad;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityCollector.addActivity(this);
    }
    //定义一个广播
    public class MyBaseActiviy_Broad extends BroadcastReceiver {

        public void onReceive(Context arg0, Intent intent) {
//接收发送过来的广播内容
            int closeAll = intent.getIntExtra("closeAll", 0);
            if (closeAll == 1) {
                finish();//销毁BaseActivity
            }
        }

    }

    /**
     * 在activity处于返回栈顶,即处于焦点时,注册一个广播接收者
     */
    public void onResume(){
        super.onResume();
        IntentFilter intentFilter=new IntentFilter();  //实例化一个intent过滤器
        intentFilter.addAction("com.yuanlp.exit.FORCEXIT");  //只关心自己想要的广播
        receiver=new MyForceExitReceiver();
        registerReceiver(receiver,intentFilter);  //动态注册广播

    }
    public void onPause(){  //当当前activity被弹出框占用时,解除注册
        super.onPause();
        if (receiver!=null){
            unregisterReceiver(receiver);
            receiver=null;
        }
    }
    public void onDestroy(){
        super.onDestroy();
        ActivityCollector.remove(this);
    }

    /**
     * 一个广播接收者,接收到广播后,弹出框提示用户退出登录,
     */
    private class MyForceExitReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(final Context context, final Intent intent) {
            AlertDialog.Builder builder=new AlertDialog.Builder(context);
            builder.setTitle("提示");
            builder.setMessage("确定要退出登录?");
            builder.setCancelable(false); 
            builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    ActivityCollector.finishAll();   //销毁所有活动
                    Intent intent=new Intent(context,LoginActivity.class); //跳转至登录界面
                    context.startActivity(intent);
                }
            });

             builder.setNegativeButton(getResources().getString(R.string.tips_limit_false), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
		//取消按钮
                }
            });
            builder.setCancelable(true);
            builder.show();
        }
    }
}

Log interface, activity_set_user.xml file on a Log button, the code is omitted here.

public class SetUserActivity extends BaseActivity {
    private TextView tvCancel;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_set_user);
        tvCancel = findViewById(R.id.tvCancel);
       //退出登录按钮点击事件
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                UserManage.clear(SetUserActivity.this);
                Intent intent = new Intent("com.exit.FORCEXIT");
                sendBroadcast(intent);  //发送广播
            }
        });
    }
}
Released five original articles · won praise 1 · views 319

Guess you like

Origin blog.csdn.net/weixin_45407364/article/details/104773381
log
log