【发布时间】:2017-09-27 13:13:46
【问题描述】:
这是创建 ServiceConnection 接口的正常方式。如果我这样做,一切都会正常。
ServiceConnection mServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
但是,如果我使用下面的反射定义 ServiceConnection 接口,那么唯一调用的方法是hashCode()。
ServiceConnection mServiceConnection = (ServiceConnection) java.lang.reflect.Proxy.newProxyInstance(
ServiceConnection.class.getClassLoader(),
new java.lang.Class[] { ServiceConnection.class },
new java.lang.reflect.InvocationHandler() {
@Override
public Object invoke(Object proxy, java.lang.reflect.Method method, Object[] args) throws java.lang.Throwable {
log("methodName", method.getName());
return null;
}
});
用法是这样的:
applicationContext.bindService(serviceIntent, mServiceConnection, Context.BIND_AUTO_CREATE);
我在这里做错了什么?
更新
好的,这很奇怪...我使用了调试器,在 the line bindService() 上,调试器显示 mServiceConnection 为空,而在上一行中,我写了 log(Boolean.toString(mServiceConnection == null)),它打印为 false (!!??!!)。然后我把invoke方法的返回值改成return 1;
@Override
public Object invoke(Object proxy, java.lang.reflect.Method method, Object[] args) throws java.lang.Throwable {
log("methodName", method.getName());
return 1;
}
现在它可以工作了......同时这个接口的两个方法都是无效的。这里发生了什么?
【问题讨论】:
-
为什么需要使用反射来定义ServiceConnection?
-
出于安全考虑,为了让代码变得模糊,更难被检测到。
-
它工作得很好:这是我的 logcat 输出:
MainActivity D invoke public native int java.lang.Object.hashCode() MainActivity D invoke public abstract void android.content.ServiceConnection.onServiceConnected(android.cont -
我不是安全专家,但您仍然不能在运行时检测匿名类吗?代码不会在 .class 文件中,但我认为您仍然可以使用反射检查代码。此外,您仍然必须将通常放在 onServiceConnected/onServiceDisconnected 中的逻辑放在调用内部,这在我看来似乎违背了目的。
-
但实际上,你为什么不通过一些权限来保护你的服务呢?例如签名许可?还是
Binder#onTransact方法内的运行时检查?
标签: android reflection interface in-app-billing