content: package cn.hotapk.fastandrutils.utils;
  
  
  import android.annotation.SuppressLint;
  import android.annotation.TargetApi;
  import android.app.AppOpsManager;
  import android.content.ContentResolver;
  import android.content.Context;
  import android.content.res.Configuration;
  import android.database.Cursor;
  import android.net.Uri;
  import android.os.Binder;
  import android.os.Build;
  import android.os.Environment;
  import android.os.SystemClock;
  import android.support.annotation.Nullable;
  import android.telephony.TelephonyManager;
  import android.text.TextUtils;
  import android.util.Xml;
  
  import org.xmlpull.v1.XmlSerializer;
  
  import java.io.File;
  import java.io.FileInputStream;
  import java.io.FileOutputStream;
  import java.lang.reflect.Method;
  import java.util.ArrayList;
  import java.util.HashMap;
  import java.util.List;
  import java.util.Properties;
  import java.util.regex.Matcher;
  import java.util.regex.Pattern;
  
  /**
   * @author laijian
   * @version 2017/9/20
   * @Copyright (C)下午3:59 , www.hotapk.cn
   * 设备相关类
   */
  @SuppressLint({"HardwareIds", "MissingPermission"})
  public final class FDeviceUtils {
  
      private final static String KEY_MIUI_VERSION_NAME = "ro.miui.ui.version.name";
      private static final String KEY_FLYME_VERSION_NAME = "ro.build.display.id";
      private final static String FLYME = "flyme";
      private final static String ZTEC2016 = "zte c2016";
      private final static String ZUKZ1 = "zuk z1";
      private final static String MEIZUBOARD[] = {"m9", "M9", "mx", "MX"};
      private static String sMiuiVersionName;
      private static String sFlymeVersionName;
      private static boolean sIsTabletChecked = false;
      private static boolean sIsTabletValue = false;
  
      static {
          FileInputStream fileInputStream = null;
          try {
              fileInputStream = new FileInputStream(new File(Environment.getRootDirectory(), "build.prop"));
              Properties properties = new Properties();
              properties.load(fileInputStream);
              Class<?> clzSystemProperties = Class.forName("android.os.SystemProperties");
              Method getMethod = clzSystemProperties.getDeclaredMethod("get", String.class);
              // miui
              sMiuiVersionName = getLowerCaseName(properties, getMethod, KEY_MIUI_VERSION_NAME);
              //flyme
              sFlymeVersionName = getLowerCaseName(properties, getMethod, KEY_FLYME_VERSION_NAME);
  
          } catch (Exception e) {
          } finally {
              FCloseUtils.closeIO(fileInputStream);
          }
      }
  
      private FDeviceUtils() {
      }
  
      /**
       * 判断设备是否是手机
       *
       * @return {@code true}: 是<br>{@code false}: 否
       */
      public static boolean isPhone() {
          TelephonyManager tm = (TelephonyManager) FUtils.getAppContext().getSystemService(Context.TELEPHONY_SERVICE);
          return tm != null && tm.getPhoneType() != TelephonyManager.PHONE_TYPE_NONE;
      }
  
      /**
       * 判断是否是平板
       *
       * @return {@code true}: 是<br>{@code false}: 否
       */
      public static boolean isTablet() {
          return (FUtils.getAppContext().getResources().getConfiguration().screenLayout
                  & Configuration.SCREENLAYOUT_SIZE_MASK)
                  >= Configuration.SCREENLAYOUT_SIZE_LARGE;
      }
  
      /**
       * 获取IMEI码
       * <p>需添加权限 {@code <uses-permission android:name="android.permission.READ_PHONE_STATE"/>}</p>
       *
       * @return IMEI码
       */
      public static String getIMEI() {
          TelephonyManager tm = (TelephonyManager) FUtils.getAppContext().getSystemService(Context.TELEPHONY_SERVICE);
          return tm != null ? tm.getDeviceId() : null;
      }
  
      /**
       * 获取IMSI码
       * <p>需添加权限 {@code <uses-permission android:name="android.permission.READ_PHONE_STATE"/>}</p>
       *
       * @return IMSI码
       */
      public static String getIMSI() {
          TelephonyManager tm = (TelephonyManager) FUtils.getAppContext().getSystemService(Context.TELEPHONY_SERVICE);
          return tm != null ? tm.getSubscriberId() : null;
      }
  
      /**
       * 获取移动终端类型
       *
       * @return 手机制式
       * <ul>
       * <li>{@link TelephonyManager#PHONE_TYPE_NONE } : 0 手机制式未知</li>
       * <li>{@link TelephonyManager#PHONE_TYPE_GSM  } : 1 手机制式为GSM，移动和联通</li>
       * <li>{@link TelephonyManager#PHONE_TYPE_CDMA } : 2 手机制式为CDMA，电信</li>
       * <li>{@link TelephonyManager#PHONE_TYPE_SIP  } : 3</li>
       * </ul>
       */
      public static int getPhoneType() {
          TelephonyManager tm = (TelephonyManager) FUtils.getAppContext().getSystemService(Context.TELEPHONY_SERVICE);
          return tm != null ? tm.getPhoneType() : -1;
      }
  
      /**
       * 判断sim卡是否准备好
       *
       * @return {@code true}: 是<br>{@code false}: 否
       */
      public static boolean isSimCardReady() {
          TelephonyManager tm = (TelephonyManager) FUtils.getAppContext().getSystemService(Context.TELEPHONY_SERVICE);
          return tm != null && tm.getSimState() == TelephonyManager.SIM_STATE_READY;
      }
  
      /**
       * 获取Sim卡运营商名称
       * <p>中国移动、如中国联通、中国电信</p>
       *
       * @return sim卡运营商名称
       */
      public static String getSimOperatorName() {
          TelephonyManager tm = (TelephonyManager) FUtils.getAppContext().getSystemService(Context.TELEPHONY_SERVICE);
          return tm != null ? tm.getSimOperatorName() : null;
      }
  
      /**
       * 网络运营商名称
       * <p>中国移动、如中国联通、中国电信</p>
       *
       * @return sim卡运营商名称
       */
      public static String getNetworkOperatorName() {
          TelephonyManager tm = (TelephonyManager) FUtils.getAppContext().getSystemService(Context.TELEPHONY_SERVICE);
          return tm != null ? tm.getNetworkOperatorName() : null;
      }
  
      /**
       * 获取Sim卡运营商名称
       * <p>中国移动、如中国联通、中国电信</p>
       *
       * @return 移动网络运营商名称
       */
      public static String getSimOperatorByMnc() {
          TelephonyManager tm = (TelephonyManager) FUtils.getAppContext().getSystemService(Context.TELEPHONY_SERVICE);
          String operator = tm != null ? tm.getSimOperator() : null;
          if (operator == null) return null;
          switch (operator) {
              case "46000":
              case "46002":
              case "46007":
                  return "中国移动";
              case "46001":
              case "46006":
                  return "中国联通";
              case "46003":
                  return "中国电信";
              default:
                  return operator;
          }
      }
  
      /**
       * 获取手机状态信息
       * <p>需添加权限 {@code <uses-permission android:name="android.permission.READ_PHONE_STATE"/>}</p>
       *
       * @return DeviceId(IMEI) = 99000311726612<br>
       * DeviceSoftwareVersion = 00<br>
       * Line1Number =<br>
       * NetworkCountryIso = cn<br>
       * NetworkOperator = 46003<br>
       * NetworkOperatorName = 中国电信<br>
       * NetworkType = 6<br>
       * honeType = 2<br>
       * SimCountryIso = cn<br>
       * SimOperator = 46003<br>
       * SimOperatorName = 中国电信<br>
       * SimSerialNumber = 89860315045710604022<br>
       * SimState = 5<br>
       * SubscriberId(IMSI) = 460030419724900<br>
       * VoiceMailNumber = *86<br>
       */
      @SuppressLint("HardwareIds")
      public static String getPhoneStatus() {
          TelephonyManager tm = (TelephonyManager) FUtils.getAppContext()
                  .getSystemService(Context.TELEPHONY_SERVICE);
          String str = "";
          str += "DeviceId(IMEI) = " + tm.getDeviceId() + "\n";
          str += "DeviceSoftwareVersion = " + tm.getDeviceSoftwareVersion() + "\n";
          str += "Line1Number = " + tm.getLine1Number() + "\n";
          str += "NetworkCountryIso = " + tm.getNetworkCountryIso() + "\n";
          str += "NetworkOperator = " + tm.getNetworkOperator() + "\n";
          str += "NetworkOperatorName = " + tm.getNetworkOperatorName() + "\n";
          str += "NetworkType = " + tm.getNetworkType() + "\n";
          str += "PhoneType = " + tm.getPhoneType() + "\n";
          str += "SimCountryIso = " + tm.getSimCountryIso() + "\n";
          str += "SimOperator = " + tm.getSimOperator() + "\n";
          str += "SimOperatorName = " + tm.getSimOperatorName() + "\n";
          str += "SimSerialNumber = " + tm.getSimSerialNumber() + "\n";
          str += "SimState = " + tm.getSimState() + "\n";
          str += "SubscriberId(IMSI) = " + tm.getSubscriberId() + "\n";
          str += "VoiceMailNumber = " + tm.getVoiceMailNumber() + "\n";
          return str;
      }
  
      private static boolean _isTablet(Context context) {
          return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >=
                  Configuration.SCREENLAYOUT_SIZE_LARGE;
      }
  
      /**
       * 判断是否为平板设备
       */
      public static boolean isTablet(Context context) {
          if (sIsTabletChecked) {
              return sIsTabletValue;
          }
          sIsTabletValue = _isTablet(context);
          sIsTabletChecked = true;
          return sIsTabletValue;
      }
  
      /**
       * 判断是否是flyme系统
       */
      public static boolean isFlyme() {
          return !TextUtils.isEmpty(sFlymeVersionName) && sFlymeVersionName.contains(FLYME);
      }
  
      /**
       * 判断是否是MIUI系统
       */
      public static boolean isMIUI() {
          return !TextUtils.isEmpty(sMiuiVersionName);
      }
  
      public static boolean isMIUIV5() {
          return "v5".equals(sMiuiVersionName);
      }
  
      public static boolean isMIUIV6() {
          return "v6".equals(sMiuiVersionName);
      }
  
      public static boolean isMIUIV7() {
          return "v7".equals(sMiuiVersionName);
      }
  
      public static boolean isMIUIV8() {
          return "v8".equals(sMiuiVersionName);
      }
  
      public static boolean isMIUIV9() {
          return "v9".equals(sMiuiVersionName);
      }
  
      public static boolean isFlymeVersionHigher5_2_4() {
          //查不到默认高于5.2.4
          boolean isHigher = true;
          if (sFlymeVersionName != null && !sFlymeVersionName.equals("")) {
              Pattern pattern = Pattern.compile("(\\d+\\.){2}\\d");
              Matcher matcher = pattern.matcher(sFlymeVersionName);
              if (matcher.find()) {
                  String versionString = matcher.group();
                  if (versionString != null && !versionString.equals("")) {
                      String[] version = versionString.split("\\.");
                      if (version.length == 3) {
                          if (Integer.valueOf(version[0]) < 5) {
                              isHigher = false;
                          } else if (Integer.valueOf(version[0]) > 5) {
                              isHigher = true;
                          } else {
                              if (Integer.valueOf(version[1]) < 2) {
                                  isHigher = false;
                              } else if (Integer.valueOf(version[1]) > 2) {
                                  isHigher = true;
                              } else {
                                  if (Integer.valueOf(version[2]) < 4) {
                                      isHigher = false;
                                  } else if (Integer.valueOf(version[2]) >= 5) {
                                      isHigher = true;
                                  }
                              }
                          }
                      }
  
                  }
              }
          }
          return isMeizu() && isHigher;
      }
  
      /**
       * 判断是否为魅族
       */
      public static boolean isMeizu() {
          return isPhone(MEIZUBOARD) || isFlyme();
      }
  
      /**
       * 判断是否为小米
       */
      public static boolean isXiaomi() {
          return Build.BRAND.toLowerCase().contains("xiaomi");
      }
  
  
      /**
       * 判断是否为 ZUK Z1 和 ZTK C2016。
       * 两台设备的系统虽然为 android 6.0，但不支持状态栏icon颜色改变，因此经常需要对它们进行额外判断。
       */
      public static boolean isZUKZ1() {
          final String board = android.os.Build.MODEL;
          return board != null && board.toLowerCase().contains(ZUKZ1);
      }
  
      public static boolean isZTKC2016() {
          final String board = android.os.Build.MODEL;
          return board != null && board.toLowerCase().contains(ZTEC2016);
      }
  
      private static boolean isPhone(String[] boards) {
          final String board = android.os.Build.BOARD;
          if (board == null) {
              return false;
          }
          for (String board1 : boards) {
              if (board.equals(board1)) {
                  return true;
              }
          }
          return false;
      }
  
      /**
       * 判断悬浮窗权限（目前主要用户魅族与小米的检测）。
       */
      public static boolean isFloatWindowOpAllowed(Context context) {
          final int version = Build.VERSION.SDK_INT;
          if (version >= 19) {
              return checkOp(context, 24);  // 24 是AppOpsManager.OP_SYSTEM_ALERT_WINDOW 的值，该值无法直接访问
          } else {
              try {
                  return (context.getApplicationInfo().flags & 1 << 27) == 1 << 27;
              } catch (Exception e) {
                  e.printStackTrace();
                  return false;
              }
          }
      }
  
      @TargetApi(19)
      private static boolean checkOp(Context context, int op) {
          final int version = Build.VERSION.SDK_INT;
          if (version >= Build.VERSION_CODES.KITKAT) {
              AppOpsManager manager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
              try {
                  Method method = manager.getClass().getDeclaredMethod("checkOp", int.class, int.class, String.class);
                  int property = (Integer) method.invoke(manager, op,
                          Binder.getCallingUid(), context.getPackageName());
                  return AppOpsManager.MODE_ALLOWED == property;
              } catch (Exception e) {
                  e.printStackTrace();
              }
          }
          return false;
      }
  
      @Nullable
      private static String getLowerCaseName(Properties p, Method get, String key) {
          String name = p.getProperty(key);
          if (name == null) {
              try {
                  name = (String) get.invoke(null, key);
              } catch (Exception ignored) {
              }
          }
          if (name != null) name = name.toLowerCase();
          return name;
      }
  
  
      /**
       * 获取手机联系人
       * <p>需添加权限 {@code <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>}</p>
       * <p>需添加权限 {@code <uses-permission android:name="android.permission.READ_CONTACTS"/>}</p>
       *
       * @return 联系人链表
       */
      public static List<HashMap<String, String>> getAllContactInfo() {
          SystemClock.sleep(3000);
          ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
          // 1.获取内容解析者
          ContentResolver resolver = FUtils.getAppContext().getContentResolver();
          // 2.获取内容提供者的地址:com.android.contacts
          // raw_contacts表的地址 :raw_contacts
          // view_data表的地址 : data
          // 3.生成查询地址
          Uri raw_uri = Uri.parse("content://com.android.contacts/raw_contacts");
          Uri date_uri = Uri.parse("content://com.android.contacts/data");
          // 4.查询操作,先查询raw_contacts,查询contact_id
          // projection : 查询的字段
          Cursor cursor = resolver.query(raw_uri, new String[]{"contact_id"}, null, null, null);
          try {
              // 5.解析cursor
              if (cursor != null) {
                  while (cursor.moveToNext()) {
                      // 6.获取查询的数据
                      String contact_id = cursor.getString(0);
                      // cursor.getString(cursor.getColumnIndex("contact_id"));//getColumnIndex
                      // : 查询字段在cursor中索引值,一般都是用在查询字段比较多的时候
                      // 判断contact_id是否为空
                      if (!TextUtils.isEmpty(contact_id)) {//null   ""
                          // 7.根据contact_id查询view_data表中的数据
                          // selection : 查询条件
                          // selectionArgs :查询条件的参数
                          // sortOrder : 排序
                          // 空指针: 1.null.方法 2.参数为null
                          Cursor c = resolver.query(date_uri, new String[]{"data1",
                                          "mimetype"}, "raw_contact_id=?",
                                  new String[]{contact_id}, null);
                          HashMap<String, String> map = new HashMap<String, String>();
                          // 8.解析c
                          if (c != null) {
                              while (c.moveToNext()) {
                                  // 9.获取数据
                                  String data1 = c.getString(0);
                                  String mimetype = c.getString(1);
                                  // 10.根据类型去判断获取的data1数据并保存
                                  if (mimetype.equals("vnd.android.cursor.item/phone_v2")) {
                                      // 电话
                                      map.put("phone", data1);
                                  } else if (mimetype.equals("vnd.android.cursor.item/name")) {
                                      // 姓名
                                      map.put("name", data1);
                                  }
                              }
                          }
                          // 11.添加到集合中数据
                          list.add(map);
                          // 12.关闭cursor
                          if (c != null) {
                              c.close();
                          }
                      }
                  }
              }
          } finally {
              // 12.关闭cursor
              if (cursor != null) {
                  cursor.close();
              }
          }
          return list;
      }
  
  
      /**
       * 获取手机短信并保存到xml中
       * <p>需添加权限 {@code <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>}</p>
       * <p>需添加权限 {@code <uses-permission android:name="android.permission.READ_SMS"/>}</p>
       */
      public static void getAllSMS(String filepath) {
          // 1.获取短信
          // 1.1获取内容解析者
          ContentResolver resolver = FUtils.getAppContext().getContentResolver();
          // 1.2获取内容提供者地址   sms,sms表的地址:null  不写
          // 1.3获取查询路径
          Uri uri = Uri.parse("content://sms");
          // 1.4.查询操作
          // projection : 查询的字段
          // selection : 查询的条件
          // selectionArgs : 查询条件的参数
          // sortOrder : 排序
          Cursor cursor = resolver.query(uri, new String[]{"address", "date", "type", "body"}, null, null, null);
          // 设置最大进度
          int count = cursor.getCount();//获取短信的个数
          // 2.备份短信
          // 2.1获取xml序列器
          XmlSerializer xmlSerializer = Xml.newSerializer();
          try {
              // 2.2设置xml文件保存的路径
              // os : 保存的位置
              // encoding : 编码格式
              xmlSerializer.setOutput(new FileOutputStream(new File(filepath)), "utf-8");
              // 2.3设置头信息
              // standalone : 是否独立保存
              xmlSerializer.startDocument("utf-8", true);
              // 2.4设置根标签
              xmlSerializer.startTag(null, "smss");
              // 1.5.解析cursor
              while (cursor.moveToNext()) {
                  SystemClock.sleep(1000);
                  // 2.5设置短信的标签
                  xmlSerializer.startTag(null, "sms");
                  // 2.6设置文本内容的标签
                  xmlSerializer.startTag(null, "address");
                  String address = cursor.getString(0);
                  // 2.7设置文本内容
                  xmlSerializer.text(address);
                  xmlSerializer.endTag(null, "address");
                  xmlSerializer.startTag(null, "date");
                  String date = cursor.getString(1);
                  xmlSerializer.text(date);
                  xmlSerializer.endTag(null, "date");
                  xmlSerializer.startTag(null, "type");
                  String type = cursor.getString(2);
                  xmlSerializer.text(type);
                  xmlSerializer.endTag(null, "type");
                  xmlSerializer.startTag(null, "body");
                  String body = cursor.getString(3);
                  xmlSerializer.text(body);
                  xmlSerializer.endTag(null, "body");
                  xmlSerializer.endTag(null, "sms");
              }
              xmlSerializer.endTag(null, "smss");
              xmlSerializer.endDocument();
              // 2.8将数据刷新到文件中
              xmlSerializer.flush();
          } catch (Exception e) {
              e.printStackTrace();
          }
      }
  }
  