1.1 Java层
int pid = Binder.getCallingPid();
int uid = Binder.getCallingUid();
String callingApp = mContext.getPackageManager().getNameForUid(uid);
还可通过ActivityManager来跟进进程PID来获取进程名
public String getProcessNanmeByPid(int pid) {
ActivityManager mActivityManager = (ActivityManager) getContext().getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningAppProcessInfo appProcess : mActivityManager
.getRunningAppProcesses()) {
if (appProcess.pid == pid) {
return appProcess.processName;
}
}
return null;
}
1.2 C++层
#include <binder/IPCThreadState.h>
int pid = IPCThreadState::self()->getCallingPid();
int uid = IPCThreadState::self()->getCallingUid();
获取进程名(需要有读取proc目录的权限)
static int getprocname(pid_t pid, char *buf, size_t len) {
char filename[20];
FILE *f;
sprintf(filename, "/proc/%d/cmdline", pid);
f = fopen(filename, "r");
if (!f) { *buf = '\0'; return 1; }
if (!fgets(buf, len, f)) { *buf = '\0'; return 2; }
fclose(f);
return 0;
}