Is there a way to get current process name in Android

后端 未结 11 1812
-上瘾入骨i
-上瘾入骨i 2020-12-03 00:59

I set an Android:process=\":XX\" for my particular activity to make it run in a separate process. However when the new activity/process init, it will call my Application:onC

11条回答
  •  长情又很酷
    2020-12-03 01:34

    To wrap up different approaches of getting process name using Kotlin:

    Based on the https://stackoverflow.com/a/21389402/3256989 (/proc/pid/cmdline):

        fun getProcessName(): String? =
            try {
                FileInputStream("/proc/${Process.myPid()}/cmdline")
                    .buffered()
                    .readBytes()
                    .filter { it > 0 }
                    .toByteArray()
                    .inputStream()
                    .reader(Charsets.ISO_8859_1)
                    .use { it.readText() }
            } catch (e: Throwable) {
                null
            }
    
    

    Based on https://stackoverflow.com/a/55549556/3256989 (from SDK v.28 (Android P)):

      fun getProcessName(): String? = 
        if (VERSION.SDK_INT >= VERSION_CODES.P) Application.getProcessName() else null
    

    Based on https://stackoverflow.com/a/45960344/3256989 (reflection):

        fun getProcessName(): String? =
            try {
                val loadedApkField = application.javaClass.getField("mLoadedApk")
                loadedApkField.isAccessible = true
                val loadedApk = loadedApkField.get(application)
    
                val activityThreadField = loadedApk.javaClass.getDeclaredField("mActivityThread")
                activityThreadField.isAccessible = true
                val activityThread = activityThreadField.get(loadedApk)
    
                val getProcessName = activityThread.javaClass.getDeclaredMethod("getProcessName")
                getProcessName.invoke(activityThread) as String
            } catch (e: Throwable) {
                null
            }
    

    Based on https://stackoverflow.com/a/19632382/3256989 (ActivityManager):

        fun getProcessName(): String? {
            val pid = Process.myPid()
            val manager = appContext.getSystemService(Context.ACTIVITY_SERVICE) as? ActivityManager
            return manager?.runningAppProcesses?.filterNotNull()?.firstOrNull { it.pid == pid }?.processName
        }
    

提交回复
热议问题