Skip to content Skip to sidebar Skip to footer

Pid For The Process That Sent An Intent

I am trying to discover the process id or package name of the process that sent me an intent. I don't want to put the process id or package name in an extra (as some other questio

Solution 1:

I tried this as well and I could only get a result using bound services.

@Overridepublic IBinder onBind(Intent intent) {
    @SuppressWarnings("static-access")intuid= mBinder.getCallingUid();

    finalPackageManagerpm= getPackageManager();
    Stringname= pm.getNameForUid(uid);

    Log.d("ITestService", String.format("onBind: calling name: %s"), name);

    //name is your own package, not the callerreturn mBinder;
}

But if you implement the Stub of your AIDL:

privatefinal ITestService.Stub mBinder = new ITestService.Stub() {
    publicvoid test() {
        //Get caller information//UIDint uid = Binder.getCallingUid();

        final PackageManager pm = getPackageManager();
        String name = pm.getNameForUid(uid);        
        //name will be sharedUserId of caller, OR if not set the package name of the callerString[] packageNames = pm.getPackagesForUid(uid);
        //packageNames is a array of packages using that UID, could be more than 1 if using sharedUserIds

        Log.d("ITestService", String.format("Calling uid: %d (getNameForUid: %s)", uid, name));
        for (String packageName : packageNames) {
            Log.d("ITestService", String.format("getPackagesForUid: %s", packageName));
        } 

        //PIDint pid = Binder.getCallingPid();
        Log.d("ITestService", String.format("Calling pid: %d", pid));
        String processName = "";

        ActivityManager am = (ActivityManager) getSystemService( ACTIVITY_SERVICE );
        List<ActivityManager.RunningAppProcessInfo> processes = am.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo proc : processes) {
            if (proc.pid == pid) {
                processName = proc.processName;
                Log.d("ITestService", String.format("Found ProcessName of pid(%d): %s", pid, processName));

                //processName will be the package name of the caller, YEAH!
            }
        }
    }
}

PID will be the most reliable one if you want to know which package called it.

Solution 2:

take a look at

http://developer.android.com/reference/android/app/ActivityManager.RunningAppProcessInfo.html

Post a Comment for "Pid For The Process That Sent An Intent"