Android获取APP当前进程的名称

1
2
3
4
5
6
7
8
9
10
11
12
13
public static String getProcessName(Context cxt, int pid) {
ActivityManager am = (ActivityManager) cxt.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> runningApps = am.getRunningAppProcesses();
if (runningApps == null) {
return null;
}
for (ActivityManager.RunningAppProcessInfo procInfo : runningApps) {
if (procInfo.pid == pid) {
return procInfo.processName;
}
}
return null;
}

在 Application 的 onCreate 中获取进程名称并进行相应的判断,例如:

1
2
3
4
5
6
7
//cn.appblog.demo
String processName = AppUtil.getProcessName(this, android.os.Process.myPid());

//判断进程名,保证只有主进程运行
if (!TextUtils.isEmpty(processName) && processName.equals(this.getPackageName())) {
//主进程初始化逻辑
}

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :