如何检查android设备是否支持库? [英] How can i check if android device supports a library?

查看:106
本文介绍了如何检查android设备是否支持库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用IR blaster创建了一个Android应用程序,我希望我的代码检查Android设备是否支持这些库。当另一台设备安装我的应用程序时,它会崩溃。我怎么能避免这个?



我希望我的代码能够获得有关手机是否支持我的应用程序的信息。

解决方案

这与加载JDBC驱动程序类似。如果驱动程序不存在,您不希望崩溃整个应用程序。



解决方案的基本原则是使用 Class.forName()



这可以让你检查类是否存在,如果不存在则抛出异常。



编辑:



要清楚 - 之所以能够解决这个问题的原因以及为什么必要,如果Java无法执行代码,因为它不能有一个类,然后Java会将此视为灾难性故障(错误 - 特异性 NoClassDefFoundError )。因此,执行对缺少的类的任何直接引用都将引发此错误。根据文档


当抛出错误时,它们不应被应用程序代码捕获。


但是当 Class.forName()无法找到一个类(或更多直接调用 ClassLoader 抛出异常。因为这是一个例外,而不是错误,它可以被捕获。并且因为函数将String作为参数,所以您不需要直接引用该类(只需在字符串中给出它的名称),这样就可以在不直接引用类的情况下执行检查,从而不会导致程序崩溃。 / p>

I created an Android application with IR blaster and I want my code to check if an Android device supports these libraries. When another device installs my app, it crashes. How can I avoid this?

I want my code to get info about whether the phone supports my app.

解决方案

This is a similar problem to loading JDBC drivers. If the drivers don't exist you don't want to crash out your entire app.

The basic principle of the solution is to use Class.forName()

This lets you check if the class exists and throws an exception if it doesn't.

Edit:

To be clear - the reason why this works and why this is necessary is that if Java is unable to execute code because it doesn't have a class then Java will treat this as a catastrophic failure (an Error - specificity a NoClassDefFoundError). Therefore executing any direct reference to a missing class will throw this Error. According to the documentation:

When errors are thrown, they should not be caught by application code.

However when Class.forName() is unable to find a class (or more direct calls to a ClassLoader) an Exception is thrown. Because this is an exception and not an Error it can be caught. And because the function takes a String as an argument, you don't need to directly reference the class (just give it's name in the string) so the check can be performed without directly referencing the class and thus without crashing out your program.

这篇关于如何检查android设备是否支持库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆