Android aidl客户端APP包名验证

实现代码如下

//这里实现了aidl中的抽象函数
private final IMyService.Stub mBinder = new IMyService.Stub() {
    
    @Override
    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
            throws RemoteException {
        // 包名未验证通过
        if (!hasPermission(this)) {
            return false;
        }
        return super.onTransact(code, data, reply, flags);
    }
};


// 调用者白名单
private String[] callerList = {"com.android.mms"};

public boolean hasPermission(Binder binder) {
    // 默认不允许通过
    boolean hasPermission = false;
    //
    String callerPackageName = null;
    // 获取调用者包名
    String[] packages = getPackageManager().getPackagesForUid(binder.getCallingUid());
    if (packages != null && packages.length > 0) {
        callerPackageName = packages[0];
    }
    if (!TextUtils.isEmpty(callerPackageName)) {
        for (int i = 0; i < callerList.length; i++) {
            // 有权限的调用者
            String permissionCaller = callerList[i];
            // 包名相同,则验证通过
            if (callerPackageName.startsWith(permissionCaller)) {
                hasPermission = true;
            }
        }
    }
    return hasPermission;
}

你可能感兴趣的:(Android代码)