android 多用户之间userid和username之间判断处理;

在研发过程中,由于系统增加了多用户这个模块,需要通过userID或useName来区分当前处于那个空间,做些不同处理,为后续使用,就做些笔记,望有些帮助:

下面来看一下封装类;

package com.android.systemui.statusbar.phone.vargocontainer.mode;

import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.UserInfo;
import android.os.UserHandle;
import android.os.UserManager;

/**
 * Created by yuanjl
 */

public class WorkUserName {
    //本地定义的action和包名,可对应自己的工作目录进行修改;
    public String workAction = "com.work.name.action.openwork";
    public String workPackageName = "com.work.name";

   //这个用户其实是内部以定义好的用户名称,我们只是在这里定义,编于我们直接可取对应的用户进行判断;
    private String workName = "用户1";

    private final Context mContext;

    public WorkUserName(Context context) {
        this.mContext = context;
    }
    //此方法是用来获取当前用户名字;
    public String getSystemWrokName() {
        UserManager userManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
        UserInfo systemWrokName = userManager.getUserInfo(SystemUserId());
        return systemWrokName.name;
    }
  //此方法是在startActivityAsUser()时启动不同空间的app或activity,;
    public UserHandle getUserHandle() {
        return UserHandle.of(SystemUserId());
    }
   //此方法用来获取当前用户id;
    public int SystemUserId() {
        return ActivityManager.getCurrentUser();
    }
  //此方法用来对当前用户进行判断,查看是否是主空间;
    public boolean isWrokName() {
        return getSystemWrokName().equals(workName) || SystemUserId() == 0;
    }
  //用来判断非主空间时,是否是"用户1"空间;
    public boolean noWrokName() {
        return SystemUserId() != 0 && !(getSystemWrokName().equals(workName));
    }
}

简单看一下如何使用;

//先获取对象;
mUsesName = new WorkUserName(mContext);
//简单的实例,通过clickListener来进行监听;
holder.itemView.setOnClickListener(new View.OnClickListener() {
            public Intent intent;

            @Override
            public void onClick(View v) {
                try {
                    intent = new Intent();
                    intent.setPackage(mUserName.workPackageName);
                    intent.setAction(mUserName.workAction);
                    //这部分就是来进行判断当前处于那个用户空间,可根据个人需求进行判断;
                     if (mUsesName.isWrokName()) {
                    intent.putExtra("target", "work");
                  } else if (mUsesName.noWrokName()) {
                    intent.putExtra("target", "lord");
                  }
                    context.startActivityAsUser(intent, mUserName.getUserHandle());
                } catch (Exception e) {
                    Log.w(TAG, "onClick to work APP: " + e.toString());
                }
            }
        });

以上就算ok了;

你可能感兴趣的:(android,研发,多用户,android,调查)