Android设备基本信息获取

简述

本章节着重说明从Android设备获取其基本信息参数,如:设备SDK版本,设备型号,手机品牌,厂商分配的序列号,真实对外的ip地址,是否root,apk签名文件的md5值,当前屏幕亮度, cpu最大频率,总存储空间字节,是否允许位置模拟,WiFiManager相关,网络相关,手机SIM卡信息、经纬度信息的获取等等。

正文

设备SDK版本

获取方式:

apiVersion = Build.VERSION.SDK; //设备SDK版本

权限要求:

设备系统版本

获取方式:

releaseVersion = Build.VERSION.RELEASE; //设备的系统版本

权限要求:

设备型号

获取方式:

deviceModel = Build.MODEL; // 设备型号

权限要求:

手机品牌

获取方式:

brand = Build.BRAND; //手机品牌

权限要求:

厂商分配的序列号

获取方式:

try {
    serial = Build.class.getField("SERIAL").get(null).toString(); //厂商分配的序列号
    } catch (IllegalAccessException e) {
       e.printStackTrace();
    } catch (NoSuchFieldException e) {
       e.printStackTrace();
}

权限要求:

生产该产品的内部代码

获取方式:

product = Build.PRODUCT; //生产该产品的内部代码

权限要求:

固件编号

获取方式:

display = Build.DISPLAY; //手机固件编号

权限要求:

编译ROM的主机

获取方式:

host = Build.HOST; //编译ROM的主机

权限要求:

出厂时设备名称

获取方式:

deviceName = Build.DEVICE; //出厂时设备名称

权限要求:

硬件平台名称

获取方式:

hardware = Build.HARDWARE; //硬件平台名称 

权限要求:

ROM的标签

获取方式:

tags = Build.TAGS; //ROM的标签

权限要求:

当前时区

获取方式:

timeZone = DeviceInfoUtils.getCurrentTimeZone(); //当前时区(dstDiff=0,gmfOffset=480)
/**
 * 获取当前设备的时区信息
 * @return
 */
public static String getCurrentTimeZone() {
    TimeZone tz = TimeZone.getDefault();
    return tz.getDisplayName(false, TimeZone.SHORT) + " Timezon id :: " + tz.getID();
}

权限要求:

设备当前配置的语言

获取方式:

language = DeviceInfoUtils.getSystemLanguage(); //当前配置的语言
/**
 * 获取系统语言
 * @return
 */
public static String getSystemLanguage() {
    String language = null;
    try{
        language = context.getResources().getConfiguration().locale.getLanguage();
    }catch (Exception e){
        e.printStackTrace();
    }
    return language;
}

权限要求:

当前屏幕亮度

获取方式:

language = DeviceInfoUtils.getSystemLanguage(); //当前配置的语言
/**
 * 获得系统亮度
 *
 * @return
 */
public static int getSystemBrightness() {
    int systemBrightness = 0;
    try {
        systemBrightness = Settings.System.getInt(context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS);
    } catch (Settings.SettingNotFoundException e) {
        e.printStackTrace();
    }
    return systemBrightness;
}

权限要求:

屏幕分辨率

获取方式:

screenRes = DeviceInfoUtils.getScreenRes(); //屏幕分辨率
/**
 * 获取屏幕分辨率
 *
 * @return
 */
public static String getScreenRes() {
    try {
        // 获取屏幕分辨率
        WindowManager wm = (WindowManager)(context.getSystemService(Context.WINDOW_SERVICE));
        DisplayMetrics dm = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(dm);
        int screenWidth = dm.widthPixels;
        int screenHeight = dm.heightPixels;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("screenWidth", screenWidth);
        jsonObject.put("screenHeight", screenHeight);
        return jsonObject.toString();
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return null;
}

权限要求:

系统初始化时生成的随机id

获取方式:

androidId = DeviceInfoUtils.getAndroidID(); //系统初始化时生成的随机id
/**
 * 获取androidId
 *
 * @return
 */
public static String getAndroidID() {
    try {
        return Settings.System.getString(context.getContentResolver(), Settings.System.ANDROID_ID);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

权限要求:

应用包名

获取方式:

packageName = DeviceInfoUtils.getPackageName(); //应用包名
/**
 * 获取应用包名
 * @return
 */
public static String getPackageName() {
    return context.getPackageName();
}

权限要求:

应用版本号

获取方式:

apkVersion = DeviceInfoUtils.getApkVersionName(); //应用版本号
/**
 * 应用版本号
 * @return
 */
public static String getApkVersionName() {
    PackageManager manager = context.getPackageManager();
    String name = null;
    try {
        PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
        name = info.versionName;
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
    return name;
}

权限要求:

APK签名文件的MD5值

获取方式:

signMD5 = DeviceInfoUtils.getAPKSignMd5Str(); //APK签名文件的md5

/**
 * 获取当前apk的签名信息
 * @return
 */
public static String getAPKSignMd5Str() {
    try {
        PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES);
        Signature[] signs = packageInfo.signatures;
        Signature sign = signs[0];
        String signStr = StringUtils.encryptionMD5(sign.toByteArray());
        return signStr;
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
    return "";
}


/**
 * MD5加密
 * @param byteStr 需要加密的内容
 * @return 返回 byteStr的md5值
 */
public static String encryptionMD5(byte[] byteStr) {
    MessageDigest messageDigest = null;
    StringBuffer md5StrBuff = new StringBuffer();
    try {
        messageDigest = MessageDigest.getInstance("MD5");
        messageDigest.reset();
        messageDigest.update(byteStr);
        byte[] byteArray = messageDigest.digest();
        for (int i = 0; i < byteArray.length; i++) {
            if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) {
                md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
            } else {
                md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
            }
        }
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return md5StrBuff.toString();
}

权限要求:

基带版本

获取方式:

basebandVersion = DeviceInfoUtils.getBasebandVer(); //基带版本
/**
 * 基带版本
 * @return
 */
public static String getBasebandVer() {
    String Version = "";
    try {
        Class cl = Class.forName("android.os.SystemProperties");
        Object invoker = cl.newInstance();
        Method m = cl.getMethod("get", new Class[] { String.class,String.class });
        Object result = m.invoke(invoker, new Object[]{"gsm.version.baseband", "no message"});
        Version = (String)result;
    } catch (Exception e) {
    }
    return Version;
}

权限要求:

CPU最大频率

获取方式:

cpuFrequency = DeviceInfoUtils.getCPUFreQuency(); //cpu最大频率
/**
 * cpu最大频率
 * @return
 */
public static String getCPUFreQuency() {
    // 获取CPU最大频率(单位KHZ)
    // "/system/bin/cat" 命令行
    // "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq" 存储最大频率的文件的路径
    String result = "";
    ProcessBuilder cmd;
    try {
        String[] args = {"/system/bin/cat", 
                         "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq"}; /
        cmd = new ProcessBuilder(args);
        Process process = cmd.start();
        InputStream in = process.getInputStream();
        byte[] re = new byte[24];
        while (in.read(re) != -1) {
            result = result + new String(re);
        }
        in.close();
    } catch (IOException ex) {
        ex.printStackTrace();
        result = "N/A";
    }
    return result.trim();
}

权限要求:

内存信息

获取方式:

ActivityManager.MemoryInfo memoryInfo = DeviceInfoUtils.getMemoryInfo();
if (memoryInfo != null) {
    totalMemory = memoryInfo.totalMem; //总内存字节
    availableMemory = memoryInfo.availMem;//可用内存字节
}

/**
 * 获取当前内存信息对象
 *
 * @return 当前内存信息对象。
 */
public static ActivityManager.MemoryInfo getMemoryInfo() {
    ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
    ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    activityManager.getMemoryInfo(mi);
    return mi;
}

权限要求:

存储信息

获取方式:

StatFs statFs = DeviceInfoUtils.getSystemStatFs();
            if (statFs != null) {
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {
                    availableStorage = statFs.getAvailableBytes(); //可用存储空间字节
                    totalStorage = statFs.getTotalBytes(); //总存储空间字节
                }
            }

/**
 * 获取系统存储空间信息
 * @return
 */
public static StatFs getSystemStatFs(){
    String state = Environment.getExternalStorageState();
    if(Environment.MEDIA_MOUNTED.equals(state)) {
        File sdcardDir = Environment.getExternalStorageDirectory();
        StatFs sf = new StatFs(sdcardDir.getPath());
        long blockSize = sf.getBlockSize();
        long blockCount = sf.getBlockCount();
        long availCount = sf.getAvailableBlocks();
        LogUtils.i("", "block大小:"+ blockSize+",block数目:"+ blockCount+",总大小:"+blockSize*blockCount/1024+"KB");
        LogUtils.i("", "可用的block数目::"+ availCount+",剩余空间:"+ availCount*blockSize/1024+"KB");
        return sf;
    }
    return null;
}

权限要求:

是否允许位置模拟

获取方式:

allowMockLocation = DeviceInfoUtils.isAllowMockLocation(); //是否允许位置模拟

/**
 * 是否允许位置模拟
 * @return
 */
public static boolean isAllowMockLocation() {
    boolean isAllowMock = false;
    try {
        isAllowMock = Settings.Secure.getInt(context.getContentResolver(),Settings.Secure.ALLOW_MOCK_LOCATION, 0) != 0;
    }catch (Exception e){
        e.printStackTrace();
    }
    return isAllowMock;
}

权限要求:

CPU型号或平台号

获取方式:

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
    String[] cpuTypes = Build.SUPPORTED_ABIS;
    cpuType = "";
    if(cpuTypes != null){
        for (String item : cpuTypes){
            if(!StringUtils.isNull(item)){
                cpuType += item + ",";
            }

        }
        if(cpuType.length() > 1){
            cpuType.substring(0, cpuType.length() - 2);
        }
    }
}

权限要求:

电池信息

获取方式:

public class BatteryReceiver extends BroadcastReceiver {

    public void registerBatteryReceiver(Context context){
        IntentFilter intentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        context.registerReceiver(this, intentFilter);
    }
    
     /**
     * 是否处于充电状态
     */
    private boolean isBatteryCharging;
    /**
     * 电池温度
     */
    private int batteryTemp;
    
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
            //电池电量,数字
            LogUtils.d("Battery", "" + intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0));
            //电池最大容量
            LogUtils.d("Battery", "" + intent.getIntExtra(BatteryManager.EXTRA_SCALE, 0));
            //电池伏数
            LogUtils.d("Battery", "" + intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, 0));
            //电池温度
            batteryTemp = intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0);
            LogUtils.d("Battery", "" + batteryTemp);

            //电池状态,返回是一个数字
            // BatteryManager.BATTERY_STATUS_CHARGING 表示是充电状态
            // BatteryManager.BATTERY_STATUS_DISCHARGING 放电中
            // BatteryManager.BATTERY_STATUS_NOT_CHARGING 未充电
            // BatteryManager.BATTERY_STATUS_FULL 电池满
            int batteryStatus = intent.getIntExtra(BatteryManager.EXTRA_STATUS, BatteryManager.BATTERY_STATUS_UNKNOWN);
            LogUtils.d("Battery", "" + batteryStatus);
            if(batteryStatus == BatteryManager.BATTERY_STATUS_CHARGING){
                isBatteryCharging = true;
            }else{
                isBatteryCharging = false;
            }



            //充电类型 BatteryManager.BATTERY_PLUGGED_AC 表示是充电器,不是这个值,表示是 USB
            LogUtils.d("Battery", "" + intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0));

            //电池健康情况,返回也是一个数字
            //BatteryManager.BATTERY_HEALTH_GOOD 良好
            //BatteryManager.BATTERY_HEALTH_OVERHEAT 过热
            //BatteryManager.BATTERY_HEALTH_DEAD 没电
            //BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE 过电压
            //BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE 未知错误
            LogUtils.d("Battery", "" + intent.getIntExtra(BatteryManager.EXTRA_HEALTH, BatteryManager.BATTERY_HEALTH_UNKNOWN));
        }
    }
}

权限要求:

蓝牙Mac地址

获取方式:

blueMac = DeviceInfoUtils.getBlueMacAddress(); //蓝牙mac地址
/**
 * 获取蓝牙地址
 *
 * @return
 */
public static String getBlueMacAddress() {
    try {
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        Object bluetoothManagerService = new Mirror().on(bluetoothAdapter).get().field("mService");
        if (bluetoothManagerService == null) {
            LogUtils.e(TAG, "couldn't find bluetoothManagerService");
            return null;
        }
        Object address = new Mirror().on(bluetoothManagerService).invoke().method("getAddress").withoutArgs();
        if (address != null && address instanceof String) {
            LogUtils.e(TAG, "using reflection to get the BT MAC address: " + address);
            return (String) address;
        } else {
            return null;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

权限要求:


开机到当前时间(不包括休眠时间)

获取方式:

upTime = SystemClock.uptimeMillis();

权限要求:

开机到当前时间(包括休眠时间)

获取方式:

activeTime = SystemClock.elapsedRealtime();

权限要求:

当前网络类型

获取方式:

networkTy = DeviceInfoUtils.getNetWorkType();

/**
 * 获取当前的网络类型
 * @return
 */
public static String getNetWorkType() {
    try{
        //获取系统的网络服务
        ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        //如果当前没有网络
        if (null == connManager)
            return "NO";
        //获取当前网络类型,如果为空,返回无网络
        NetworkInfo activeNetInfo = connManager.getActiveNetworkInfo();
        if (activeNetInfo == null || !activeNetInfo.isAvailable()) {
            return "NO";
        }
        // 判断是不是连接的是不是wifi
        NetworkInfo wifiInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (null != wifiInfo) {
            NetworkInfo.State state = wifiInfo.getState();
            if (null != state)
                if (state == NetworkInfo.State.CONNECTED || state == NetworkInfo.State.CONNECTING) {
                    return "WIFI";
                }
        }
        // 如果不是wifi,则判断当前连接的是运营商的哪种网络2g、3g、4g等
        NetworkInfo networkInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        if (null != networkInfo) {
            NetworkInfo.State state = networkInfo.getState();
            String strSubTypeName = networkInfo.getSubtypeName();
            if (null != state)
                if (state == NetworkInfo.State.CONNECTED || state == NetworkInfo.State.CONNECTING) {
                    switch (activeNetInfo.getSubtype()) {
                            //如果是2g类型
                        case TelephonyManager.NETWORK_TYPE_GPRS: // 联通2g
                        case TelephonyManager.NETWORK_TYPE_CDMA: // 电信2g
                        case TelephonyManager.NETWORK_TYPE_EDGE: // 移动2g
                        case TelephonyManager.NETWORK_TYPE_1xRTT:
                        case TelephonyManager.NETWORK_TYPE_IDEN:
                            return "2G";
                            //如果是3g类型
                        case TelephonyManager.NETWORK_TYPE_EVDO_A: // 电信3g
                        case TelephonyManager.NETWORK_TYPE_UMTS:
                        case TelephonyManager.NETWORK_TYPE_EVDO_0:
                        case TelephonyManager.NETWORK_TYPE_HSDPA:
                        case TelephonyManager.NETWORK_TYPE_HSUPA:
                        case TelephonyManager.NETWORK_TYPE_HSPA:
                        case TelephonyManager.NETWORK_TYPE_EVDO_B:
                        case TelephonyManager.NETWORK_TYPE_EHRPD:
                        case TelephonyManager.NETWORK_TYPE_HSPAP:
                            return "3G";
                            //如果是4g类型
                        case TelephonyManager.NETWORK_TYPE_LTE:
                            return "4G";
                        default:
                            //中国移动 联通 电信 三种3G制式
                            if (strSubTypeName.equalsIgnoreCase("TD-SCDMA")
                                || strSubTypeName.equalsIgnoreCase("WCDMA")
                                || strSubTypeName.equalsIgnoreCase("CDMA2000")) {
                                return "3G";
                            } else {
                                return "MOBILE";
                            }
                    }
                }
        }
        return "NO";
    }catch (Exception e){
        e.printStackTrace();
    }
    return null;

}

权限要求:



对外请求的可用ip列表

获取方式:

trueIps = DeviceInfoUtils.getIpAddressString();
/**
 * 获取真实对外可用的ip列表
 * @return
 */
public static String getIpAddressString() {
    String ipAddresses = "";
    try {
        for (Enumeration enNetI = NetworkInterface
             .getNetworkInterfaces(); enNetI.hasMoreElements(); ) {
            NetworkInterface netI = enNetI.nextElement();
            for (Enumeration enumIpAddr = netI
                 .getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (inetAddress instanceof Inet4Address && !inetAddress.isLoopbackAddress()) {
                    ipAddresses += inetAddress.getHostAddress() + ",";
                }
            }
        }
        if(ipAddresses.length() > 1){
            ipAddresses.substring(0, ipAddresses.length() - 2);
        }
    } catch (SocketException e) {
        e.printStackTrace();
    }
    return ipAddresses;
}

权限要求:

是否root

获取方式:

root = DeviceInfoUtils.isRoot();
/**
 * 判断手机是否root,不弹出root请求框
 *
 */
public static boolean isRoot() {
    try{
        String binPath = "/system/bin/su";
        String xBinPath = "/system/xbin/su";
        if (new File(binPath).exists() && isExecutable(binPath))
            return true;
        if (new File(xBinPath).exists() && isExecutable(xBinPath))
            return true;
        return false;
    }catch (Exception e){
        e.printStackTrace();
    }
    return false;
}

private static boolean isExecutable(String filePath) {
    Process p = null;
    try {
        p = Runtime.getRuntime().exec("ls -l " + filePath);
        // 获取返回内容
        BufferedReader in = new BufferedReader(new InputStreamReader(
            p.getInputStream()));
        String str = in.readLine();
        LogUtils.i(TAG, str);
        if (str != null && str.length() >= 4) {
            char flag = str.charAt(3);
            if (flag == 's' || flag == 'x')
                return true;
        }
    } catch (IOException e) {
        e.printStackTrace();
    }finally{
        if(p!=null){
            p.destroy();
        }
    }
    return false;
}

权限要求:



SIM卡相关信息

获取方式:

 try {
            TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            imei = telephonyManager.getDeviceId();
            LogUtils.i("imei ->" + imei);

            imsi = telephonyManager.getSubscriberId();
            LogUtils.i("imsi ->" + imsi);

            phoneNumber = telephonyManager.getLine1Number();
            LogUtils.i("SIM卡中存储本机号码 phoneNumber ->" + phoneNumber);

            voiceMail = telephonyManager.getVoiceMailNumber();
            LogUtils.i("语音邮件号码 voiceMail ->" + voiceMail);

            simSerial = telephonyManager.getSimSerialNumber();
            LogUtils.i("SIM卡序列号 simSerial ->" + simSerial);

            countryIso = telephonyManager.getNetworkCountryIso();
            LogUtils.i("SIM卡提供商的国家代码 countryIso ->" + countryIso);

            carrier = telephonyManager.getNetworkOperatorName();
            LogUtils.i("当前移动网络运营商 carrier ->" + carrier);

            if (!StringUtils.isNull(imsi) && imsi.length() == 15) {
                mcc = imsi.substring(0, 3);
                mnc = imsi.substring(3, 5);
            }
            LogUtils.i("mcc ->" + mcc);
            LogUtils.i("mnc ->" + mnc);

            simOperator = telephonyManager.getSimOperator();
            LogUtils.i("SIM的移动运营商的名称 simOperator ->" + simOperator);

            phoneType = telephonyManager.getPhoneType();
            LogUtils.i("移动终端的类型 phoneType ->" + phoneType);

            radioType = telephonyManager.getNetworkType();
            LogUtils.i("当前使用的网络制式 radioType ->" + radioType);

        }catch (Exception e){
            e.printStackTrace();
        }

权限要求:


经纬度信息

获取方式:

gpsLocation = locationUtils.getLocationStr(locationUtils.getCurrentNetLocation()); //获取经纬度信息

public class LocationUtils {

    private Context context;

    private LocationManager locationManager;


    public LocationUtils(Context context){
        try{
            this.context = context;
            locationManager = (LocationManager) this.context.getSystemService(Context.LOCATION_SERVICE);
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    public Location getCurrentNetLocation(){
        try{
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
                if(ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION)
                        == PackageManager.PERMISSION_GRANTED &&
                        ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION)
                                == PackageManager.PERMISSION_GRANTED){
                    if(!locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
                        return null;
                    }
                    return locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                }
            }else{
                if(!locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
                    return null;
                }
                return locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }


    public String getLocationStr(Location location) {
        try{
            if(location == null){
                return getDefaultLocationStr();
            }
            return getLocationNormalStr(location);
        }catch (Exception e){
            e.printStackTrace();
        }
        return getDefaultLocationStr();
    }


    /**
     * 获取失败时 返回默认值
     *
     * @return
     */
    private static String getDefaultLocationStr(){
        JSONObject object = new JSONObject();
        try {
            object.put("lng", 0);
            object.put("lat", 0);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return object.toString();
    }



    private String getLocationNormalStr(Location location){
        JSONObject object = new JSONObject();
        try {
            object.put("lng", location.getLongitude());
            object.put("lat", location.getLatitude());
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }
        return object.toString();
    }


}

权限要求:


SIM卡获取经纬度信息

获取方式:

cellLocation = DeviceInfoUtils.getCellLocation();
/**
 * 获取从sim卡得到的基站经纬度
 * @return
 */
public static String getCellLocation() {
    try {
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
            ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return null;
        }
        return tm.getCellLocation().toString();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

权限要求:



与wifi相关的信息

获取方式:

try {
    WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    if(!wifiManager.isWifiEnabled()){
        return;
    }
    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
    if(wifiInfo != null){
        wifiIp = StringUtils.long2ip(wifiInfo.getIpAddress());
        wifiMac = wifiInfo.getMacAddress();   //此方法在高版本时返回异常数据
        ssid = wifiInfo.getSSID();
        bssid = wifiInfo.getBSSID();
    }
    LogUtils.i("当设备处于wifi状态时,获取当前设备的ip wifiIp ->" + wifiIp);
    LogUtils.i("当设备处于wifi可用状态时,获取当前设备的mac地址 wifiMac ->" + wifiMac);
    LogUtils.i("当前连接的无线网络名称 ssid ->" + ssid);
    LogUtils.i("当前连接无线网络的BSSID bssid ->" + bssid);
    DhcpInfo dhcpInfo = wifiManager.getDhcpInfo();
    gateway = StringUtils.long2ip(dhcpInfo.gateway);
    wifiNetmask = StringUtils.long2ip(dhcpInfo.netmask);
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("dns1", StringUtils.long2ip(dhcpInfo.dns1));
    jsonObject.put("dns2", StringUtils.long2ip(dhcpInfo.dns2));
    dnsAddress = jsonObject.toString();

    LogUtils.i("当前连接无线网络的网关地址 gateway ->" + gateway);
    LogUtils.i("当前连接无线网络的子网掩码 wifiNetmask ->" + wifiNetmask);
    LogUtils.i("当前活动网络的dns地址 dnsAddress ->" + dnsAddress);

}catch (Exception e){
    e.printStackTrace();
}

public static String long2ip(long ip) {
    StringBuffer sb = new StringBuffer();
    sb.append(String.valueOf((int) (ip & 0xff)));
    sb.append('.');
    sb.append(String.valueOf((int) ((ip >> 8) & 0xff)));
    sb.append('.');
    sb.append(String.valueOf((int) ((ip >> 16) & 0xff)));
    sb.append('.');
    sb.append(String.valueOf((int) ((ip >> 24) & 0xff)));
    return sb.toString();
}

权限要求:


注意事项

Android6.0之后对于




需要运行时权限获取

你可能感兴趣的:(Android设备基本信息获取)