Android Library 目标编译和后续 Android 版本中的对象

发布于 2024-12-10 07:06:13 字数 481 浏览 0 评论 0原文

我正在构建一个 Android 库,并且有一种方法来获取有关设备的一些信息。我们的目标是支持 2.2 及更高版本,但想知道是否有一种方法可以收集更高版本中引入的信息(2.3 中的设备序列),并使用 2.2 版本设置应用程序进行编译。

四处搜索后,我发现人们使用如下代码:

private static String getHardwareSerial() {
    try {  
        return Build.SERIAL;
    } catch (VerifyError e) {
        //Android 8 and previous did not have this information
        return Build.UNKNOWN;  
    }
}

然而,有了这段代码,当将构建目标设置为 8 时,使用我们库的示例应用程序无法构建。有什么建议吗?或者我们是否必须接受我们的客户将其目标设置为 9获取此信息?

I am building an Android Library and have a method getting some information about the device. Our target is to support 2.2 and up but was wondering if there is a way to collect information introduced in later versions (ex device serial in 2.3) and have the application set with version 2.2 to compile.

After searching around I found people using code like:

private static String getHardwareSerial() {
    try {  
        return Build.SERIAL;
    } catch (VerifyError e) {
        //Android 8 and previous did not have this information
        return Build.UNKNOWN;  
    }
}

However, with this code present, my sample application using our library fails to build when setting the build target to 8. Any suggestions or do we have to live with our clients setting their target to 9 to get this info?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

绮烟 2024-12-17 07:06:13

您可以通过反射来完成此操作:

public static String getHardwareSerial() {
    try {
        Field serialField = Build.class.getDeclaredField("SERIAL");
        return (String)serialField.get(null);
    }
    catch (NoSuchFieldException nsf) {
    } 
    catch (IllegalAccessException ia) {
    }
    return Build.UNKNOWN;
}

如果未找到该字段(在早期版本的操作系统上),它将抛出一个异常,该异常将被忽略,然后返回 Build.UNKNOWN。

You could do it through reflection:

public static String getHardwareSerial() {
    try {
        Field serialField = Build.class.getDeclaredField("SERIAL");
        return (String)serialField.get(null);
    }
    catch (NoSuchFieldException nsf) {
    } 
    catch (IllegalAccessException ia) {
    }
    return Build.UNKNOWN;
}

If the field isn't found (on earlier versions of the OS) it'll throw an exception that will be ignored and then fall through to return Build.UNKNOWN.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文