javaandroidreflectionandroid-5.0-lollipoppowermanager

Call setPowerSaveMode of PowerManager class with reflection


I will call a method of the public final class PowerManager with @hide annotation.

the method is:

/**
 * Set the current power save mode.
 *
 * @return True if the set was allowed.
 *
 * @see #isPowerSaveMode()
 *
 * @hide
 */
public boolean setPowerSaveMode(boolean mode) {
    try {
        return mService.setPowerSaveMode(mode);
    } catch (RemoteException e) {
        return false;
    }
}

In my code I tried to call the method with reflection:

    Class c;
    try {
        c = Class.forName("android.os.PowerManager");
        Method m = c.getMethod("setPowerSaveMode", new Class[]{Boolean.class});
        Boolean response = (Boolean) m.invoke(true);
        Log.d("test", "invoked?: " + response);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }

but I run out with java.lang.NoSuchMethodException: setPowerSaveMode [class java.lang.Boolean].

Where am I wrong? How can I call this method?

Thank you in advance!


Solution

  • I've got solution with this code:

        PowerManager powerManager = (PowerManager) this.getSystemService(Context.POWER_SERVICE);        
        //NEED ROOT PERMISSION :( permission nedded: android.permission.DEVICE_POWER (only system app)
        Class c;
        try {
            c = Class.forName("android.os.PowerManager");
            Method[] ar = c.getDeclaredMethods();
            for (Method m : ar) {
                Log.d("test", "we have: "+m.getName());
                if (m.getName().equalsIgnoreCase("setPowerSaveMode")) {
                    Boolean response = (Boolean) m.invoke(powerManager, true);
                    Log.d("test", "invoked?: " + response);
                }
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    

    But need permission android.permission.DEVICE_POWER only for system app.