话不多说直接上代码,代码含义注释里有
Method getRotation ;
Object IWindowManager ;
public void getRotation(){
try {
//加载得到ServiceManager类,然后得到方法getService。
Method getServiceMethod = Class.forName("android.os.ServiceManager").getDeclaredMethod("getService", new Class[]{String.class});
//通过getServiceMethod得到ServiceManager的实例(隐藏类,所以使用Object)
Object ServiceManager = getServiceMethod.invoke(null, new Object[]{"window"});
//通过反射的到Stub
Class<?> cStub = Class.forName("android.view.IWindowManager$Stub");
//得到Stub类的asInterface 方法
Method asInterface = cStub.getMethod("asInterface", IBinder.class);
//然后通过类似serviceManager.getIWindowManager的方法获取IWindowManager的实例
IWindowManager = asInterface.invoke(null, ServiceManager);
//通过IWindowManager的实例得到方法getRotation
getRotation = IWindowManager.getClass().getMethod("getRotation");
} catch (Exception e) {
Log.e("wmb", "--shutDown has an exception");
e.printStackTrace();
}
}
使用Method方法时,只需
int x = (int)getRotation.invoke(IWindowManager);
这里要注意的最后一句IWindowManager.getClass().getMethod(“getRotation”);中的getMethod方法,中的参数可以是多个的,看了一下源码
private Method getMethod(String name, Class<?>[] parameterTypes, boolean recursivePublicMethods)
throws NoSuchMethodException {
if (name == null) {
throw new NullPointerException("name == null");
}
if (parameterTypes == null) {
parameterTypes = EmptyArray.CLASS;
}
for (Class<?> c : parameterTypes) {
if (c == null) {
throw new NoSuchMethodException("parameter type is null");
}
}
Method result = recursivePublicMethods ? getPublicMethodRecursive(name, parameterTypes)
: getDeclaredMethodInternal(name, parameterTypes);
// Fail if we didn't find the method or it was expected to be public.
if (result == null ||
(recursivePublicMethods && !Modifier.isPublic(result.getAccessFlags()))) {
throw new NoSuchMethodException(name + " " + Arrays.toString(parameterTypes));
}
return result;
}
这里第二个参数parameterTypes,就是这个方法需要传入的参数类型。第三个参数默认就是true。
比如如果getRotation方法需要传入参数,那么获取这个方法时应该
getRotation = IWindowManager.getClass().getMethod("getRotation",boolean.class,String.class);
调用方法时就是
int x = (int)getRotation.invoke(IWindowManager,false,"param");
有错误的,多包涵,请赐教