Search code examples
androidandroid-actionbar-compat

getWindow().hasFeature() on API < 11


I need to check if the overlay feature has been set on an ActionBarCompat instance. The getWindow().hasFeature() method is only available on API 11 and up.

How can I check the feature on API < 11 ?

EDIT: Based on the comment, the getFeatures method should be available from API 1 but it is protected scope and I need to access the feature from another class. The hasFeature method, the one I need to use, on the other hand is API 11 and above only. This is what Android Studio shows me and the app crashes on a 2.3.3 device.

Image from AS

FYI, the activity class used here is a custom class that extends ActionBarActivity from the ActionBarCompat library. Don't know if that should make a difference.


Solution

  • You can access private methods using The Reflection API.

    boolean hasFeature(int feature) {
        Window window = getWindow(); //get the window instance.
        if (android.os.Build.VERSION.SDK_INT >= 11) { // if we are running api level 11 and later
            return window.hasFeature(feature); //call hasFeature
        } else {
            try {
                Class c = window.getClass();
                Method getFeatures = c.getDeclaredMethod("getFeatures");//get the getFeatures method using reflection
                getFeatures.setAccessible(true);//make it public
                Integer features = getFeatures.invoke(window, null); //invoke it
                return (features.intValue() & (1 << feature)) != 0; //check if we have the feature and return the result.
            } catch (Exception e) {
                return false;//in case invocation fails with any reason
            }
        }
    }