安卓开发获取安卓设备信息工具类

以下是一个获取安卓设备信息的工具类:

```
import android.content.Context;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

public class DeviceInfoUtils {

    /**
     * 获取设备唯一标识符
     * @return
     */
    public static String getDeviceUniqueId(Context context) {
        String uniqueId = null;
        TelephonyManager telephonyManager = null;
        try {
            telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            uniqueId = telephonyManager.getDeviceId();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (uniqueId == null) {
            uniqueId = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
        }
        if (uniqueId == null) {
            uniqueId = UUID.randomUUID().toString();
        }
        MessageDigest sha;
        try {
            sha = MessageDigest.getInstance("SHA-1");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return uniqueId;
        }
        byte[] hash = sha.digest(uniqueId.getBytes());
        StringBuilder sb = new StringBuilder();
        for (byte b : hash) {
            sb.append(Integer.toHexString(b));
        }
        return sb.toString();
    }

    /**
     * 获取设备名称
     * @return
     */
    public static String getDeviceName() {
        return Build.MODEL;
    }

    /**
     * 获取设备系统版本
     * @return
     */
    public static String getDeviceOsVersion() {
        return Build.VERSION.RELEASE;
    }
}
```
在使用调用该工具类获取设备信息,例如:

```
String uniqueId = DeviceInfoUtils.getDeviceUniqueId(context);
String deviceName = DeviceInfoUtils.getDeviceName();
String deviceOsVersion = DeviceInfoUtils.getDeviceOsVersion();
``` 
请注意,不同的设备可能会返回不同的设备标识符,这个标识符也可能会随设备的恢复出厂设置而变化。因此,获取设备唯一标识符时需要谨慎处理。

  

posted @ 2023-04-22 21:12  今年我十八岁  阅读(65)  评论(0编辑  收藏  举报