Example usage for android.content.pm PackageManager getPackagesForUid

List of usage examples for android.content.pm PackageManager getPackagesForUid

Introduction

In this page you can find the example usage for android.content.pm PackageManager getPackagesForUid.

Prototype

public abstract @Nullable String[] getPackagesForUid(int uid);

Source Link

Document

Retrieve the names of all packages that are associated with a particular user id.

Usage

From source file:net.sf.xfd.provider.PublicProvider.java

@Override
public Uri canonicalize(@NonNull Uri uri) {
    try {//from w ww. java2 s. c om
        base.assertAbsolute(uri);

        String grantMode = uri.getQueryParameter(URI_ARG_MODE);
        if (TextUtils.isEmpty(grantMode)) {
            grantMode = "r";
        }

        verifyMac(uri, grantMode, grantMode);

        final int flags = ParcelFileDescriptor.parseMode(grantMode);

        final Context context = getContext();
        assert context != null;

        final String packageName = context.getPackageName();

        final Uri canon = DocumentsContract.buildDocumentUri(packageName + FileProvider.AUTHORITY_SUFFIX,
                canonString(uri.getPath()));

        final int callerUid = Binder.getCallingUid();

        if (callerUid != Process.myUid()) {
            int grantFlags = Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION;

            if ((flags & ParcelFileDescriptor.MODE_READ_ONLY) == flags) {
                grantFlags |= Intent.FLAG_GRANT_READ_URI_PERMISSION;
            } else if ((flags & ParcelFileDescriptor.MODE_WRITE_ONLY) == flags)
                grantFlags |= Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
            else {
                grantFlags |= Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
                grantFlags |= Intent.FLAG_GRANT_READ_URI_PERMISSION;
            }

            final String[] packages;

            final String caller = getCallingPackage();
            if (caller != null) {
                packages = new String[] { caller };
            } else {
                final PackageManager pm = context.getPackageManager();
                packages = pm.getPackagesForUid(callerUid);
            }

            if (packages != null) {
                for (String pkg : packages) {
                    context.grantUriPermission(pkg, canon, grantFlags);
                }
            }
        }

        return canon;
    } catch (FileNotFoundException e) {
        return null;
    }
}

From source file:androidx.media.MediaBrowserServiceCompat.java

/**
 * Return whether the given package is one of the ones that is owned by the uid.
 *///  w  ww  .j  a  v a2 s  .c  om
boolean isValidPackage(String pkg, int uid) {
    if (pkg == null) {
        return false;
    }
    final PackageManager pm = getPackageManager();
    final String[] packages = pm.getPackagesForUid(uid);
    final int N = packages.length;
    for (int i = 0; i < N; i++) {
        if (packages[i].equals(pkg)) {
            return true;
        }
    }
    return false;
}

From source file:me.piebridge.bible.Bible.java

private void checkApkData() {
    Log.d(TAG, "checking apkdata");
    try {/*  w w w .  jav  a 2s.co  m*/
        String packageName = mContext.getPackageName();
        PackageManager pm = mContext.getPackageManager();
        SharedPreferences preference = PreferenceManager.getDefaultSharedPreferences(mContext);
        ApplicationInfo ai = pm.getApplicationInfo(packageName, 0);
        for (String applicationName : pm.getPackagesForUid(ai.uid)) {
            if (packageName.equals(applicationName)) {
                continue;
            }

            // version
            String version = applicationName.replace(packageName + ".", "");

            // resources
            Resources resources = mContext
                    .createPackageContext(applicationName, Context.CONTEXT_IGNORE_SECURITY).getResources();

            // newVersion
            int versionCode = pm.getPackageInfo(applicationName, 0).versionCode;
            boolean newVersion = (preference.getInt(version, 0) != versionCode);

            // resid
            int resid = resources.getIdentifier("a", "raw", applicationName);
            if (resid == 0) {
                resid = resources.getIdentifier("xa", "raw", applicationName);
            }
            if (resid == 0) {
                Log.d(TAG, "package " + applicationName + " has no R.raw.a nor R.raw.xa");
                continue;
            }

            // file
            File file;
            if (versionpaths.containsKey(version)) {
                file = new File(versionpaths.get(version));
            } else {
                file = new File(getExternalFilesDirWrapper(), version + ".sqlite3");
            }
            if (file.exists() && !file.isFile()) {
                file.delete();
            }

            boolean unpack = unpackRaw(resources, newVersion, resid, file);
            if (newVersion && unpack) {
                preference.edit().putInt(version, versionCode).commit();
            }
        }
    } catch (Exception e) {
        Log.e(TAG, "", e);
    }
}

From source file:eu.faircode.netguard.ServiceSinkhole.java

public void notifyNewApplication(int uid) {
    if (uid < 0)
        return;//from  w  w w .j  a  v a  2 s. c  o m

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    try {
        // Get application name
        String name = TextUtils.join(", ", Util.getApplicationNames(uid, this));

        // Get application info
        PackageManager pm = getPackageManager();
        String[] packages = pm.getPackagesForUid(uid);
        if (packages == null || packages.length < 1)
            throw new PackageManager.NameNotFoundException(Integer.toString(uid));
        boolean internet = Util.hasInternet(uid, this);

        // Build notification
        Intent main = new Intent(this, ActivityMain.class);
        main.putExtra(ActivityMain.EXTRA_REFRESH, true);
        main.putExtra(ActivityMain.EXTRA_SEARCH, Integer.toString(uid));
        PendingIntent pi = PendingIntent.getActivity(this, uid, main, PendingIntent.FLAG_UPDATE_CURRENT);

        TypedValue tv = new TypedValue();
        getTheme().resolveAttribute(R.attr.colorPrimary, tv, true);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_security_white_24dp).setContentIntent(pi).setColor(tv.data)
                .setAutoCancel(true);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
            builder.setContentTitle(name).setContentText(getString(R.string.msg_installed_n));
        else
            builder.setContentTitle(getString(R.string.app_name))
                    .setContentText(getString(R.string.msg_installed, name));

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
            builder.setCategory(Notification.CATEGORY_STATUS).setVisibility(Notification.VISIBILITY_SECRET);

        // Get defaults
        SharedPreferences prefs_wifi = getSharedPreferences("wifi", Context.MODE_PRIVATE);
        SharedPreferences prefs_other = getSharedPreferences("other", Context.MODE_PRIVATE);
        boolean wifi = prefs_wifi.getBoolean(packages[0], prefs.getBoolean("whitelist_wifi", true));
        boolean other = prefs_other.getBoolean(packages[0], prefs.getBoolean("whitelist_other", true));

        // Build Wi-Fi action
        Intent riWifi = new Intent(this, ServiceSinkhole.class);
        riWifi.putExtra(ServiceSinkhole.EXTRA_COMMAND, ServiceSinkhole.Command.set);
        riWifi.putExtra(ServiceSinkhole.EXTRA_NETWORK, "wifi");
        riWifi.putExtra(ServiceSinkhole.EXTRA_UID, uid);
        riWifi.putExtra(ServiceSinkhole.EXTRA_PACKAGE, packages[0]);
        riWifi.putExtra(ServiceSinkhole.EXTRA_BLOCKED, !wifi);

        PendingIntent piWifi = PendingIntent.getService(this, uid, riWifi, PendingIntent.FLAG_UPDATE_CURRENT);
        NotificationCompat.Action wAction = new NotificationCompat.Action.Builder(
                wifi ? R.drawable.wifi_on : R.drawable.wifi_off,
                getString(wifi ? R.string.title_allow_wifi : R.string.title_block_wifi), piWifi).build();
        builder.addAction(wAction);

        // Build mobile action
        Intent riOther = new Intent(this, ServiceSinkhole.class);
        riOther.putExtra(ServiceSinkhole.EXTRA_COMMAND, ServiceSinkhole.Command.set);
        riOther.putExtra(ServiceSinkhole.EXTRA_NETWORK, "other");
        riOther.putExtra(ServiceSinkhole.EXTRA_UID, uid);
        riOther.putExtra(ServiceSinkhole.EXTRA_PACKAGE, packages[0]);
        riOther.putExtra(ServiceSinkhole.EXTRA_BLOCKED, !other);
        PendingIntent piOther = PendingIntent.getService(this, uid + 10000, riOther,
                PendingIntent.FLAG_UPDATE_CURRENT);
        NotificationCompat.Action oAction = new NotificationCompat.Action.Builder(
                other ? R.drawable.other_on : R.drawable.other_off,
                getString(other ? R.string.title_allow_other : R.string.title_block_other), piOther).build();
        builder.addAction(oAction);

        // Show notification
        if (internet)
            NotificationManagerCompat.from(this).notify(uid, builder.build());
        else {
            NotificationCompat.BigTextStyle expanded = new NotificationCompat.BigTextStyle(builder);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
                expanded.bigText(getString(R.string.msg_installed_n));
            else
                expanded.bigText(getString(R.string.msg_installed, name));
            expanded.setSummaryText(getString(R.string.title_internet));
            NotificationManagerCompat.from(this).notify(uid, expanded.build());
        }

    } catch (PackageManager.NameNotFoundException ex) {
        Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
    }
}

From source file:com.github.michalbednarski.intentslab.AppComponentsFragment.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mPackageName = ((AppInfoHost) getActivity()).getViewedPackageName();

    final PackageManager packageManager = getActivity().getPackageManager();

    ArrayList<Integer> presentSections = new ArrayList<Integer>();

    try {//ww w.j  a va2  s. co  m
        final PackageInfo packageInfo = packageManager.getPackageInfo(mPackageName,
                PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS | PackageManager.GET_SERVICES
                        | PackageManager.GET_PROVIDERS | PackageManager.GET_PERMISSIONS);

        // Scan activities and group them as exported and not exported
        {
            ArrayList<ActivityInfo> exportedActivities = new ArrayList<ActivityInfo>();
            ArrayList<ActivityInfo> notExportedActivities = new ArrayList<ActivityInfo>();

            if (packageInfo.activities != null && packageInfo.activities.length != 0) {
                for (ActivityInfo activity : packageInfo.activities) {
                    (activity.exported ? exportedActivities : notExportedActivities).add(activity);
                }
            }

            if (exportedActivities.size() != 0) {
                mActivities = exportedActivities.toArray(new ComponentInfo[exportedActivities.size()]);
                presentSections.add(SECTION_ACTIVITIES);
            }
            if (notExportedActivities.size() != 0) {
                mActivitiesNotExported = notExportedActivities
                        .toArray(new ComponentInfo[notExportedActivities.size()]);
                presentSections.add(SECTION_ACTIVITIES_NOT_EXPORTED);
            }
        }

        // Check receivers, services and providers
        if (packageInfo.receivers != null) {
            mReceivers = packageInfo.receivers;
            presentSections.add(SECTION_RECEIVERS);
        }
        if (packageInfo.services != null) {
            mServices = packageInfo.services;
            presentSections.add(SECTION_SERVICES);
        }
        if (packageInfo.providers != null) {
            mProviders = packageInfo.providers;
            presentSections.add(SECTION_PROVIDERS);
        }

        // Scan defined permissions
        if (packageInfo.permissions != null) {
            mDefinedPermissions = new String[packageInfo.permissions.length];
            for (int i = 0; i < packageInfo.permissions.length; i++) {
                mDefinedPermissions[i] = packageInfo.permissions[i].name;
            }
            presentSections.add(SECTION_DEFINED_PERMISSIONS);
        }

        // Scan requested permissions (granted and denied)
        HashSet<String> testedPermissions = new HashSet<String>();
        if (packageInfo.requestedPermissions != null) {
            ArrayList<String> grantedPermissions = new ArrayList<String>();
            ArrayList<String> deniedPermissions = new ArrayList<String>();
            for (String permission : packageInfo.requestedPermissions) {
                if (packageManager.checkPermission(permission,
                        mPackageName) == PackageManager.PERMISSION_GRANTED) {
                    grantedPermissions.add(permission);
                } else {
                    deniedPermissions.add(permission);
                }
                testedPermissions.add(permission);
            }
            if (grantedPermissions.size() != 0) {
                mGrantedPermissions = grantedPermissions.toArray(new String[grantedPermissions.size()]);
                presentSections.add(SECTION_GRANTED_PERMISSIONS);
            }
            if (deniedPermissions.size() != 0) {
                mDeniedPermissions = deniedPermissions.toArray(new String[deniedPermissions.size()]);
                presentSections.add(SECTION_DENIED_PERMISSIONS);
            }

        }

        // Scan shared user packages for permissions (implicitly granted)
        {
            ArrayList<String> implicitlyGrantedPermissions = new ArrayList<String>();
            for (String sharedUidPackageName : packageManager
                    .getPackagesForUid(packageInfo.applicationInfo.uid)) {
                if (mPackageName.equals(sharedUidPackageName)) {
                    continue;
                }
                final PackageInfo sharedUidPackageInfo = packageManager.getPackageInfo(sharedUidPackageName,
                        PackageManager.GET_PERMISSIONS);
                if (sharedUidPackageInfo.requestedPermissions == null) {
                    continue;
                }
                for (String permission : sharedUidPackageInfo.requestedPermissions) {
                    if (!testedPermissions.contains(permission)) {
                        testedPermissions.add(permission);
                        if (packageManager.checkPermission(permission,
                                mPackageName) == PackageManager.PERMISSION_GRANTED) {
                            implicitlyGrantedPermissions.add(permission);
                        }
                    }
                }
            }
            if (implicitlyGrantedPermissions.size() != 0) {
                mImplicitlyGrantedPermissions = implicitlyGrantedPermissions
                        .toArray(new String[implicitlyGrantedPermissions.size()]);
                presentSections.add(SECTION_IMPLICITLY_GRANTED_PERMISSIONS);
            }
        }

        // Save present sections list as array
        mPresentSections = new int[presentSections.size()];
        for (int i = 0; i < presentSections.size(); i++) {
            mPresentSections[i] = presentSections.get(i);
        }
    } catch (PackageManager.NameNotFoundException e) {
        throw new RuntimeException(e);
    }

}