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:android.support.v7.widget.SuggestionsAdapter.java

/**
 * Gets the activity or application icon for an activity.
 *
 * @param component Name of an activity.
 * @return A drawable, or {@code null} if neither the acitivy or the application
 *         have an icon set./*from   w w  w  .  ja va 2s  . c o  m*/
 */
private Drawable getActivityIcon(ComponentName component) {
    PackageManager pm = mContext.getPackageManager();
    final ActivityInfo activityInfo;
    try {
        activityInfo = pm.getActivityInfo(component, PackageManager.GET_META_DATA);
    } catch (NameNotFoundException ex) {
        Log.w(LOG_TAG, ex.toString());
        return null;
    }
    int iconId = activityInfo.getIconResource();
    if (iconId == 0)
        return null;
    String pkg = component.getPackageName();
    Drawable drawable = pm.getDrawable(pkg, iconId, activityInfo.applicationInfo);
    if (drawable == null) {
        Log.w(LOG_TAG, "Invalid icon resource " + iconId + " for " + component.flattenToShortString());
        return null;
    }
    return drawable;
}

From source file:com.apptentive.android.sdk.ApptentiveInternal.java

public boolean init() {
    boolean bRet = true;
    codePointStore.init();/*from  w  w w  .  ja va2 s.  co m*/
    /* If Message Center feature has never been used before, don't initialize message polling thread.
     * Message Center feature will be seen as used, if one of the following conditions has been met:
     * 1. Message Center has been opened for the first time
     * 2. The first Push is received which would open Message Center
     * 3. An unreadMessageCountListener() is set up
     */
    boolean featureEverUsed = prefs.getBoolean(Constants.PREF_KEY_MESSAGE_CENTER_FEATURE_USED, false);
    if (featureEverUsed) {
        messageManager.init();
    }
    conversationToken = prefs.getString(Constants.PREF_KEY_CONVERSATION_TOKEN, null);
    conversationId = prefs.getString(Constants.PREF_KEY_CONVERSATION_ID, null);
    personId = prefs.getString(Constants.PREF_KEY_PERSON_ID, null);
    apptentiveToolbarTheme = appContext.getResources().newTheme();

    boolean apptentiveDebug = false;
    String logLevelOverride = null;
    String manifestApiKey = null;
    try {
        appPackageName = appContext.getPackageName();
        PackageManager packageManager = appContext.getPackageManager();
        PackageInfo packageInfo = packageManager.getPackageInfo(appPackageName,
                PackageManager.GET_META_DATA | PackageManager.GET_RECEIVERS);
        ApplicationInfo ai = packageInfo.applicationInfo;

        Bundle metaData = ai.metaData;
        if (metaData != null) {
            manifestApiKey = Util.trim(metaData.getString(Constants.MANIFEST_KEY_APPTENTIVE_API_KEY));
            logLevelOverride = Util.trim(metaData.getString(Constants.MANIFEST_KEY_APPTENTIVE_LOG_LEVEL));
            apptentiveDebug = metaData.getBoolean(Constants.MANIFEST_KEY_APPTENTIVE_DEBUG);
        }

        // Used for application theme inheritance if the theme is an AppCompat theme.
        setApplicationDefaultTheme(ai.theme);

        AppRelease appRelease = AppRelease.generateCurrentAppRelease(appContext);

        isAppDebuggable = appRelease.getDebug();
        currentVersionCode = appRelease.getVersionCode();
        currentVersionName = appRelease.getVersionName();

        VersionHistoryEntry lastVersionEntrySeen = VersionHistoryStore.getLastVersionSeen();

        if (lastVersionEntrySeen == null) {
            onVersionChanged(null, currentVersionCode, null, currentVersionName, appRelease);
        } else {
            int lastSeenVersionCode = lastVersionEntrySeen.getVersionCode();
            Apptentive.Version lastSeenVersionNameVersion = new Apptentive.Version();
            lastSeenVersionNameVersion.setVersion(lastVersionEntrySeen.getVersionName());
            if (!(currentVersionCode == lastSeenVersionCode)
                    || !currentVersionName.equals(lastSeenVersionNameVersion.getVersion())) {
                onVersionChanged(lastVersionEntrySeen.getVersionCode(), currentVersionCode,
                        lastVersionEntrySeen.getVersionName(), currentVersionName, appRelease);
            }
        }
        defaultAppDisplayName = packageManager
                .getApplicationLabel(packageManager.getApplicationInfo(packageInfo.packageName, 0)).toString();

        // Prevent delayed run-time exception if the app upgrades from pre-2.0 and doesn't remove NetworkStateReceiver from manifest
        ActivityInfo[] registered = packageInfo.receivers;
        if (registered != null) {
            for (ActivityInfo activityInfo : registered) {
                // Throw assertion error when relict class found in manifest.
                if (activityInfo.name.equals("com.apptentive.android.sdk.comm.NetworkStateReceiver")) {
                    throw new AssertionError(
                            "NetworkStateReceiver has been removed from Apptentive SDK, please make sure it's also removed from manifest file");
                }
            }
        }

    } catch (Exception e) {
        ApptentiveLog.e("Unexpected error while reading application or package info.", e);
        bRet = false;
    }

    // Set debuggable and appropriate log level.
    if (apptentiveDebug) {
        ApptentiveLog.i("Apptentive debug logging set to VERBOSE.");
        setMinimumLogLevel(ApptentiveLog.Level.VERBOSE);
    } else if (logLevelOverride != null) {
        ApptentiveLog.i("Overriding log level: %s", logLevelOverride);
        setMinimumLogLevel(ApptentiveLog.Level.parse(logLevelOverride));
    } else {
        if (isAppDebuggable) {
            setMinimumLogLevel(ApptentiveLog.Level.VERBOSE);
        }
    }
    ApptentiveLog.i("Debug mode enabled? %b", isAppDebuggable);

    String lastSeenSdkVersion = prefs.getString(Constants.PREF_KEY_LAST_SEEN_SDK_VERSION, "");
    if (!lastSeenSdkVersion.equals(Constants.APPTENTIVE_SDK_VERSION)) {
        onSdkVersionChanged(appContext, lastSeenSdkVersion, Constants.APPTENTIVE_SDK_VERSION);
    }

    // The apiKey can be passed in programmatically, or we can fallback to checking in the manifest.
    if (TextUtils.isEmpty(apiKey) && !TextUtils.isEmpty(manifestApiKey)) {
        apiKey = manifestApiKey;
    }
    if (TextUtils.isEmpty(apiKey) || apiKey.contains(Constants.EXAMPLE_API_KEY_VALUE)) {
        String errorMessage = "The Apptentive API Key is not defined. You may provide your Apptentive API Key in Apptentive.register(), or in as meta-data in your AndroidManifest.xml.\n"
                + "<meta-data android:name=\"apptentive_api_key\"\n"
                + "           android:value=\"@string/your_apptentive_api_key\"/>";
        if (isAppDebuggable) {
            throw new RuntimeException(errorMessage);
        } else {
            ApptentiveLog.e(errorMessage);
        }
    } else {
        ApptentiveLog.d("Using cached Apptentive API Key");
    }
    ApptentiveLog.d("Apptentive API Key: %s", apiKey);

    // Grab app info we need to access later on.
    androidId = Settings.Secure.getString(appContext.getContentResolver(),
            android.provider.Settings.Secure.ANDROID_ID);
    ApptentiveLog.d("Android ID: ", androidId);
    ApptentiveLog.d("Default Locale: %s", Locale.getDefault().toString());
    ApptentiveLog.d("Conversation id: %s", prefs.getString(Constants.PREF_KEY_CONVERSATION_ID, "null"));
    return bRet;
}

From source file:com.sentaroh.android.SMBSync.SMBSyncMain.java

private void getApplVersionName() {
    try {//from  www  .  j av  a 2 s . c  o m
        String packegeName = getPackageName();
        PackageInfo packageInfo = getPackageManager().getPackageInfo(packegeName, PackageManager.GET_META_DATA);
        packageVersionName = packageInfo.versionName;
    } catch (NameNotFoundException e) {

        util.addDebugLogMsg(1, "I", "SMBSync package can not be found");
    }
}

From source file:jp.gr.java_conf.ya.shiobeforandroid3.UpdateTweetDrive.java

@Override
public final boolean onOptionsItemSelected(final MenuItem item) {

    boolean ret = true;
    if (item.getItemId() == R.string.get_maplocation) {

        final CameraPosition cameraPos = map.getCameraPosition();
        final LatLng latLng = cameraPos.target;
        editText4.setText(Double.toString(latLng.latitude));
        editText5.setText(Double.toString(latLng.longitude));

        if (checkLocationinfoException(editText4, editText5) == false) {
            final ArrayList<String> ITEM = GeocodeUtil.reverseGeoCoding(UpdateTweetDrive.this, latLng.latitude,
                    latLng.longitude);/*  w  w  w  .  j  a  va 2s .c  om*/
            if (ITEM != null) {
                if (!isFinishing()) {
                    if (alertDialog != null) {
                        if (alertDialog.isShowing()) {
                            try {
                                alertDialog.cancel();
                            } catch (final Exception e) {
                            }
                        }
                    }
                }
                alertDialog = new AlertDialog.Builder(UpdateTweetDrive.this).setTitle(R.string.reversegeocoding)
                        .setItems(ITEM.toArray(new String[ITEM.size()]), new DialogInterface.OnClickListener() {
                            @Override
                            public final void onClick(final DialogInterface dialog, final int which) {
                                String str = ITEM.get(which);
                                if (str.equals("") == false) {
                                    editText2.setText(str);
                                }
                            }
                        }).create();
                alertDialog.show();
            }
        }

    } else if (item.getItemId() == R.string.deljustbefore) {
        adapter.deljustbefore(-1);

    } else if (item.getItemId() == R.string.settings) {
        try {
            final Intent intent2 = new Intent();
            intent2.setClassName("jp.gr.java_conf.ya.shiobeforandroid3",
                    "jp.gr.java_conf.ya.shiobeforandroid3.Preference");
            startActivity(intent2);
        } catch (final ActivityNotFoundException e) {
            WriteLog.write(UpdateTweetDrive.this, e);
        } catch (final Exception e) {
            WriteLog.write(UpdateTweetDrive.this, e);
        }

    } else if (item.getItemId() == R.string.copyright) {
        new Thread(new Runnable() {
            @Override
            public final void run() {
                try {
                    final PackageInfo packageInfo = getPackageManager().getPackageInfo(
                            "jp.gr.java_conf.ya.shiobeforandroid3", PackageManager.GET_META_DATA);
                    toast(getString(R.string.app_name_short) + ": " + getString(R.string.version)
                            + packageInfo.versionName + " (" + packageInfo.versionCode + ")");
                } catch (final NameNotFoundException e) {
                }

                toast(GooglePlayServicesUtil.getOpenSourceSoftwareLicenseInfo(UpdateTweetDrive.this));

                try {
                    final Intent intent = new Intent("android.intent.action.VIEW",
                            Uri.parse(ListAdapter.app_uri_about));
                    startActivity(intent);
                } catch (final Exception e) {
                }
            }
        }).start();

    } else if (item.getItemId() == R.string.back) {
        finish();

    }
    return ret;
}

From source file:com.mobicage.rogerthat.MainService.java

public static String getVersion(Context context) {
    try {//  w w  w  .  j av a2s  .c  o  m
        return context.getPackageManager().getPackageInfo(context.getPackageName(),
                PackageManager.GET_META_DATA).versionName;
    } catch (NameNotFoundException e) {
        L.bug(e);
    }
    return "1.0.0.BUG";
}

From source file:com.mattprecious.telescope.FileProvider.java

/**
 * Parse and return {@link PathStrategy} for given authority as defined in
 * {@link #META_DATA_FILE_PROVIDER_PATHS} {@code &lt;meta-data>}.
 *
 * @see #getPathStrategy(Context, String)
 *//*  www  . j  a  va  2 s .co  m*/
private static PathStrategy parsePathStrategy(Context context, String authority)
        throws IOException, XmlPullParserException {
    final SimplePathStrategy strat = new SimplePathStrategy(authority);

    final ProviderInfo info = context.getPackageManager().resolveContentProvider(authority,
            PackageManager.GET_META_DATA);
    final XmlResourceParser in = info.loadXmlMetaData(context.getPackageManager(),
            META_DATA_FILE_PROVIDER_PATHS);
    if (in == null) {
        throw new IllegalArgumentException("Missing " + META_DATA_FILE_PROVIDER_PATHS + " meta-data");
    }

    int type;
    while ((type = in.next()) != END_DOCUMENT) {
        if (type == START_TAG) {
            final String tag = in.getName();

            final String name = in.getAttributeValue(null, ATTR_NAME);
            String path = in.getAttributeValue(null, ATTR_PATH);

            File target = null;
            if (TAG_ROOT_PATH.equals(tag)) {
                target = buildPath(DEVICE_ROOT, path);
            } else if (TAG_FILES_PATH.equals(tag)) {
                target = buildPath(context.getFilesDir(), path);
            } else if (TAG_CACHE_PATH.equals(tag)) {
                target = buildPath(context.getCacheDir(), path);
            } else if (TAG_EXTERNAL.equals(tag)) {
                target = buildPath(Environment.getExternalStorageDirectory(), path);
            } else if (TAG_EXTERNAL_APP.equals(tag)) {
                try {
                    // This sometimes causes an exception on API level 19
                    // Just avoid this specific file provider, so we can try to keep going
                    target = buildPath(context.getExternalFilesDir(null), path);
                } catch (NullPointerException npe) {
                    npe.printStackTrace();
                }
            }

            if (target != null) {
                strat.addRoot(name, target);
            }
        }
    }

    return strat;
}

From source file:com.gm.goldencity.util.Utils.java

/**
 * Getting all installed packages//from w w  w  . j a v a  2 s .c  o  m
 *
 * @param context Application context
 * @return all installed applications list
 */
public static List<PackageInfo> getAllInstalledApplication(Context context) {
    final PackageManager pm = context.getPackageManager();
    // get a list of installed apps.
    List<PackageInfo> packages = pm.getInstalledPackages(PackageManager.GET_META_DATA);

    return packages;
}

From source file:org.rm3l.maoni.ui.MaoniActivity.java

private void validateAndSubmitForm() {
    //Validate form
    if (this.validateForm(mRootView)) {
        //TODO Check that device is actually connected to the internet prior to going any further
        boolean includeScreenshot = false;
        if (mScreenCapturingFeatureEnabled && mIncludeScreenshot != null) {
            includeScreenshot = mIncludeScreenshot.isChecked();
        }//  w  w w.j  av  a2  s .com
        String contentText = "";
        if (mContent != null) {
            contentText = mContent.getText().toString();
        }

        final Intent intent = getIntent();

        Uri screenshotUri = null;
        File screenshotFile = null;
        Uri logsUri = null;
        File logsFile = null;

        final boolean includeLogs = mLogsCapturingFeatureEnabled && mIncludeLogs != null
                && mIncludeLogs.isChecked();
        if (includeLogs) {
            logsFile = new File(mWorkingDir, MAONI_LOGS_FILENAME);
            LogcatUtils.getLogsToFile(logsFile);
        }

        if (intent.hasExtra(FILE_PROVIDER_AUTHORITY)) {
            final String fileProviderAuthority = intent.getStringExtra(FILE_PROVIDER_AUTHORITY);
            //#11 : Potential NPE in Android's FileProvider if Provider Authority couldn't be resolved
            final ProviderInfo providerAuthorityInfo = this.getPackageManager()
                    .resolveContentProvider(fileProviderAuthority, PackageManager.GET_META_DATA);
            if (providerAuthorityInfo == null) {
                Log.w(TAG,
                        "Could not resolve file provider authority : " + fileProviderAuthority
                                + ". Sharing of files captured not supported then. "
                                + "See http://maoni.rm3l.org/ for setup instructions.");
            } else {
                if (mScreenshotFilePath != null) {
                    screenshotFile = new File(mScreenshotFilePath.toString());
                    screenshotUri = FileProvider.getUriForFile(this, fileProviderAuthority, screenshotFile);
                    grantUriPermission(intent.getComponent().getPackageName(), screenshotUri,
                            Intent.FLAG_GRANT_READ_URI_PERMISSION);
                }
                if (logsFile != null) {
                    logsUri = FileProvider.getUriForFile(this, fileProviderAuthority, logsFile);
                    grantUriPermission(intent.getComponent().getPackageName(), logsUri,
                            Intent.FLAG_GRANT_READ_URI_PERMISSION);
                }
            }
        }

        //Construct the feedback object and call the actual implementation
        final Feedback feedback = new Feedback(mFeedbackUniqueId, this, mAppInfo, contentText,
                includeScreenshot, screenshotUri, screenshotFile, includeLogs, logsUri, logsFile,
                mSharedPreferences);
        if (mListener != null) {
            if (mListener.onSendButtonClicked(feedback)) {
                finish();
            } // else do *not* finish the activity
        } else {
            finish();
        }
    } //else do nothing - this is up to the callback implementation
}

From source file:utils.bobo.com.boboutils.App.appwidget.CustomViewFileProvider.java

/**
 * Parse and return {@link PathStrategy} for given authority as defined in
 * {@link #META_DATA_FILE_PROVIDER_PATHS} {@code &lt;meta-data>}.
 *
 * @see #getPathStrategy(Context, String)
 *//*from   w w  w . java2  s.  c  o m*/
private static PathStrategy parsePathStrategy(Context context, String authority)
        throws IOException, XmlPullParserException {
    final SimplePathStrategy strat = new SimplePathStrategy(authority);

    final ProviderInfo info = context.getPackageManager().resolveContentProvider(authority,
            PackageManager.GET_META_DATA);
    final XmlResourceParser in = info.loadXmlMetaData(context.getPackageManager(),
            META_DATA_FILE_PROVIDER_PATHS);
    if (in == null) {
        throw new IllegalArgumentException("Missing " + META_DATA_FILE_PROVIDER_PATHS + " meta-data");
    }

    int type;
    while ((type = in.next()) != END_DOCUMENT) {
        if (type == START_TAG) {
            final String tag = in.getName();

            final String name = in.getAttributeValue(null, ATTR_NAME);
            String path = in.getAttributeValue(null, ATTR_PATH);

            File target = null;
            if (TAG_ROOT_PATH.equals(tag)) {
                target = buildPath(DEVICE_ROOT, path);
            } else if (TAG_FILES_PATH.equals(tag)) {
                target = buildPath(context.getFilesDir(), path);
            } else if (TAG_CACHE_PATH.equals(tag)) {
                target = buildPath(context.getCacheDir(), path);
            } else if (TAG_EXTERNAL.equals(tag)) {
                target = buildPath(Environment.getExternalStorageDirectory(), path);
            }

            if (target != null) {
                strat.addRoot(name, target);
            }
        }
    }

    return strat;
}

From source file:org.onebusaway.android.ui.HomeActivity.java

@SuppressWarnings("deprecation")
private void autoShowWhatsNew() {
    SharedPreferences settings = Application.getPrefs();

    // Get the current app version.
    PackageManager pm = getPackageManager();
    PackageInfo appInfo = null;//from w ww  . j av a  2 s .c  o  m
    try {
        appInfo = pm.getPackageInfo(getPackageName(), PackageManager.GET_META_DATA);
    } catch (NameNotFoundException e) {
        // Do nothing, perhaps we'll get to show it again? Or never.
        return;
    }

    final int oldVer = settings.getInt(WHATS_NEW_VER, 0);
    final int newVer = appInfo.versionCode;

    if (oldVer < newVer) {
        mWhatsNewMessage = R.string.main_help_whatsnew;
        showDialog(WHATSNEW_DIALOG);

        // Updates will remove the alarms. This should put them back.
        // (Unfortunately I can't find a way to reschedule them without
        // having the app run again).
        TripService.scheduleAll(this);
        PreferenceUtils.saveInt(WHATS_NEW_VER, appInfo.versionCode);
    }
}