How to get application package name or UID which is trying to bind my service from onBind function?

前端 未结 6 1929
说谎
说谎 2020-12-03 03:17

I have a service in an application, and I can reach this service from different applications. And when applications are tried to bind this service I want to know which appli

6条回答
  •  甜味超标
    2020-12-03 03:49

    The accepted answer was not quite right! Why? If two or more applications use the same android:sharedUserId, the method Binder.getCallingUid() will return a same uid and getPackageManager().getNameForUid(uid) will return a same string, it looks like: com.codezjx.demo:10058, but is not a package name!

    The right way is use the pid:

    int pid = Binder.getCallingPid();
    

    And then use pid to get package name by ActivityManager, each process can hold multiple packages, so it looks like:

    private String[] getPackageNames(Context context, int pid) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List infos = am.getRunningAppProcesses();
        if (infos != null && infos.size() > 0) {
            for(RunningAppProcessInfo info : infos) {
                if(info.pid == pid) {
                    return info.pkgList;
                }
            }
        }
        return null;
    }
    

    Warnning: When using method Binder.getCallingPid() and if the current thread is not currently executing an incoming transaction, then its own pid is returned. That means you need to call this method in AIDL exposed interface method.

提交回复
热议问题