From ff16db811ead25402f942a22a7e207ebd93112e7 Mon Sep 17 00:00:00 2001 From: Quyunshuo Date: Tue, 16 Mar 2021 09:41:44 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=B7=BB=E5=8A=A0=E8=BF=9B=E7=A8=8B?= =?UTF-8?q?=E5=88=A4=E6=96=AD=E5=B7=A5=E5=85=B7=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/quyunshuo/base/utils/ProcessUtils.kt | 74 +++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 Lib_Base/src/main/java/com/quyunshuo/base/utils/ProcessUtils.kt diff --git a/Lib_Base/src/main/java/com/quyunshuo/base/utils/ProcessUtils.kt b/Lib_Base/src/main/java/com/quyunshuo/base/utils/ProcessUtils.kt new file mode 100644 index 0000000..8451c2c --- /dev/null +++ b/Lib_Base/src/main/java/com/quyunshuo/base/utils/ProcessUtils.kt @@ -0,0 +1,74 @@ +package com.quyunshuo.base.utils + +import android.app.ActivityManager +import android.content.Context +import android.content.pm.PackageManager +import android.os.Process +import kotlin.jvm.Throws + +/** + * 进程工具类 + * + * @author Qu Yunshuo + * @since 3/16/21 9:06 AM + */ +object ProcessUtils { + + /** + * 获取当前App所有进程 + * + * @param context Context 上下文 + * @return List 当前App所有进程 + */ + fun getRunningAppProcessList(context: Context): List { + val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager + return activityManager.runningAppProcesses + } + + /** + * 判断该进程id是否属于该进程名的进程 + * + * @param context Context 上下文 + * @param processId Int 进程Id + * @param processName String 进程名 + * @return Boolean + */ + fun isPidOfProcessName(context: Context, processId: Int, processName: String): Boolean { + // 遍历所有进程找到该进程id对应的进程 + for (process in getRunningAppProcessList(context)) { + if (process.pid == processId) { + // 判断该进程id是否和进程名一致 + return (process.processName == processName) + } + break + } + return false + } + + /** + * 获取主进程名 + * + * @param context Context 上下文 + * @return String 主进程名 + * @throws PackageManager.NameNotFoundException if a package with the given name cannot be found on the system. + */ + @Throws(PackageManager.NameNotFoundException::class) + fun getMainProcessName(context: Context): String { + val applicationInfo = context.packageManager.getApplicationInfo(context.packageName, 0) + return applicationInfo.processName + } + + /** + * 判断当前进程是否是主进程 + * + * @param context Context 上下文 + * @return Boolean + * @throws PackageManager.NameNotFoundException if a package with the given name cannot be found on the system. + */ + @Throws(PackageManager.NameNotFoundException::class) + fun isMainProcess(context: Context): Boolean { + val processId = Process.myPid() + val mainProcessName = getMainProcessName(context) + return isPidOfProcessName(context, processId, mainProcessName) + } +} \ No newline at end of file