Wednesday, April 9, 2008

Detecting if a Class/Package is available on the phone

You know Java ME has many optional packages that phones must have preinstalled over MIDP and CLDC. So, how can you compile one only code that detects on the fly if some class or API is available?

We can use the dynamic instantiation method, like this:

Code:
boolean MMAPIAvailable;
try {
// Try to instantiate a class using a string as the Class name
// so, the SDK without the API can compile the application
Class.forName("javax.microedition.media.Player").newInstance();
// If the next code is executed, then the API is available
MMAPIAvailable = true;
} catch ( ClassNotFoundException e) {
MMAPIAvailable = false;
}

No comments: