栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Android 获取手机系统版本号、获取手机型号、获取手机厂商、获取手机IMEI、获取手机CPU

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Android 获取手机系统版本号、获取手机型号、获取手机厂商、获取手机IMEI、获取手机CPU

1.先申请权限,关于如何申请权限请查看RxPermissions的使用(简单实用)_ErwinNakajima的博客-CSDN博客

2.手機唯一識別碼管理類。

package com.phone.common_library.manager;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.telephony.TelephonyManager;

import androidx.core.app.ActivityCompat;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.security.MessageDigest;
import java.util.UUID;

public class SystemIdManager {

    private static final String TAG = SystemIdManager.class.getSimpleName();
    //保存文件的路径
//    private static final String CACHE_IMAGE_DIR = "aray/cache/devices";
//    private static final String CACHE_IMAGE_DIR = "Android/data/systemId";
    private static final String CACHE_IMAGE_DIR = "Android/systemId";
    //保存的文件 采用隐藏文件的形式进行保存
    private static final String DEVICES_FILE_NAME = ".DEVICES";

    
    public static String getSystemId(Context context) {
        //读取保存的在sd卡中的唯一标识符
        String systemId = readSystemId(context);
        //用于生成最终的唯一标识符
        StringBuffer stringBuffer = new StringBuffer();
        //判断是否已经生成过,
        if (systemId != null && !"".equals(systemId)) {
            LogManager.i(TAG, "已经生成过");
            return systemId;
        }
        try {
            //获取IMES(也就是常说的SystemId)
            systemId = getIMIEStatus(context);
            stringBuffer.append(systemId);
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            //获取设备的MACAddress地址 去掉中间相隔的冒号
            systemId = getLocalMac(context).replace(":", "");
            stringBuffer.append(systemId);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //如果以上搜没有获取相应的则自己生成相应的UUID作为相应设备唯一标识符
        if (stringBuffer == null || stringBuffer.length() <= 0) {
            UUID uuid = UUID.randomUUID();
            systemId = uuid.toString().replace("-", "");
            stringBuffer.append(systemId);
        }
        //为了统一格式对设备的唯一标识进行md5加密 最终生成32位字符串
        String md5 = getMD5(stringBuffer.toString(), false);
        if (stringBuffer.length() > 0) {
            //持久化操作, 进行保存到SD卡中
            saveSystemId(md5, context);
        } else {

        }
        return md5;
    }

    
    public static String readSystemId(Context context) {
        File file = getSystemIdDir(context);
        if (file.exists()) {
            LogManager.i(TAG, "file.exists()");
            if (file.length() > 1) {
                LogManager.i(TAG, "file.length() > 1");
                StringBuffer buffer = new StringBuffer();
                try {
                    FileInputStream fis = new FileInputStream(file);
                    InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
                    Reader in = new BufferedReader(isr);
                    int i;
                    while ((i = in.read()) > -1) {
                        buffer.append((char) i);
                    }
                    in.close();
                    return buffer.toString();
                } catch (IOException e) {
                    e.printStackTrace();
                    return null;
                }
            } else {
                return null;
            }
        } else {
            LogManager.i(TAG, "xfile.exists()");
            return null;
        }
    }

    
    public static String getIMIEStatus(Context context) {
        TelephonyManager telephonyManager = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        String iMIEStatus = null;
        if (Build.VERSION.SDK_INT >= 23) {
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return null;
            }
            iMIEStatus = telephonyManager.getDeviceId();
            LogManager.i(TAG, "iMIEStatus*****" + iMIEStatus);
        }
        return iMIEStatus;
    }


    
    private static String getLocalMac(Context context) {
//        WifiManager wifi = (WifiManager) context
//                .getSystemService(Context.WIFI_SERVICE);
//        WifiInfo info = wifi.getConnectionInfo();
//        return info.getMacAddress();
        
        String macAddress = null;
        StringBuffer buf = new StringBuffer();
        NetworkInterface networkInterface = null;
        try {
            networkInterface = NetworkInterface.getByName("eth1");
            if (networkInterface == null) {
                networkInterface = NetworkInterface.getByName("wlan0");
            }
            if (networkInterface == null) {
                return "";
            }
            byte[] addr = networkInterface.getHardwareAddress();


            for (byte b : addr) {
                buf.append(String.format("%02X:", b));
            }
            if (buf.length() > 0) {
                buf.deleteCharAt(buf.length() - 1);
            }
            macAddress = buf.toString();
        } catch (SocketException e) {
            e.printStackTrace();
            return "";
        }
        return macAddress;
    }

    
    public static void saveSystemId(String str, Context context) {
        File file = getSystemIdDir(context);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            Writer out = new OutputStreamWriter(fos, "UTF-8");
            out.write(str);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    
    public static String getMD5(String message, boolean upperCase) {
        String md5str = "";
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");

            byte[] input = message.getBytes();

            byte[] buff = md.digest(input);

            md5str = bytesToHex(buff, upperCase);

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

    public static String bytesToHex(byte[] bytes, boolean upperCase) {
        StringBuffer md5str = new StringBuffer();
        int digital;
        for (int i = 0; i < bytes.length; i++) {
            digital = bytes[i];

            if (digital < 0) {
                digital += 256;
            }
            if (digital < 16) {
                md5str.append("0");
            }
            md5str.append(Integer.toHexString(digital));
        }
        if (upperCase) {
            return md5str.toString().toUpperCase();
        }
        return md5str.toString().toLowerCase();
    }

    
    private static File getSystemIdDir(Context context) {
        File file = null;
        File dirs = new File(Environment.getExternalStorageDirectory(), CACHE_IMAGE_DIR);
        if (!dirs.exists()) {
            LogManager.i(TAG, "!dir.exists()");
//            dir.mkdirs();

            //适配android 9
            boolean isCreateDirsSuccess = DocumentManager.mkdirs(context, dirs);
            LogManager.i(TAG, "getSystemIdDir isCreateDirsSuccess*****" + isCreateDirsSuccess);
        }

        file = new File(dirs, DEVICES_FILE_NAME); // 用DEVICES_FILE_NAME给文件命名
        if (file.exists()) {
            LogManager.i(TAG, "getSystemIdDir file.exists()");
        } else {
            LogManager.i(TAG, "getSystemIdDir !file.exists()");
//            try {
//                file.createNewFile();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }

            //适配android 9
            boolean isCreateFileSuccess = DocumentManager.canWrite(file);
            LogManager.i(TAG, "getSystemIdDir isCreateFileSuccess*****" + isCreateFileSuccess);
        }
        return file;
    }

}

3.系統信息管理類。

package com.phone.common_library.manager;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.telephony.TelephonyManager;

import androidx.core.app.ActivityCompat;

import com.blankj.utilcode.util.DeviceUtils;

import java.util.Locale;
import java.util.UUID;

public class SystemManager {

    

    public static String getSystemLanguage() {
        return Locale.getDefault().getLanguage();
    }

    

    public static Locale[] getSystemLanguageList() {
        return Locale.getAvailableLocales();
    }

    

    public static String getSystemVersion() {
        return android.os.Build.VERSION.RELEASE;
    }

    

    public static String getSystemModel() {
        return android.os.Build.MODEL;
    }

    
    public static String getDeviceBrand() {
        return android.os.Build.BRAND;
    }

    

    public static String getIMEI(Context context) {
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Activity.TELEPHONY_SERVICE);
        if (telephonyManager != null) {
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return null;
            }
            return telephonyManager.getDeviceId();
        }
        return null;
    }

    
    public static String getDeviceCpuAbi() {
        return android.os.Build.CPU_ABI;
    }

    
    public static String getSystemId(Context context) {
        return SystemIdManager.getSystemId(context);
    }

    
    public static String getDeviceUUid() {
        String androidId = DeviceUtils.getAndroidID();
        UUID deviceUuid = new UUID(androidId.hashCode(), ((long) androidId.hashCode() << 32));
        return deviceUuid.toString();
    }

}

4.獲取系統數據。

        //手机厂商
        SystemManager.getDeviceBrand();
        //手机型号
        SystemManager.getSystemModel();
        //手机当前系统语言
        SystemManager.getSystemLanguage();
        //手机系统版本号
        SystemManager.getSystemVersion();
        //手机CPU架构
        SystemManager.getDeviceCpuAbi();
        //手機唯一識別碼
        SystemManager.getSystemId(mContext.getApplicationContext());

如对此有疑问,请联系qq1164688204。

推荐Android开源项目

项目功能介绍:RxJava2和Retrofit2项目,添加自动管理token功能,添加RxJava2生命周期管理,使用App架构设计是MVP模式和MVVM模式,同时使用组件化,部分代码使用Kotlin,此项目持续维护中。

项目地址:https://gitee.com/urasaki/RxJava2AndRetrofit2

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/936572.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号