How can i check if android device supports a libra

2020-07-26 06:10发布

问题:

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.