Android Gets package name call interface

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/myvest/article/details/73821941

In the framework layer, sometimes, you need to get the package name call interface, to do something different for the apk processing logic. Met today to get the package name by PID, the result is wrong, write code to test his colleagues say this is normal.
Let's look at this code

    private String getCallerProcessName() {
        if (null == mContext) {
            return "";
        }
        int pid = Binder.getCallingPid();
        ActivityManager manager = (ActivityManager)mContext.getSystemService(Context.ACTIVITY_SERVICE);
        for (RunningAppProcessInfo processInfo : manager.getRunningAppProcesses()) {
            if (processInfo.pid == pid) {
                Log.d(TAG, "processName: " + processInfo.processName);
                return processInfo.processName;
            }
        }
        return "";
    }

Basically by getting the caller's PID, by traversing the currently running app to get the package name. In fact, the code is problematic, because a apk, not necessarily only one process, that there may be multiple PID. I tested for that case, the process is called app_process, so after traversal, and can not get the package name apk, and the situation is only my colleagues just a process, it is naturally no problem.

How to modify it? More accurate method is to use the UID to be judged, we know that in android, each process has one and only one UID.

    private String getCallerProcessName() {
        int uid = Binder.getCallingUid();
        String callingApp = mContext.getPackageManager().getNameForUid(uid);
        Log.d(TAG, "callingApp: " + callingApp);
        if(callingApp != null){
            return callingApp;
        }
        return "";
    }   

Guess you like

Origin blog.csdn.net/myvest/article/details/73821941