Android设备有唯一的ID吗?如果有,使用Java访问它的简单方法是什么?


当前回答

是的,每个Android设备都有一个唯一的序列号,你可以从这个代码中得到它。Build.SERIAL。请注意,它只是在API级别9中添加的,可能不会出现在所有设备上。要在早期平台上获得唯一ID,您需要读取MAC地址或IMEI等信息。

其他回答

这里有相当有用的信息。

它包括五种不同的ID类型:

IMEI(仅适用于使用手机的Android设备;需要Android.permission.READ_Phone_STATE)伪唯一ID(适用于所有Android设备)Android ID(可以为空,可以在工厂重置时更改,可以在根手机上更改)WLAN MAC地址字符串(需要android.permission.ACCESS_WIFI_STATE)BT MAC地址字符串(带蓝牙的设备,需要android.permission.蓝牙)

有关如何为安装应用程序的每个Android设备获取唯一标识符的详细说明,请参阅官方Android开发者博客“识别应用程序安装”。

似乎最好的方法是在安装时自己生成一个,然后在重新启动应用程序时读取它。

我个人认为这是可以接受的,但并不理想。Android提供的标识符在所有情况下都不起作用,因为大多数都取决于手机的无线电状态(Wi-Fi开/关、手机开/关和蓝牙开/关)。其他设置(如Settings.Secure.ANDROID_ID)必须由制造商实现,并且不保证是唯一的。

以下是将数据写入安装文件的示例,该文件将与应用程序本地保存的任何其他数据一起存储。

public class Installation {
    private static String sID = null;
    private static final String INSTALLATION = "INSTALLATION";

    public synchronized static String id(Context context) {
        if (sID == null) {
            File installation = new File(context.getFilesDir(), INSTALLATION);
            try {
                if (!installation.exists())
                    writeInstallationFile(installation);
                sID = readInstallationFile(installation);
            } 
            catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return sID;
    }

    private static String readInstallationFile(File installation) throws IOException {
        RandomAccessFile f = new RandomAccessFile(installation, "r");
        byte[] bytes = new byte[(int) f.length()];
        f.readFully(bytes);
        f.close();
        return new String(bytes);
    }

    private static void writeInstallationFile(File installation) throws IOException {
        FileOutputStream out = new FileOutputStream(installation);
        String id = UUID.randomUUID().toString();
        out.write(id.getBytes());
        out.close();
    }
}

要获取用户id,您可以使用Google Play授权库。

要下载此库,请打开SDK管理器=>SDK工具。下载的库文件的路径为:

path_to_android_sdk_on_your_pc/extras/google/market_licensing/library

将库包含在项目中(只需复制其文件)。

接下来,您需要一些策略接口的实现(只需使用库中的两个文件之一:ServerManagedPolicy或StrictPolicy)。

将在processServerResponse()函数中为您提供用户id:

public void processServerResponse(int response, ResponseData rawData) {
    if(rawData != null) {
        String userId = rawData.userId
        // use/save the value
    }
    // ...
}

接下来,需要使用策略构造LicenseChecker,并调用checkAccess()函数。使用MainActivity.java作为示例说明如何执行此操作。MainActivity.ava位于以下文件夹中:

path_to_android_sdk_on_your_pc/extras/google/market_licensing/sample/src.com/sample/android/market/licensing

不要忘记将CHECK_LICENSE权限添加到AndroidManifest.xml。

有关授权库的详细信息:https://developer.android.com/google/play/licensing

为了完整起见,以下是如何在Xamarin.Android和C#中获取Id:

var id = Settings.Secure.GetString(ContentResolver, Settings.Secure.AndroidId);

或者如果您不在“活动”中:

var id = Settings.Secure.GetString(context.ContentResolver, Settings.Secure.AndroidId);

其中上下文是传入的上下文。

官方Android开发者博客现在有一篇关于这个主题的完整文章,即“识别应用程序安装”。