3

我正在尝试发现向我发送意图的进程的进程 ID 或包名称。我不想将进程 ID 或包名称放在额外的位置(正如其他一些问题所问的那样),因为我不想允许欺骗。我使用的代码是:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_secure_file_share);
    ...   

    Intent intent = getIntent();

    if (intent != null)
    {
        // get the caller
        String callingPackage = getAppNameByPID(getApplicationContext(),
               Binder.getCallingPid());
    ....
    }
 }

wheregetAppNameByPID将 PID 转换为包名称。问题是它Binder.getCallingPid()总是返回接收者的 PID(而不是调用者的)。

你如何获得调用者的PID?

4

2 回答 2

7

我也试过这个,我只能使用绑定服务得到结果。

@Override
public IBinder onBind(Intent intent) {
    @SuppressWarnings("static-access")
    int uid = mBinder.getCallingUid();

    final PackageManager pm = getPackageManager();
    String name = pm.getNameForUid(uid);

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

    //name is your own package, not the caller

    return mBinder;
}

但是如果你实现你的 AIDL 的存根:

private final ITestService.Stub mBinder = new ITestService.Stub() {
    public void test() {
        //Get caller information
        //UID
        int 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 caller

        String[] 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));
        } 

        //PID
        int 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 将是最可靠的。

于 2012-09-07T13:19:57.657 回答
1

看一眼

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

于 2012-09-07T13:08:17.060 回答