The accepted answer was not quite right! Why? If two or more applications use the same android:sharedUserId
, the method Binder.getCallingUid()
will return a same uid and getPackageManager().getNameForUid(uid)
will return a same string, it looks like: com.codezjx.demo:10058, but is not a package name!
The right way is use the pid:
int pid = Binder.getCallingPid();
And then use pid to get package name by ActivityManager
, each process can hold multiple packages, so it looks like:
private String[] getPackageNames(Context context, int pid) {
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningAppProcessInfo> infos = am.getRunningAppProcesses();
if (infos != null && infos.size() > 0) {
for(RunningAppProcessInfo info : infos) {
if(info.pid == pid) {
return info.pkgList;
}
}
}
return null;
}
Warnning: When using method Binder.getCallingPid()
and if the current thread is not currently executing an incoming transaction, then its own pid is returned. That means you need to call this method in AIDL exposed interface method.