Example usage for android.content.pm PackageManager GET_META_DATA

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

Introduction

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

Prototype

int GET_META_DATA

To view the source code for android.content.pm PackageManager GET_META_DATA.

Click Source Link

Document

ComponentInfo flag: return the ComponentInfo#metaData data android.os.Bundle s that are associated with a component.

Usage

From source file:com.landenlabs.all_devtool.PackageFragment.java

/**
 * Load installed (user or system) packages.
 *
 * TODO - include/*from w  w w .  j  ava2 s . c  o  m*/
 *    /data/local/tmp
 *    /sdcard/local/tmp ?
 *    /storage/sdcardx/LOST.DIR/
 *    /sdcard/download
 *
 */
void loadCachedPackages() {
    try {
        // m_pkgUninstallBtn.setText(R.string.package_uninstall);
        m_uninstallResId = R.string.package_del_cache;
        m_pkgUninstallBtn.post(new Runnable() {
            @Override
            public void run() {
                updateUninstallBtn();
            }
        });

        m_workList = new ArrayList<PackingItem>();

        // PackageManager.GET_SIGNATURES | PackageManager.GET_PERMISSIONS | PackageManager.GET_PROVIDERS;
        int flags1 = PackageManager.GET_META_DATA | PackageManager.GET_SHARED_LIBRARY_FILES
                | PackageManager.GET_INTENT_FILTERS;
        int flags2 = PackageManager.GET_META_DATA | PackageManager.GET_SHARED_LIBRARY_FILES;
        int flags3 = PackageManager.GET_META_DATA;
        int flags4 = 0;

        List<PackageInfo> packList = getActivity().getPackageManager().getInstalledPackages(flags1);
        /*
        packList = mergePackages(packList,
            getActivity().getPackageManager().getInstalledPackages(flags2));
        packList = mergePackages(packList,
            getActivity().getPackageManager().getInstalledPackages(flags3));
        packList = mergePackages(packList,
            getActivity().getPackageManager().getInstalledPackages(flags4));
        */

        if (packList != null)
            for (int idx = 0; idx < packList.size(); idx++) {
                PackageInfo packInfo = packList.get(idx);
                long cacheSize = 0;
                long fileCount = 0;

                if (packInfo == null || packInfo.lastUpdateTime <= 0) {
                    continue; // Bad package
                }

                Context pkgContext;
                try {
                    m_log.d(String.format("%3d/%d : %s", idx, packList.size(), packInfo.packageName));
                    pkgContext = getActivity().createPackageContext(packInfo.packageName,
                            Context.CONTEXT_IGNORE_SECURITY);
                } catch (Exception ex) {
                    m_log.e(ex.getLocalizedMessage());
                    continue; // Bad package
                }

                File cacheDirectory = null;
                Utils.DirSizeCount cacheDirSize = null;
                if (pkgContext.getCacheDir() != null) {
                    cacheDirectory = pkgContext.getCacheDir();
                } else {
                    // cacheDirectory = new File(mContext.getPackageResourcePath());
                    if (pkgContext.getFilesDir() != null) {
                        String dataPath = pkgContext.getFilesDir().getPath(); // "/data/data/"
                        cacheDirectory = new File(dataPath, pkgContext.getPackageName() + "/cache");
                    }
                }

                if (cacheDirectory != null) {
                    // cacheSize = cacheDirectory.length()/1024;
                    cacheDirSize = Utils.getDirectorySize(cacheDirectory);
                    if (true) {
                        // Cache is not readable or empty,
                        // Try and map cache dir to one of the sd storage paths
                        for (String storageDir : m_storageDirs) {
                            try {
                                File cacheDirectory2 = new File(cacheDirectory.getCanonicalPath()
                                        .replace("/data/data", storageDir + "/Android/data"));
                                if (cacheDirectory2.exists()) {
                                    cacheDirectory = cacheDirectory2;
                                    Utils.DirSizeCount dirSize = Utils.getDirectorySize(cacheDirectory2);
                                    if (cacheDirSize == null || dirSize.size > cacheDirSize.size) {
                                        cacheDirSize = dirSize;
                                        cacheDirectory = cacheDirectory2;
                                    }
                                }
                            } catch (Exception ex) {
                                m_log.d(ex.getMessage());
                            }
                        }
                    }
                } else {
                    m_log.d(packInfo.packageName + " missing cache dir");
                }

                Utils.DirSizeCount datDirSize = null;
                if (packInfo.applicationInfo.dataDir != null) {
                    try {
                        datDirSize = Utils.getDirectorySize(new File(packInfo.applicationInfo.dataDir));
                    } catch (Exception ex) {

                    }
                }

                /*
                                    Method getPackageSizeInfo;
                                    try {
                getPackageSizeInfo = getActivity().getPackageManager().getClass().getMethod(
                        "getPackageSizeInfo", String.class,
                        Class.forName("android.content.pm.IPackageStatsObserver"));
                        
                getPackageSizeInfo.invoke(getActivity().getPackageManager(), packInfo.packageName,
                        new IPackageStatsObserver() {
                        
                            @Override
                            public void onGetStatsCompleted(
                                    PackageStats pStats, boolean succeeded)
                                    throws RemoteException {
                        
                                totalSize = totalSize + pStats.cacheSize;
                            }
                        }
                );
                                    } catch (Exception e) {
                continue;
                                    }
                */
                /* if ((packInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) */ {
                    ArrayListPairString pkgList = new ArrayListPairString();
                    String appName = "unknown";
                    try {
                        appName = packInfo.applicationInfo.loadLabel(getActivity().getPackageManager())
                                .toString().trim();
                    } catch (Exception ex) {
                        m_log.e(ex.getLocalizedMessage());
                    }
                    long pkgSize = 0;

                    addList(pkgList, "Version", packInfo.versionName);
                    addList(pkgList, "TargetSDK", String.valueOf(packInfo.applicationInfo.targetSdkVersion));
                    String installTyp = "auto";
                    if (Build.VERSION.SDK_INT >= 21) {
                        switch (packInfo.installLocation) {
                        case PackageInfo.INSTALL_LOCATION_AUTO:
                            break;
                        case PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY:
                            installTyp = "internal";
                            break;
                        case PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL:
                            installTyp = "external";
                            break;
                        }
                    }
                    addList(pkgList, "Install", installTyp);

                    // Add application info.
                    try {
                        addList(pkgList, "Allow Backup",
                                String.valueOf((packInfo.applicationInfo.flags & FLAG_ALLOW_BACKUP) != 0));
                        addList(pkgList, "Debuggable", String.valueOf(
                                (packInfo.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0));
                        addList(pkgList, "External Storage", String.valueOf(
                                (packInfo.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0));
                        String themeName = getResourceName(packInfo, packInfo.applicationInfo.theme);
                        if (!TextUtils.isEmpty(themeName))
                            addList(pkgList, "Theme", themeName);
                    } catch (Exception ex) {
                        Log.d("foo", ex.getMessage());
                    }

                    try {
                        File file = new File(packInfo.applicationInfo.sourceDir);
                        pkgSize = file.length();
                    } catch (Exception ex) {
                    }

                    addList(pkgList, "Apk File", packInfo.applicationInfo.publicSourceDir);
                    addList(pkgList, "Apk Size",
                            NumberFormat.getNumberInstance(Locale.getDefault()).format(pkgSize));

                    addList(pkgList, "Src Dir", packInfo.applicationInfo.sourceDir);
                    addList(pkgList, "lib Dir", packInfo.applicationInfo.nativeLibraryDir);

                    addList(pkgList, "dat Dir", packInfo.applicationInfo.dataDir);
                    if (null != datDirSize) {
                        addList(pkgList, "*  Dir Size",
                                NumberFormat.getNumberInstance(Locale.getDefault()).format(datDirSize.size));
                        addList(pkgList, "*  File Count",
                                NumberFormat.getNumberInstance(Locale.getDefault()).format(datDirSize.count));
                    }

                    if (null != cacheDirectory) {
                        addList(pkgList, "Cache", cacheDirectory.getCanonicalPath());
                        if (null != cacheDirSize) {
                            cacheSize = cacheDirSize.size;
                            addList(pkgList, "*  Dir Size", NumberFormat.getNumberInstance(Locale.getDefault())
                                    .format(cacheDirSize.size));
                            addList(pkgList, "*  File Count", NumberFormat
                                    .getNumberInstance(Locale.getDefault()).format(cacheDirSize.count));
                        }
                    }

                    if (null != packInfo.applicationInfo.sharedLibraryFiles
                            && packInfo.applicationInfo.sharedLibraryFiles.length != 0) {
                        addList(pkgList, "ShareLibs", NumberFormat.getNumberInstance(Locale.getDefault())
                                .format(packInfo.applicationInfo.sharedLibraryFiles.length));
                        for (String shrLibStr : packInfo.applicationInfo.sharedLibraryFiles) {
                            addList(pkgList, "  ", shrLibStr);
                        }
                    }

                    if (true) {
                        // packInfo.configPreferences; use with flag= GET_CONFIGURATIONS;
                        // packInfo.providers use with GET_PROVIDERS;

                        List<IntentFilter> outFilters = new ArrayList<IntentFilter>();
                        List<ComponentName> outActivities = new ArrayList<ComponentName>();
                        int num = getActivity().getPackageManager().getPreferredActivities(outFilters,
                                outActivities, packInfo.packageName);
                        if (num > 0) {
                            addList(pkgList, "Preferred #", String.valueOf(num));
                        }
                    }

                    /* if (null != cacheDirectory) */
                    // if (cacheDirSize != null)
                    {
                        m_workList.add(new PackingItem(packInfo.packageName.trim(), pkgList, packInfo,
                                cacheSize, appName));
                    }
                }
            }

    } catch (Exception ex) {
        m_log.e(ex.getMessage());
    }
}

From source file:dev.ukanth.ufirewall.Api.java

public static boolean isPackageExists(PackageManager pm, String targetPackage) {
    try {//from   w w w.  j av a  2 s .  c om
        pm.getPackageInfo(targetPackage, PackageManager.GET_META_DATA);
    } catch (NameNotFoundException e) {
        return false;
    }
    return true;
}

From source file:com.landenlabs.all_devtool.PackageFragment.java

/**
 * Load installed libraries/* ww  w  . j  av a2 s.c o  m*/
 */
void loadLibraries() {
    try {
        m_workList = new ArrayList<PackingItem>();
        int flag = PackageManager.GET_META_DATA;
        String[] libraries = getActivity().getPackageManager().getSystemSharedLibraryNames();
        if (libraries != null && libraries.length != 0) {
            ArrayListPairString libList = new ArrayListPairString();
            addList(libList, "Libraries", String.format("%,d", libraries.length));
            long libSize = 0;
            for (String lib : libraries) {
                addList(libList, "  ", lib);
            }

            m_workList.add(new PackingItem("Libraries", libList, null, libSize, "lib"));
        }

        // Getting status
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this.getActivity());
        if (status == ConnectionResult.SUCCESS) {

            PackageInfo packInfo = getActivity().getPackageManager()
                    .getPackageInfo(GooglePlayServicesUtil.GOOGLE_PLAY_SERVICES_PACKAGE, flag);
            addPackageInfo(packInfo);
            // GooglePlayServicesUtil.GOOGLE_PLAY_SERVICES_PACKAGE;
            // GooglePlayServicesUtil.GOOGLE_PLAY_SERVICES_VERSION_CODE;
        }

        FeatureInfo[] features = getActivity().getPackageManager().getSystemAvailableFeatures();
        if (features != null && features.length != 0) {
            // features.name
        }

    } catch (Exception ex) {
        m_log.e(ex.getMessage());
    }
}

From source file:com.cognizant.trumobi.PersonaLauncher.java

@SuppressWarnings("unused")
void addAppWidget(final Intent data) {
    // TODO: catch bad widget exception when sent
    int appWidgetId = data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);

    String customWidget = data.getStringExtra(EXTRA_CUSTOM_WIDGET);
    /*/*from  ww w.ja v  a2s . c  o m*/
     * if (SEARCH_WIDGET.equals(customWidget)) { // We don't need this any
     * more, since this isn't a real app widget.
     * mAppWidgetHost.deleteAppWidgetId(appWidgetId); // add the search
     * widget addSearch(); } else {
     */
    AppWidgetProviderInfo appWidget = mAppWidgetManager.getAppWidgetInfo(appWidgetId);

    try {
        Bundle metadata = getPackageManager().getReceiverInfo(appWidget.provider,
                PackageManager.GET_META_DATA).metaData;
        if (metadata != null) {
            if (metadata.containsKey(PersonaLauncherMetadata.Requirements.APIVersion)) {
                int requiredApiVersion = metadata.getInt(PersonaLauncherMetadata.Requirements.APIVersion);
                if (requiredApiVersion > PersonaLauncherMetadata.CurrentAPIVersion) {
                    onActivityResult(REQUEST_CREATE_APPWIDGET, Activity.RESULT_CANCELED, data);
                    // Show a nice toast here to tell the user why the
                    // widget is rejected.
                    new AlertDialog.Builder(this).setTitle(R.string.adw_version).setCancelable(true)
                            .setIcon(R.drawable.pr_app_icon)
                            .setPositiveButton(getString(android.R.string.ok), null)
                            .setMessage(getString(R.string.scrollable_api_required)).create().show();
                    return;
                }
            }
        }
    } catch (PackageManager.NameNotFoundException expt) {
        // No Metadata available... then it is all OK...
    }
    configureOrAddAppWidget(data);
}

From source file:com.android.launcher3.Utilities.java

private static boolean isPackageExisted(Context context, String targetPackage) {
    PackageManager pm = context.getPackageManager();
    try {/*from  w ww  .j a  v  a2  s . c o  m*/
        PackageInfo info = pm.getPackageInfo(targetPackage, PackageManager.GET_META_DATA);
    } catch (PackageManager.NameNotFoundException e) {
        return false;
    }
    return true;
}

From source file:com.android.launcher2.Launcher.java

private Drawable getExternalPackageToolbarIcon(ComponentName activityName, String resourceName) {
    try {/* w ww .ja  v  a 2 s  .  c  o  m*/
        PackageManager packageManager = getPackageManager();
        // Look for the toolbar icon specified in the activity meta-data
        Bundle metaData = packageManager.getActivityInfo(activityName, PackageManager.GET_META_DATA).metaData;
        if (metaData != null) {
            int iconResId = metaData.getInt(resourceName);
            if (iconResId != 0) {
                Resources res = packageManager.getResourcesForActivity(activityName);
                return res.getDrawable(iconResId);
            }
        }
    } catch (NameNotFoundException e) {
        // This can happen if the activity defines an invalid drawable
        Log.w(TAG, "Failed to load toolbar icon; " + activityName.flattenToShortString() + " not found", e);
    } catch (Resources.NotFoundException nfe) {
        // This can happen if the activity defines an invalid drawable
        Log.w(TAG, "Failed to load toolbar icon from " + activityName.flattenToShortString(), nfe);
    }
    return null;
}

From source file:android.content.pm.PackageParser.java

private static boolean copyNeeded(int flags, Package p, PackageUserState state, Bundle metaData, int userId) {
    if (userId != UserHandle.USER_OWNER) {
        // We always need to copy for other users, since we need
        // to fix up the uid.
        return true;
    }/*from   ww  w  .j  a  va  2 s. c o m*/
    if (state.enabled != PackageManager.COMPONENT_ENABLED_STATE_DEFAULT) {
        boolean enabled = state.enabled == PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
        if (p.applicationInfo.enabled != enabled) {
            return true;
        }
    }
    if (!state.installed || state.hidden) {
        return true;
    }
    if (state.stopped) {
        return true;
    }
    if ((flags & PackageManager.GET_META_DATA) != 0 && (metaData != null || p.mAppMetaData != null)) {
        return true;
    }
    if ((flags & PackageManager.GET_SHARED_LIBRARY_FILES) != 0 && p.usesLibraryFiles != null) {
        return true;
    }
    return false;
}

From source file:android.content.pm.PackageParser.java

public static ApplicationInfo generateApplicationInfo(Package p, int flags, PackageUserState state,
        int userId) {
    if (p == null)
        return null;
    if (!checkUseInstalledOrHidden(flags, state)) {
        return null;
    }/*from   w ww  .ja  v  a2s  .c o m*/
    if (!copyNeeded(flags, p, state, null, userId)
            && ((flags & PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS) == 0
                    || state.enabled != PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
        // In this case it is safe to directly modify the internal ApplicationInfo state:
        // - CompatibilityMode is global state, so will be the same for every call.
        // - We only come in to here if the app should reported as installed; this is the
        // default state, and we will do a copy otherwise.
        // - The enable state will always be reported the same for the application across
        // calls; the only exception is for the UNTIL_USED mode, and in that case we will
        // be doing a copy.
        updateApplicationInfo(p.applicationInfo, flags, state);
        return p.applicationInfo;
    }

    // Make shallow copy so we can store the metadata/libraries safely
    ApplicationInfo ai = new ApplicationInfo(p.applicationInfo);
    ai.uid = UserHandle.getUid(userId, ai.uid);
    ai.dataDir = Environment.getDataUserPackageDirectory(ai.volumeUuid, userId, ai.packageName)
            .getAbsolutePath();
    if ((flags & PackageManager.GET_META_DATA) != 0) {
        ai.metaData = p.mAppMetaData;
    }
    if ((flags & PackageManager.GET_SHARED_LIBRARY_FILES) != 0) {
        ai.sharedLibraryFiles = p.usesLibraryFiles;
    }
    if (state.stopped) {
        ai.flags |= ApplicationInfo.FLAG_STOPPED;
    } else {
        ai.flags &= ~ApplicationInfo.FLAG_STOPPED;
    }
    updateApplicationInfo(ai, flags, state);
    return ai;
}

From source file:android.content.pm.PackageParser.java

public static final PermissionInfo generatePermissionInfo(Permission p, int flags) {
    if (p == null)
        return null;
    if ((flags & PackageManager.GET_META_DATA) == 0) {
        return p.info;
    }//from   w  w  w  .j  a v  a2 s . co m
    PermissionInfo pi = new PermissionInfo(p.info);
    pi.metaData = p.metaData;
    return pi;
}

From source file:android.content.pm.PackageParser.java

public static final PermissionGroupInfo generatePermissionGroupInfo(PermissionGroup pg, int flags) {
    if (pg == null)
        return null;
    if ((flags & PackageManager.GET_META_DATA) == 0) {
        return pg.info;
    }//w w  w  .  ja v  a  2  s .  c o  m
    PermissionGroupInfo pgi = new PermissionGroupInfo(pg.info);
    pgi.metaData = pg.metaData;
    return pgi;
}