How can i check if android device supports a library?

百般思念 提交于 2019-12-09 21:59:22

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/17002421/how-can-i-check-if-android-device-supports-a-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!