前言
反射是很常用的一种方式。
今天就记录一下,反射ServiceManager的addService()和getService()。
如果不反射,需要引入
正常情况下,如果没有系统源码的编译,不太可能拿到framework_classes.jar。
正文
我是一个lib库中需要这个ServiceManager的添加和获取服务方法,不太想导入framework_classes.jar,因此才考虑反射。
addService()
- public static void addService(String name, IBinder binder) {
- try {
- Class<?> forName = Class.forName("android.os.ServiceManager");
- Method method = forName.getMethod("addService", String.class, IBinder.class);
- method.invoke(null, name, binder);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
getService()
- private static IBinder getService(String name) {
- try {
- Class<?> forName = Class.forName("android.os.ServiceManager");
- Method method = forName.getMethod("getService", String.class);
- return (IBinder) method.invoke(null, name);
- } catch (Exception e) {
- e.printStackTrace();
- }
- return null;
- }
参考文章
《
历史上的今天
© 版权声明