2023-03-13

import android.Manifest;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Environment;
import android.os.Looper;
import android.os.PowerManager;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import com.vrv.imsdk.VIMClient;
import com.vrv.imsdk.api.Constants;
import com.vrv.imsdk.bean.LoginInfo;
import com.vrv.imsdk.model.ConfigApi;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import java.util.TimeZone;

import static android.content.Context.MODE_PRIVATE;

/**

  • 工具类 Utility Type
    /
    public class SDKUtils {
    //预登录会返回维护模式,把这个剔除在外,就是有效的预登录数据
    private static Map<String,String> preloginJsonMapValid = new HashMap<>();
    private static Map<String,String> preloginJsonMap = new HashMap<>();
    private static final String TAG = SDKUtils.class.getSimpleName();
    public static final String LOGIN_KEY_SERVER = "login_key_server";
    public static final String LOGIN_KEY_EXINFO = "login_key_exinfo";
    /
    *

    • 是否是小米应用市场的包
      /
      public static boolean isXiaomiMarket = false;
      static {
      if(preloginJsonMapValid == null){
      preloginJsonMapValid = new HashMap<>();
      }
      }
      /
      *
    • 分隔符:逗号
      */
      public static final String SEPARATOR_COMMA = ",";

    public static final String DEVICE_TYPE = SDKUtils.class.getSimpleName()+"_DEVICE_TYPE";

    public static Map<String, String> getPreloginJsonMap() {
    if(preloginJsonMap == null){
    preloginJsonMap = new HashMap<>();
    }
    return preloginJsonMap;
    }

    public static void setPreloginJsonMap(Map<String, String> preloginMap) {
    preloginJsonMap = preloginMap;
    }

    public static void setPreloginJsonToMap(String key,String value) {
    if(preloginJsonMap!=null && !TextUtils.isEmpty(key) && !TextUtils.isEmpty(value)){
    preloginJsonMap.put(key,value);
    }
    }

    public static void clearPreloginJsonMap(){
    if(preloginJsonMap!= null){
    preloginJsonMap.clear();
    }
    clearPreloginJsonMapValid();
    }

    public static void deletePreloginJsonByServer(String server){
    try{
    if(preloginJsonMap!= null && preloginJsonMap.containsKey(server)){
    Iterator<Map.Entry<String,String>> it = preloginJsonMap.entrySet().iterator();
    while (it.hasNext()){
    Map.Entry<String,String> entry = it.next();
    String key = entry.getKey();
    if (key!=null && key.equals(server)){
    it.remove();
    }
    }
    }
    deletePreloginJsonByServerValid(server);
    }catch (Exception e){
    VIMLog.i(TAG, "deletePreloginJsonByServer error");
    };

    }

public static Map<String, String> getPreloginJsonMapValid() {
    if(preloginJsonMapValid == null){
        preloginJsonMapValid = new HashMap<>();
    }
    return preloginJsonMapValid;
}


public static void clearPreloginJsonMapValid(){
    if(preloginJsonMapValid!= null){
        preloginJsonMapValid.clear();
    }
}

public static void deletePreloginJsonByServerValid(String server){
    try{
        if(preloginJsonMapValid!= null && preloginJsonMapValid.containsKey(server)){
            Iterator<Map.Entry<String,String>> it = preloginJsonMapValid.entrySet().iterator();
            while (it.hasNext()){
                Map.Entry<String,String> entry = it.next();
                String key = entry.getKey();
                if (key!=null && key.equals(server)){
                    it.remove();
                }
            }
        }
    }catch (Exception e){
        VIMLog.i(TAG, "deletePreloginJsonByServerValid  error");
    };

}


/**
 * 获取sd根路径 Obtain sd root path
 *
 * @return
 */
public static String getSDPath() {
    // 判断SDCard是否存在
    /*boolean sdcardExist = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);  //沙箱变动路径
    if (sdcardExist) {
        return Environment.getExternalStorageDirectory() + File.separator;
    }*/
    return ConfigApi.getRootPath();
}

/**
 * 获取sd根路径 Obtain sd root path,jssdk仍然要用外部存储
 *
 * @return
 */
public static String getOldSDPath() {
    // 判断SDCard是否存在
    boolean sdcardExist = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    if (sdcardExist) {
        return Environment.getExternalStorageDirectory() + File.separator;
    }
    return null;
}

/**
 * 判断是否有WIFI Determine if WIFI is available
 *
 * @param context
 * @return
 */
public static boolean isNetwork(Context context) {
    ConnectivityManager connectivityManager = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
    return networkInfo != null && networkInfo.isAvailable();
}

/**
 * 版本号 Version code
 *
 * @param context
 * @return
 */
public static final int getVersionCode(Context context) {
    int versionCode = 0;
    try {
        PackageManager manager = context.getPackageManager();
        PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
        versionCode = info.versionCode;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return versionCode;
}

//签名证书解析
public static String getCertificate(Context context){
    try {
        PackageInfo packageInfo = context.getPackageManager().
                getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES);
        Signature[] signatures = packageInfo.signatures;
        if (signatures == null || signatures.length <= 0) {
            return "";
        }
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        ByteArrayInputStream stream = new ByteArrayInputStream(signatures[0].toByteArray());
        X509Certificate cert = (X509Certificate) cf.generateCertificate(stream);
        String subjectDN = cert.getSubjectDN().getName();
        if (TextUtils.isEmpty(subjectDN)){
            return "";
        }
        if (subjectDN.contains(",")){
            String[] subjects = subjectDN.split(",");
            for (String subject: subjects) {
                String[] values = subject.split("=");
                if ("O".equals(values[0])){
                    return values[1];
                }
            }
        }else if(subjectDN.startsWith("O=") ){
            String[] subjects = subjectDN.split("=");
            if( subjects.length == 2){
                return subjects[1];
            }
        }else{

        }
        /*Log.d(TAG,"signName:" + cert.getSigAlgName());//算法名
        Log.d(TAG,"pubKey:" + cert.getPublicKey().toString());//公钥
        Log.d(TAG,"signNumber:" + cert.getSerialNumber().toString());//证书序列编号
        Log.d(TAG,"subjectDN:" + cert.getSubjectDN().toString());//所有者
        Log.d(TAG,"IssuerDN" + cert.getIssuerDN().toString());//发行者
        Log.d(TAG,cert.getNotAfter() + "--" + cert.getNotBefore());*/
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }  catch (CertificateException e) {
        e.printStackTrace();
    } catch (Exception e){
        e.printStackTrace();
    }
    return "";
}

/**
 * 根据类型获取签名信息
 * @param context
 * @param type
 * @return
 */
public static String getSignInfoByType(Context context, String type) {
    try {
        PackageInfo packageInfo = context.getPackageManager().
                getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES);
        Signature[] signatures = packageInfo.signatures;
        if (signatures == null || signatures.length <= 0){
            return "";
        }
        byte[] certBytes = signatures[0].toByteArray();
        MessageDigest digest = MessageDigest.getInstance(type);
        byte[] publicKey = digest.digest(certBytes);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < publicKey.length; i++) {
            String appendString = Integer.toHexString(0XFF & publicKey[i]).toUpperCase(Locale.US);
            if (appendString.length() == 1){
                sb.append("0");
            }
            sb.append(appendString);
            if (i < publicKey.length - 1){
                sb.append(":");
            }
        }
        return sb.toString();
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return "";
}

/**
 * 应用版本名 App version name
 *
 * @param context
 * @return
 */
public static final String getAppVersionName(Context context) {
    String versionName = null;
    try {
        // 获取PackageManager的实例
        PackageManager packageManager = context.getPackageManager();
        // getPackageName()是你当前类的包名,0代表是获取版本信息
        PackageInfo packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
        versionName = packInfo.versionName;
        /*if (versionName.endsWith("-debug")){
            versionName=versionName.replace("-debug","");
        }*/
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
    return versionName;
}

/**
 * 网络类型 Network Type
 *
 * @param context
 * @return
 */
public static final String getNetTypeName(Context context) {
    ConnectivityManager manager = (ConnectivityManager) context.getSystemService(
            Context.CONNECTIVITY_SERVICE);
    NetworkInfo info = manager.getActiveNetworkInfo();
    if (info != null) {
        return info.getTypeName();
    }
    return "";
}

/**
 * 获取本地系统语言 Obtain language of local system
 *
 * @param context
 * @return
 */
public static final String getLocalLanguage(Context context) {
    //参考wiki { http://192.168.166.166/doku.php?id=wiki:%E8%AF%AD%E8%A8%80%E7%B1%BB%E5%9E%8B }
    String language = context.getResources().getConfiguration().locale.toString().toLowerCase();
    //马来西亚特殊处理
    if (language.equals("ms_my")) {
        return "en_my";
    }
    return language;
}

/**
 * Mac地址 MAC address
 *
 * @return
 */
public static final String getMac(Context context) {
    String macAddress = "";
    WifiManager wifiMgr = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    WifiInfo info = (null == wifiMgr ? null : wifiMgr.getConnectionInfo());
    if (null != info) {
        macAddress = info.getMacAddress();
    }
    return macAddress;
}

/**
 * @return 获取手机系统时区*4
 * Obtain mobile system timezone *4
 * 例如+8==32,-4=-16,当前为东八区timeZone =32
 */
public static byte getTimeZone() {
    TimeZone timeZone = TimeZone.getDefault();
    return (byte) (4 * (timeZone.getRawOffset() / 60000 / 60));
}

public static String getPhoneUniqueCode(Context context,boolean istre) {
    StringBuilder sb = new StringBuilder();
    boolean isUserAllowed = isUserAllow(context);
    VIMLog.i("init istre:" +istre +" os:"+ Build.VERSION.SDK_INT+",isUserAllowed==" +isUserAllowed);
    if(isUserAllowed){
        final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        String imei = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//23动态申请权限
            if (context.checkSelfPermission(Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
                VIMLog.i("init istre:" +istre +" isGranted:"+ true);
                try {
                    if(Build.VERSION.SDK_INT < Build.VERSION_CODES.O){//小于8.0系统
                        imei = tm.getDeviceId();
                    }
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && Build.VERSION.SDK_INT < 29) {//8.0-----10.0系统
                        imei =  tm.getDeviceId();
                        VIMLog.i("init istre:" +istre +", getDeviceId(), imei == "+ imei);
                    /*if(TextUtils.isEmpty(imei)){
                        imei = tm.getImei();
                        VIMLog.i("init istre:" +istre +",getImei() ,imei == "+ imei);
                    }
                    if(TextUtils.isEmpty(imei)){
                        imei = tm.getMeid();
                        VIMLog.i("init istre:" +istre +" getMeid , imei == "+ imei);
                    }*/
                    }
                    if (Build.VERSION.SDK_INT >= 29) {//大于等于10.0系统,10.0之后的系统getDeviceId(),getImei(),getMeid() 会报java.lang.SecurityException
                        imei = null;
                    }
                }catch (Exception e) {
                    VIMLog.i("init istre:" +istre +" throw exception:"+ e.getMessage());
                }
            }else{
                VIMLog.i("init istre:" +istre +" isGranted:"+ false);
            }
        }else{
            imei = tm.getDeviceId();
        }

        VIMLog.i("init istre:" +istre +" imei:"+imei);

        String androidId = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
        if (!TextUtils.isEmpty(androidId)) {
            sb.append(androidId);
        }
        VIMLog.i(TAG+",getPhoneUniqueCode(),init istre:" +istre +" androidId:" + androidId);
        if (!TextUtils.isEmpty(imei)) {
            sb.append(imei);
        }

        if (Build.VERSION.SDK_INT > 8) {
            String serial = Build.SERIAL ;
            VIMLog.i("init istre:" +istre +" SERIAL:"+ serial);
            if (!TextUtils.isEmpty(serial)) {
                sb.append(Build.SERIAL);
            }
        }
    }
    /*if (istre) {
        try {
            imei = tm.getDeviceId();
        }catch (Exception e) {

        }
    }*/

    /*String androidId = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
    StringBuilder sb = new StringBuilder();
    if (!TextUtils.isEmpty(androidId)) {
        sb.append(androidId);
    }
    VIMLog.i("init istre:" +istre +" androidId:" + androidId);
    if (!TextUtils.isEmpty(imei)) {
        sb.append(imei);
    }*/

    return sb.toString();
}
public static  boolean isUserAllow(Context context){
    //VIVO市场豆豆第一次安装启动,会弹出温馨提示,欢迎使用信源密信...... 里面有用户协议和隐私政策,vivo市场政策不让过,
    //APP以隐私政策弹窗的形式向用户明示收集使用规则,未经用户同意,存在收集设备MAC地址、IMEI等信息的行为

    final String SHAREDPREFERENCES_NAME = "linkdood_pref";//和IMApp里面的变量同名
    boolean firstStart = false;//兼容老版本升上去,是不是第一次使用豆豆
    boolean agreedPolicyPrivacy = false;//新版本用这个字段,是不是同意了用户协议和隐私政策
    //boolean isXiaomiSecondAgreedPolicyPrivacy = false; //登录/注册前,请先设置服务器,我已阅读并同意隐私政策和服务协议
    try {
        SharedPreferences sharedPreferences = context.getSharedPreferences(SHAREDPREFERENCES_NAME, MODE_PRIVATE);
        firstStart = sharedPreferences.getBoolean("isFirstGuide", true);
        agreedPolicyPrivacy = sharedPreferences.getBoolean("agreedPolicyPrivacy", false);

        //isXiaomiSecondAgreedPolicyPrivacy = sharedPreferences.getBoolean(xiaomiSecondAgreedPolicyPrivacy, false);
    }catch (Exception e){
        VIMLog.i(TAG+","+"ex,firstStartValue:" +firstStart);
    }
    boolean isUserAllowed = false;
        /*if(SDKUtils.isXiaomiMarket){
            if(isAppFirstInstall(context) && !isXiaomiSecondAgreedPolicyPrivacy){
                isUserAllowed = false;
            }else{
                isUserAllowed = true;
            }
        }else*/ if(agreedPolicyPrivacy){
        isUserAllowed = true;

    }else if(firstStart){

    }else{
        isUserAllowed = true;
    }
    if(SDKUtils.isXiaomiMarket){

    }else if(!Build.MANUFACTURER.equalsIgnoreCase("vivo")){//非vivo没有这个政策
        isUserAllowed = true;
    }
    VIMLog.i(TAG+",isUserAllow(),init istre"+"firstStartValue:" +firstStart+",agreedPolicyPrivacy:" +agreedPolicyPrivacy+",isUserAllowed:" +isUserAllowed+",Build.MANUFACTURER:"+Build.MANUFACTURER);
    return  isUserAllowed;
}
/**
 * 登录时需要的设备信息
 * Device information required during login
 *
 * @return
 */
public static final String getDeviceInfo() {
    StringBuilder sb = new StringBuilder("an-");
    sb.append(android.os.Build.MODEL);
    sb.append("#");
    sb.append(android.os.Build.VERSION.RELEASE);
    sb.append("#");
    sb.append(getLocalLanguage(VIMClient.getContext()));
    return sb.toString();
}

/**
 * MD5
 *
 * @param str
 * @return
 */
public static String md5(String str) {
    if (str == null) {
        return null;
    }
    try {
        MessageDigest algorithm = MessageDigest.getInstance("MD5");
        algorithm.reset();
        algorithm.update(str.getBytes());
        return hexString(algorithm.digest());
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        return str;
    }
}

private static String hexString(byte[] bytes) {
    assert bytes != null;
    StringBuilder hexString = new StringBuilder();
    for (byte b : bytes) {
        if (b >= 0 && b <= 0xF) {
            hexString.append("0");
        }
        hexString.append(Integer.toHexString(0xFF & b));
    }
    return hexString.toString().toLowerCase();
}

/**
 * 删除文件
 * Delete File
 *
 * @param file
 */

public static void deleteFile(File file) {
    if (file == null || !file.exists()) {
        return;
    }
    if (file.isDirectory()) {
        File[] childFiles = file.listFiles();
        if (childFiles == null || childFiles.length == 0) {
            //                file.delete();
            return;
        }
        for (int i = 0; i < childFiles.length; i++) {
            deleteFile(childFiles[i]);
        }
        //            file.delete();
    } else {
        file.delete();
    }
}

/**
 * 生成16位密码 Generate 16 bit password
 *
 * @return
 */
public static String make16EncryptKey() {
    final int length = 16;
    char[] data = new char[length];
    for (int i = 0; i < length; i++) {
        switch (Math.abs(new Random().nextInt() % 3)) {
            case 0:
                data[i] = (char) ('A' + Math.abs(new Random().nextInt() % 26));
                break;
            case 1:
                data[i] = (char) ('a' + Math.abs(new Random().nextInt() % 26));
                break;
            case 2:
                data[i] = (char) ('0' + Math.abs(new Random().nextInt() % 10));
                break;
            default:
                break;
        }
    }
    return String.valueOf(data);
}

/**
 * 获取文件名 Obtain file name
 *
 * @param filePath
 * @return
 */
public static String getFileNameByPath(String filePath) {
    if (TextUtils.isEmpty(filePath)) {
        return "";
    }
    if (!filePath.contains(File.separator)) {
        return filePath;
    }
    if (filePath.lastIndexOf(File.separator) >= filePath.length()) {
        return filePath;
    }
    return filePath.substring(filePath.lastIndexOf(File.separator) + 1);
}

/**
 * 判断屏幕是否开着 Determine if screen is on
 *
 * @param context
 * @return
 */
public static boolean isScreenOn(Context context) {
    PowerManager pm = ((PowerManager) context.getSystemService(Context.POWER_SERVICE));
    return pm.isScreenOn();
}

/**
 * 判断程序是否前台 Determine is program is running on screen
 *
 * @param context
 * @return
 */
public static boolean isRunningForeground(Context context) {
    ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    String currentPackageName = "";
    List<ActivityManager.RunningTaskInfo> infos =  am.getRunningTasks(1);
    if(infos != null && infos.size() >0 ){
        ComponentName cn = infos.get(0).topActivity;
        currentPackageName = cn.getPackageName();
    }
    return !TextUtils.isEmpty(currentPackageName) && currentPackageName.equals(context.getPackageName());
}

/**
 * 判断程序是否后台 Determine if program is running in background
 *
 * @param context
 * @return
 */
public static boolean isBackground(Context context) {
    ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
    for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
        if (appProcess.processName.equals(context.getPackageName())) {
            return appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
        }
    }
    return false;
}

/**
 * 网络检测 Network Verification
 */
public static void pingNet() {

// VIMLog.i("PING", "--->pingNet: test---");
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
return;
}
Runnable pingRunnable = new Runnable() {
@Override
public void run() {
final String ip = "www.baidu.com";// ping 的地址,可以换成任何一种可靠的外网
InputStream input = null;
BufferedReader in = null;
try {
Process p = Runtime.getRuntime().exec("ping -c 1 -w 100 " + ip);
// 读取ping的内容,可以不加
input = p.getInputStream();
in = new BufferedReader(new InputStreamReader(input));
StringBuffer stringBuffer = new StringBuffer();
String content;
while ((content = in.readLine()) != null) {
stringBuffer.append(content);
}
// VIMLog.i("PING", "--->ping result: " + stringBuffer.toString());
// ping的状态
int status = p.waitFor();
if (status == 0) {
VIMLog.i("PING", "--->ping: net connect");
} else {
VIMLog.i("PING", "--->ping: net disConnect");
}
} catch (Exception e) {
} finally {
try {
if (input != null) {
input.close();
input = null;
}
}catch (Exception e) {}

                try {
                    if (in != null) {
                        in.close();
                        in = null;
                    }
                }catch (Exception e) {}
            }
        }
    };
    new Thread(pingRunnable).start();
}

/**
 * 判断当前线程是否是主线程 Determine if current thread is primary thread
 *
 * @return
 */
public static boolean isMainProcess() {
    boolean main = Thread.currentThread() == Looper.getMainLooper().getThread();
    if (!main) {
        VIMLog.e(TAG, "This process is not mainProcess");
    }
    return main;
}

/**
 * 通过分隔符 将String转成List<Long>
 *
 * @param str  需要转换的String
 * @param sepa 分隔符(为null的话,则使用逗号作为分隔符)
 * @return 成功:返回List<Long>, 失败:返回null
 */
public static List<Long> str2Longs(String str, String sepa) {
    if (sepa == null) {
        sepa = SEPARATOR_COMMA;
    }
    List<Long> longs = null;
    try {
        if (!TextUtils.isEmpty(str)) {
            String[] strs = str.split(sepa);
            if (strs != null && strs.length > 0) {
                longs = new ArrayList<Long>();
                for (String temps : strs) {
                    longs.add(Long.valueOf(temps));
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        longs = null;
    }
    return longs;
}


/**
 * 通过分隔符 将List<Long>转成String
 *
 * @param longs 需要转换的List<Long>
 * @param sepa  分隔符(为null的话,则使用逗号作为分隔符)
 * @return 成功:返回String,失败:返回null
 */
public static String longs2Str(List<Long> longs, String sepa) {
    if (sepa == null) {
        sepa = SEPARATOR_COMMA;
    }
    String str = null;
    try {
        if (longs!= null && longs.size()>0) {
            StringBuffer sb = new StringBuffer("");
            for (Long templ : longs) {
                sb.append(templ);
                sb.append(sepa);
            }
            str = sb.substring(0, sb.length() - sepa.length());
        }
    } catch (Exception e) {
        e.printStackTrace();
        str = null;
    }
    return str;
}


public static String listToString(List list, String separator) {
    if (separator == null) {
        separator = SEPARATOR_COMMA;
    }
    StringBuilder sb = new StringBuilder();
    if(list != null && list.size() > 0){
        for (int i = 0; i < list.size(); i++) {
            if (i == list.size() - 1) {
                sb.append(list.get(i));
            } else {
                sb.append(list.get(i));
                sb.append(separator);
            }
        }
    }
    return sb.toString();
}

/**
 * 通过分隔符 将String转成List<Long>
 *
 * @param str  需要转换的String
 * @param sepa 分隔符(为null的话,则使用逗号作为分隔符)
 * @return 成功:返回List<Long>, 失败:返回null
 */
public static List<String> str2List(String str, String sepa) {
    if (sepa == null) {
        sepa = SEPARATOR_COMMA;
    }
    List<String> strings = null;
    try {
        if (!TextUtils.isEmpty(str)) {
            String[] strs = str.split(sepa);
            if (strs != null && strs.length > 0) {
                strings = new ArrayList<String>();
                for (String temps : strs) {
                    strings.add(temps);
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        strings = null;
    }
    return strings;
}
/**
 * 是不是平板
 *
 * @param context
 * @return
 */
public static boolean isTabletDevice(Context context) {
    boolean b = (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >=
            Configuration.SCREENLAYOUT_SIZE_LARGE;
    if(b){
        VIMLog.i(TAG + ",isTabletDevice()," + b + "," + context.getClass().getSimpleName());
    }
    return b;
}
public static String e2S(Exception ex) {
    Writer writer = new StringWriter();
    PrintWriter printWriter = new PrintWriter(writer);
    ex.printStackTrace(printWriter);
    Throwable cause = ex.getCause();
    while (cause != null) {
        cause.printStackTrace(printWriter);
        cause = cause.getCause();
    }
    printWriter.close();
    String result = writer.toString();
    return result;
}

/**
 * 当前使用的设备类型
 * @return
 */
public static int getDeviceType(){
    int deviceType = Constants.DEVICE_PHONE;
    try {
         //deviceType = SharedPreferenceUtils.getSharePreferenceInstance().getInt(DEVICE_TYPE);
         //VIMLog.i(TAG+",getDeviceType(),sharePreferenceInstance deviceType==" +deviceType);
         //if(deviceType != Constants.DEVICE_PHONE &&  deviceType != Constants.DEVICE_PAD ){
             deviceType = isTabletDevice(VIMClient.getContext()) ? Constants.DEVICE_PAD :Constants.DEVICE_PHONE;
             //VIMLog.i(TAG+",getDeviceType(),not phone, pad,deviceType==" +deviceType);
        // }
    }catch (Exception e){
        VIMLog.i(TAG +",getDeviceType(),ex==" + e2S(e));
    }finally {
        return deviceType;
    }
}
public static byte getDeviceTypeByte(){
    return  (byte) getDeviceType();
}

public static boolean accountIsExistBeforeLogin(List<LoginInfo> loginInfos,long userId,String server){
    if(userId == 0 || TextUtils.isEmpty(server)){
        VIMLog.d(TAG,",accountIsExistBeforeLogin null server:"+server);
        return false;
    }

    try {
        String elogo = JsonToolHelper.getElogo(server,userId);
        if(loginInfos != null && loginInfos.size() > 0){
            for(LoginInfo loginInfo : loginInfos){
                if(loginInfo != null && loginInfo.getUserID() == userId && (loginInfo.getServer().equals(server) || JsonToolHelper.getElogo(loginInfo.getServer(),loginInfo.getUserID()).equals(elogo))){
                    return true;
                }
            }
        }
    }catch (Exception e){
        VIMLog.d(TAG,",accountIsExistBeforeLogin ,ex=="+e2S(e));
        e.printStackTrace();
    }
    return false;
}

/**
 * 删除文件
 * Delete File
 * @param notDeleteFiles 不删除的文件绝对路径
 * @param file
 */

public static void deleteFile(File file,List<String> notDeleteFiles) {
    if (file == null || !file.exists()) {
        return;
    }
    if (file.isDirectory()) {
        File[] childFiles = file.listFiles();
        if (childFiles == null || childFiles.length == 0) {
            //                file.delete();
            return;
        }
        for (int i = 0; i < childFiles.length; i++) {
            deleteFile(childFiles[i],notDeleteFiles);
        }
        //            file.delete();
    } else {
        if(notDeleteFiles != null && notDeleteFiles.size() > 0){
            if(!notDeleteFiles.contains(file.getAbsolutePath())){
                file.delete();
            }
        }else{
            file.delete();
        }
    }
}

/**
 * debug包获取时间后缀
 * */
public static String getdebugVC(Context context) {
    String debugvc = "";
    try {
        // 获取PackageManager的实例
        PackageManager packageManager = context.getPackageManager();
        ApplicationInfo appInfo = packageManager.getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
        debugvc = appInfo.metaData.getString("DEBUG_VC", "");
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
    return debugvc;
}

}

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 215,923评论 6 498
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,154评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 161,775评论 0 351
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,960评论 1 290
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,976评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,972评论 1 295
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,893评论 3 416
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,709评论 0 271
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,159评论 1 308
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,400评论 2 331
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,552评论 1 346
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,265评论 5 341
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,876评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,528评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,701评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,552评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,451评论 2 352

推荐阅读更多精彩内容