Is there a way to get current process name in Android

后端 未结 11 1798
-上瘾入骨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:15

    The ActivityManager solution contains a sneaky bug, particularly if you check your own process name from your Application object. Sometimes, the list returned from getRunningAppProcesses simply doesn't contain your own process, raising a peculiar existential issue.

    The way I solve this is

        BufferedReader cmdlineReader = null;
        try {
            cmdlineReader = new BufferedReader(new InputStreamReader(
                new FileInputStream(
                    "/proc/" + android.os.Process.myPid() + "/cmdline"),
                "iso-8859-1"));
            int c;
            StringBuilder processName = new StringBuilder();
            while ((c = cmdlineReader.read()) > 0) {
                processName.append((char) c);
            }
            return processName.toString();
        } finally {
            if (cmdlineReader != null) {
                cmdlineReader.close();
            }
        }
    

    EDIT: Please notice that this solution is much faster than going through the ActivityManager but does not work if the user is running Xposed or similar. In that case you might want to do the ActivityManager solution as a fallback strategy.

提交回复
热议问题