GetDevicesUtil.java 11 KB
package com.hjx.personalcenter.util;

import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.os.storage.StorageManager;
import android.os.storage.StorageVolume;
import android.util.Log;
import android.widget.Toast;

import com.hjx.personalcenter.model.DeviceInfo;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.Reader;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Locale;
import java.util.UUID;


public class GetDevicesUtil {
    private final static String LOG_TAG = "GetDevicesUtil";

    public static DeviceInfo getDevicesInfo(Context context) {
        DeviceInfo mDeviceInfo = new DeviceInfo();
        initDevicesInfo(mDeviceInfo, context);

        return mDeviceInfo;
    }

    public static void initDevicesInfo(DeviceInfo mDeviceInfo, Context context) {
        //if (PermissionUtil.hasReadExternalStoragePermission((Activity) context))
        if(android.os.Build.MODEL.equals("T8") && queryWithStorageManager(context)/(1024*1024*1024)>64){
            mDeviceInfo.setDeviceModel("T8 PRO");
        }else {
            mDeviceInfo.setDeviceModel(android.os.Build.MODEL);
        }
        Log.e(LOG_TAG, "" + mDeviceInfo.getDeviceModel());
        mDeviceInfo.setMac(getMacAddress(context));
        Log.e(LOG_TAG, "" + mDeviceInfo.getMac());

        mDeviceInfo.setDeviceNumber(getCPUSerial(context));
        Log.e(LOG_TAG, "" + mDeviceInfo.getDeviceNumber());
    }

    private static String getCPUSerial(Context context) {
        //String androidID = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
        String cpuAddress = Build.SERIAL;
//		String cpuAddress = null;
//		TelephonyManager mTelephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
//		//if (PermissionUtil.hasReadExternalStoragePermission((Activity) context))
//		if (mTelephony.getDeviceId() != null) {
//			cpuAddress = mTelephony.getDeviceId();
//		} else {
//			//android.provider.Settings;
//			cpuAddress = Settings.Secure.getString(context.getApplicationContext().getContentResolver(), Settings.Secure.ANDROID_ID);
//		}
        return cpuAddress;
    }


    public static String getMacAddress(Context context) {
        // 如果是7.0以下,
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            return getMacAddress6(context);
        } else {
            return getNewMac();
        }
    }



    private static String[] units = {"B", "KB", "MB", "GB", "TB"};
    /**
     * 单位转换
     */
    private static String getUnit(float size) {
        int index = 0;
        while (size > 1024 && index < 4) {
            size = size / 1024;
            index++;
        }
        return String.format(Locale.getDefault(), " %.2f %s", size, units[index]);
    }

    /**
     * 获取总共容量大小,包括系统大小
     */
    public static float queryWithStorageManager(Context context) {
        //5.0 查外置存储
        StorageManager storageManager = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);
        float unit = 1024;
        int version = Build.VERSION.SDK_INT;
        if (version < Build.VERSION_CODES.M) {//小于6.0
            try {
                Method getVolumeList = StorageManager.class.getDeclaredMethod("getVolumeList");
                StorageVolume[] volumeList = (StorageVolume[]) getVolumeList.invoke(storageManager);
                long totalSize = 0, availableSize = 0;
                if (volumeList != null) {
                    Method getPathFile = null;
                    for (StorageVolume volume : volumeList) {
                        if (getPathFile == null) {
                            getPathFile = volume.getClass().getDeclaredMethod("getPathFile");
                        }
                        File file = (File) getPathFile.invoke(volume);
                        totalSize += file.getTotalSpace();
                        availableSize += file.getUsableSpace();
                    }
                }
                Log.d("TAG", "totalSize = " + getUnit(totalSize) +"||"+totalSize+ " ,availableSize = " + getUnit(availableSize));
                return totalSize;
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        } else {

            try {
                Method getVolumes = StorageManager.class.getDeclaredMethod("getVolumes");//6.0
                List<Object> getVolumeInfo = (List<Object>) getVolumes.invoke(storageManager);
                long total = 0L, used = 0L;
                for (Object obj : getVolumeInfo) {

                    Field getType = obj.getClass().getField("type");
                    int type = getType.getInt(obj);

                    Log.d("TAG", "type: " + type);
                    if (type == 1) {//TYPE_PRIVATE

                        long totalSize = 0L;

                        //获取内置内存总大小
                        if (version >=26) {//8.0
//                            unit = 1000;
//                            Method getFsUuid = obj.getClass().getDeclaredMethod("getFsUuid");
//                            String fsUuid = (String) getFsUuid.invoke(obj);
//                            totalSize = getTotalSize(context, fsUuid);//8.0 以后使用
                        } else if (version >= Build.VERSION_CODES.N_MR1) {//7.1.1
                            Method getPrimaryStorageSize = StorageManager.class.getMethod("getPrimaryStorageSize");//5.0 6.0 7.0没有
                            totalSize = (long) getPrimaryStorageSize.invoke(storageManager);
                        }
                        long systemSize = 0L;

                        Method isMountedReadable = obj.getClass().getDeclaredMethod("isMountedReadable");
                        boolean readable = (boolean) isMountedReadable.invoke(obj);
                        if (readable) {
                            Method file = obj.getClass().getDeclaredMethod("getPath");
                            File f = (File) file.invoke(obj);

                            if (totalSize == 0) {
                                totalSize = f.getTotalSpace();
                            }
                            systemSize = totalSize - f.getTotalSpace();
                            used += totalSize - f.getFreeSpace();
                            total += totalSize;
                        }
                        Log.d("TAG", "设备内存大小:" + getUnit(totalSize) + "\n系统大小:" + getUnit(systemSize));
                        Log.d("TAG", "totalSize = " + getUnit(totalSize) +"||"+totalSize+ " ,used(with system) = " + getUnit(used) + " ,free = " + getUnit(totalSize - used));
                        return totalSize;

                    } else if (type == 0) {//TYPE_PUBLIC
//                        //外置存储
//                        Method isMountedReadable = obj.getClass().getDeclaredMethod("isMountedReadable");
//                        boolean readable = (boolean) isMountedReadable.invoke(obj);
//                        if (readable) {
//                            Method file = obj.getClass().getDeclaredMethod("getPath");
//                            File f = (File) file.invoke(obj);
//                            used += f.getTotalSpace() - f.getFreeSpace();
//                            total += f.getTotalSpace();
//                        }
                    } else if (type == 2) {//TYPE_EMULATED

                    }
                }
                Log.d("TAG", "总内存 total = " + getUnit(total) +"||"+total+ "\n已用 used(with system) = " + getUnit(used) + "\n可用 available = " + getUnit(total - used));
//                return total;
                Log.e("TAG", "缺少权限:permission.PACKAGE_USAGE_STATS");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return 0;
    }



    /**
     * 7.0以下获取
     *
     * @param mContext
     * @return
     */
    private static String getMacAddress6(Context mContext) {

        String str = "";
        String macSerial = "";
        try {
            Process pp = Runtime.getRuntime().exec(
                    "cat /sys/class/net/wlan0/address ");
            InputStreamReader ir = new InputStreamReader(pp.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);

            for (; null != str; ) {
                str = input.readLine();
                if (str != null) {
                    macSerial = str.trim();// 去空格
                    break;
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        if (macSerial == null || "".equals(macSerial)) {
            try {
                return loadFileAsString("/sys/class/net/eth0/address")
                        .toUpperCase().substring(0, 17);
            } catch (Exception e) {
                e.printStackTrace();

            }

        }
        return macSerial;
    }

    public static String loadFileAsString(String fileName) throws Exception {
        FileReader reader = new FileReader(fileName);
        String text = loadReaderAsString(reader);
        reader.close();
        return text;
    }

    public static String loadReaderAsString(Reader reader) throws Exception {
        StringBuilder builder = new StringBuilder();
        char[] buffer = new char[4096];
        int readLength = reader.read(buffer);
        while (readLength >= 0) {
            builder.append(buffer, 0, readLength);
            readLength = reader.read(buffer);
        }
        return builder.toString();
    }


    /**
     * 7.0以上根据busybox获取本地Mac
     *
     * @return
     */
    private static String getNewMac() {
        try {
            List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface nif : all) {
                if (!nif.getName().equalsIgnoreCase("wlan0")) continue;

                byte[] macBytes = nif.getHardwareAddress();
                if (macBytes == null) {
                    return null;
                }

                StringBuilder res1 = new StringBuilder();
                for (byte b : macBytes) {
                    res1.append(String.format("%02X:", b));
                }

                if (res1.length() > 0) {
                    res1.deleteCharAt(res1.length() - 1);
                }
                return res1.toString();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

}