我通过AIDL机制公开了一些API。客户端需要绑定到AIDL并同步调用方法。有没有办法可以检索客户端的Java包名?
例如,如果我将方法boolean isFooAvailable()
公开为AIDL API,则从isFooAvalable的实现中,我可以确定绑定到AIDL服务的应用程序的Java包名称吗?
答案 0 :(得分:0)
是的,您可以在实现中找到包名称,如下所示:
IAidl.Stub mBinder = new IAidl.Stub() {
@Override
public boolean isFooAvailable() throws RemoteException {
String pkgName = "";
int pid = Binder.getCallingPid();
ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> processes = am.getRunningAppProcesses();
for (ActivityManager.RunningAppProcessInfo proc : processes) {
if (proc.pid == pid) {
pkgName = proc.processName;
}
}
// package name of calling application package
Log.e("Package Name", pkgName);
return false;
}
}
与UID相比,通过PID查找包名是最好的方法。
答案 1 :(得分:0)
在您的Service
内使用CommonsWare给出的注释进行扩展
PackageManager packageManager = context.getPackageManager();
String callingName = packageManager.getNameForUid(Binder.getCallingUid());
如果您想限制呼叫者的访问权限,还应该检查呼叫应用程序的证书。
PackageInfo callingPackageInfo = packageManager
.getPackageInfo(callingPackage, PackageManager.GET_SIGNATURES);
// Make sure to check there is only one signature, or you may run into a security
// vulnerability: https://androidvulnerabilities.org/vulnerabilities/Fake_ID
verify(callingPackageInfo.signatures);