Java Code Examples for android.content.pm.PackageManager.NameNotFoundException

The following examples show how to use android.content.pm.PackageManager.NameNotFoundException. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: AndroidPirateBox   Source File: AbstractPluginActivity.java    License: MIT License 6 votes vote down vote up
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupTitleApi11()
{
    CharSequence callingApplicationLabel = null;
    try
    {
        callingApplicationLabel =
                getPackageManager().getApplicationLabel(getPackageManager().getApplicationInfo(getCallingPackage(),
                                                                                               0));
    }
    catch (final NameNotFoundException e)
    {
        if (Constants.IS_LOGGABLE)
        {
            Log.e(Constants.LOG_TAG, "Calling package couldn't be found", e); //$NON-NLS-1$
        }
    }
    if (null != callingApplicationLabel)
    {
        setTitle(callingApplicationLabel);
    }
}
 
Example 2
Source Project: stitch-android-sdk   Source File: Stitch.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Initializes the Stitch SDK so that app clients can be created.
 *
 * @param context An Android context value.
 */
public static void initialize(final Context context) {
  if (!initialized.compareAndSet(false, true)) {
    return;
  }

  applicationContext = context.getApplicationContext();

  final String packageName = applicationContext.getPackageName();
  localAppName = packageName;

  final PackageManager manager = applicationContext.getPackageManager();
  try {
    final PackageInfo pkgInfo = manager.getPackageInfo(packageName, 0);
    localAppVersion = pkgInfo.versionName;
  } catch (final NameNotFoundException e) {
    Log.d(TAG, "Failed to get version of application, will not send in device info.");
  }

  Log.d(TAG, "Initialized android SDK");
}
 
Example 3
@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.about);

    LayoutUtils.maximizeWindow(getWindow());

    String name = getResources().getString(R.string.app_name);
    String version = "";
    try {
        final PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
        version = packageInfo.versionName;
        name = getResources().getString(packageInfo.applicationInfo.labelRes);
    } catch (final NameNotFoundException e) {
        e.printStackTrace();
    }

    final TextView title = (TextView) findViewById(R.id.about_title);
    title.setText(name + (LengthUtils.isNotEmpty(version) ? " v" + version : ""));

    final ExpandableListView view = (ExpandableListView) findViewById(R.id.about_parts);
    view.setAdapter(new PartsAdapter());
    view.expandGroup(0);
}
 
Example 4
Source Project: xmall   Source File: SystemWebViewClient.java    License: MIT License 6 votes vote down vote up
/**
 * Notify the host application that an SSL error occurred while loading a resource.
 * The host application must call either handler.cancel() or handler.proceed().
 * Note that the decision may be retained for use in response to future SSL errors.
 * The default behavior is to cancel the load.
 *
 * @param view          The WebView that is initiating the callback.
 * @param handler       An SslErrorHandler object that will handle the user's response.
 * @param error         The SSL error object.
 */
@TargetApi(8)
@Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {

    final String packageName = parentEngine.cordova.getActivity().getPackageName();
    final PackageManager pm = parentEngine.cordova.getActivity().getPackageManager();

    ApplicationInfo appInfo;
    try {
        appInfo = pm.getApplicationInfo(packageName, PackageManager.GET_META_DATA);
        if ((appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
            // debug = true
            handler.proceed();
            return;
        } else {
            // debug = false
            super.onReceivedSslError(view, handler, error);
        }
    } catch (NameNotFoundException e) {
        // When it doubt, lock it out!
        super.onReceivedSslError(view, handler, error);
    }
}
 
Example 5
/**
 * Query the signature for the application that would be invoked by the
 * given intent and verify that it matches the FB application's signature.
 * 
 * @param context
 * @param packageName
 * @return true if the app's signature matches the expected signature.
 */
private boolean validateAppSignatureForPackage(Context context, String packageName) {

    PackageInfo packageInfo;
    try {
        packageInfo = context.getPackageManager().getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
    } catch (NameNotFoundException e) {
        return false;
    }

    for (Signature signature : packageInfo.signatures) {
        if (signature.toCharsString().equals(FB_APP_SIGNATURE)) {
            return true;
        }
    }
    return false;
}
 
Example 6
Source Project: AppAuth-Android   Source File: BrowserSelectorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSelect_defaultBrowserSetNoneSupporting() throws NameNotFoundException {
    // Chrome is set as the users default browser, but the version is not supporting Custom Tabs
    // BrowserSelector.getAllBrowsers will result in a list, where the Dolphin browser is the
    // first element and the other browser, in this case Firefox, as the second element in the list.
    setBrowserList(FIREFOX, CHROME);
    setBrowsersWithWarmupSupport(NO_BROWSERS);
    when(mContext.getPackageManager().resolveActivity(BROWSER_INTENT, 0))
        .thenReturn(CHROME.mResolveInfo);
    List<BrowserDescriptor> allBrowsers = BrowserSelector.getAllBrowsers(mContext);

    assertThat(allBrowsers.get(0).packageName.equals(CHROME.mPackageName));
    assertFalse(allBrowsers.get(0).useCustomTab);
    assertThat(allBrowsers.get(1).packageName.equals(FIREFOX.mPackageName));
    assertFalse(allBrowsers.get(1).useCustomTab);
}
 
Example 7
Source Project: 365browser   Source File: AndroidTiclManifest.java    License: Apache License 2.0 6 votes vote down vote up
ApplicationMetadata(Context context) {
  ApplicationInfo appInfo;
  try {
    // Read metadata from manifest.xml
    appInfo = context.getPackageManager()
        .getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
  } catch (NameNotFoundException exception) {
    throw new RuntimeException("Cannot read own application info", exception);
  }
  ticlServiceClass = readApplicationMetadata(appInfo, TICL_SERVICE_NAME_KEY);
  listenerClass = readApplicationMetadata(appInfo, LISTENER_NAME_KEY);
  listenerServiceClass = readApplicationMetadata(appInfo, LISTENER_SERVICE_NAME_KEY);
  backgroundInvalidationListenerServiceClass =
      readApplicationMetadata(appInfo, BACKGROUND_INVALIDATION_LISTENER_SERVICE_NAME_KEY);
  gcmUpstreamServiceClass = readApplicationMetadata(appInfo, GCM_UPSTREAM_SERVICE_NAME_KEY);
}
 
Example 8
public Drawable getIcon(int density) {
    int iconRes = mResolveInfo.getIconResource();
    Resources resources = null;
    Drawable icon = null;
    // Get the preferred density icon from the app's resources
    if (density != 0 && iconRes != 0) {
        try {
            resources = mPm.getResourcesForApplication(mActivityInfo.applicationInfo);
            icon = resources.getDrawableForDensity(iconRes, density);
        } catch (NameNotFoundException | Resources.NotFoundException exc) {
        }
    }
    // Get the default density icon
    if (icon == null) {
        icon = mResolveInfo.loadIcon(mPm);
    }
    if (icon == null) {
        resources = Resources.getSystem();
        icon = resources.getDrawableForDensity(android.R.mipmap.sym_def_app_icon, density);
    }
    return icon;
}
 
Example 9
Source Project: AndroidComponentPlugin   Source File: ContextImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Context createApplicationContext(ApplicationInfo application, int flags)
        throws NameNotFoundException {
    LoadedApk pi = mMainThread.getPackageInfo(application, mResources.getCompatibilityInfo(),
            flags | CONTEXT_REGISTER_PACKAGE);
    if (pi != null) {
        final boolean restricted = (flags & CONTEXT_RESTRICTED) == CONTEXT_RESTRICTED;
        ContextImpl c = new ContextImpl(this, mMainThread, pi, mActivityToken,
                new UserHandle(UserHandle.getUserId(application.uid)), restricted,
                mDisplay, mOverrideConfiguration);
        if (c.mResources != null) {
            return c;
        }
    }

    throw new PackageManager.NameNotFoundException(
            "Application package " + application.packageName + " not found");
}
 
Example 10
Source Project: bankomatinfos   Source File: ChangeLog.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Constructor
 *
 * Retrieves the version names and stores the new version name in
 * SharedPreferences
 *
 * @param context
 * @param sp
 *            the shared preferences to store the last version name into
 */
public ChangeLog(Context context, SharedPreferences sp) {
    this.context = context;

    // get version numbers
    this.lastVersion = sp.getString(VERSION_KEY, NO_VERSION);
    Log.d(TAG, "lastVersion: " + lastVersion);
    try {
        this.thisVersion = context.getPackageManager().getPackageInfo(
                context.getPackageName(), 0).versionName;
    } catch (NameNotFoundException e) {
        this.thisVersion = NO_VERSION;
        Log.e(TAG, "could not get version name from manifest!");
        e.printStackTrace();
    }
    Log.d(TAG, "appVersion: " + this.thisVersion);
}
 
Example 11
Source Project: android-project-wo2b   Source File: ManifestTools.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 获取版本信息
 * 
 * @return
 */
public static VersionInfo getVersionInfo(Context context)
{
	VersionInfo versionInfo = new VersionInfo();

	try
	{
		PackageInfo pkg = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
		versionInfo.setAppName(pkg.applicationInfo.name);
		versionInfo.setVersionCode(pkg.versionCode);
		versionInfo.setVersionName(pkg.versionName);
	}
	catch (NameNotFoundException e)
	{
		Log.E(TAG, "getVersionInfo error" + e.getMessage());
		e.printStackTrace();
	}

	return versionInfo;
}
 
Example 12
Source Project: AppAuth-Android   Source File: BrowserSelectorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSelect_defaultBrowserNoCustomTabs() throws NameNotFoundException {
    // Firefox is set as the users default browser, but the version is not supporting Custom Tabs
    // BrowserSelector.getAllBrowsers will result in a list, where the Firefox browser is the
    // first element and the other browser, in this case Chrome, as the second element in the list.
    setBrowserList(CHROME, FIREFOX);
    setBrowsersWithWarmupSupport(CHROME);
    when(mContext.getPackageManager().resolveActivity(BROWSER_INTENT, 0))
        .thenReturn(FIREFOX.mResolveInfo);
    List<BrowserDescriptor> allBrowsers = BrowserSelector.getAllBrowsers(mContext);

    assertThat(allBrowsers.get(0).packageName.equals(FIREFOX.mPackageName));
    assertFalse(allBrowsers.get(0).useCustomTab);
    assertThat(allBrowsers.get(1).packageName.equals(CHROME.mPackageName));
    assertTrue(allBrowsers.get(1).useCustomTab);
}
 
Example 13
/**
 * Check to see if the app was installed from a trusted app store.
 * @param packageName the package name of the app to be tested
 * @return whether or not the app was installed from a trusted app store
 */
public boolean wasInstalledByAppStore(String packageName){
	if(shouldOverrideInstalledFrom()){
		return true;
	}
	PackageManager packageManager = context.getPackageManager();
	try {
		final ApplicationInfo applicationInfo = packageManager.getApplicationInfo(packageName, 0);
		if(TrustedAppStore.isTrustedStore(packageManager.getInstallerPackageName(applicationInfo.packageName))){
			// App was installed by trusted app store
			return true;
		}
	} catch (final NameNotFoundException e) {
		e.printStackTrace();
		return false;
	}
	return false;
}
 
Example 14
Source Project: zen4android   Source File: SuggestionsAdapter.java    License: MIT License 6 votes vote down vote up
/**
 * 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.
 */
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;
}
 
Example 15
Source Project: iMoney   Source File: ExampleUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 获取 AppKey
 *
 * @param context
 * @return
 */
public static String getAppKey(Context context) {
    Bundle metaData = null;
    String appKey = null;
    try {
        ApplicationInfo ai = context.getPackageManager().getApplicationInfo(
                context.getPackageName(), PackageManager.GET_META_DATA);
        if (null != ai) {
            metaData = ai.metaData;
        }
        if (null != metaData) {
            appKey = metaData.getString(KEY_APP_KEY);
            if ((null == appKey) || appKey.length() != 24) {
                appKey = null;
            }
        }
    } catch (NameNotFoundException e) {
        e.printStackTrace();
    }
    return appKey;
}
 
Example 16
Source Project: AndroidComponentPlugin   Source File: ContextImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Context createPackageContextAsUser(String packageName, int flags, UserHandle user)
        throws NameNotFoundException {
    final boolean restricted = (flags & CONTEXT_RESTRICTED) == CONTEXT_RESTRICTED;
    if (packageName.equals("system") || packageName.equals("android")) {
        return new ContextImpl(this, mMainThread, mPackageInfo, mActivityToken,
                user, restricted, mDisplay, mOverrideConfiguration);
    }

    LoadedApk pi = mMainThread.getPackageInfo(packageName, mResources.getCompatibilityInfo(),
            flags | CONTEXT_REGISTER_PACKAGE, user.getIdentifier());
    if (pi != null) {
        ContextImpl c = new ContextImpl(this, mMainThread, pi, mActivityToken,
                user, restricted, mDisplay, mOverrideConfiguration);
        if (c.mResources != null) {
            return c;
        }
    }

    // Should be a better exception.
    throw new PackageManager.NameNotFoundException(
            "Application package " + packageName + " not found");
}
 
Example 17
Source Project: LaunchEnr   Source File: IconCache.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Updates the entries related to the given package in memory and persistent DB.
 */
public synchronized void updateIconsForPkg(String packageName, UserHandle user) {
    removeIconsForPkg(packageName, user);
    try {
        int uninstalled = android.os.Build.VERSION.SDK_INT >= 24 ? PackageManager.MATCH_UNINSTALLED_PACKAGES : PackageManager.GET_UNINSTALLED_PACKAGES;

        PackageInfo info = mPackageManager.getPackageInfo(packageName,
                uninstalled);
        long userSerial = mUserManager.getSerialNumberForUser(user);
        for (LauncherActivityInfo app : mLauncherApps.getActivityList(packageName, user)) {
            addIconToDBAndMemCache(app, info, userSerial, false /*replace existing*/);
        }
    } catch (NameNotFoundException e) {
        e.printStackTrace();
        return;
    }
}
 
Example 18
Source Project: 365browser   Source File: AboutChromePreferences.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Build the application version to be shown.  In particular, this ensures the debug build
 * versions are more useful.
 */
public static String getApplicationVersion(Context context, String version) {
    if (ChromeVersionInfo.isOfficialBuild()) {
        return version;
    }

    // For developer builds, show how recently the app was installed/updated.
    PackageInfo info;
    try {
        info = context.getPackageManager().getPackageInfo(
                context.getPackageName(), 0);
    } catch (NameNotFoundException e) {
        return version;
    }
    CharSequence updateTimeString = DateUtils.getRelativeTimeSpanString(
            info.lastUpdateTime, System.currentTimeMillis(), 0);
    return context.getString(R.string.version_with_update_time, version,
            updateTimeString);
}
 
Example 19
Source Project: AppAuth-Android   Source File: BrowserSelectorTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Browsers are expected to be in priority order, such that the default would be first.
 */
private void setBrowserList(TestBrowser... browsers) throws NameNotFoundException {
    if (browsers == null) {
        return;
    }

    List<ResolveInfo> resolveInfos = new ArrayList<>();

    for (TestBrowser browser : browsers) {
        when(mPackageManager.getPackageInfo(
                eq(browser.mPackageInfo.packageName),
                eq(PackageManager.GET_SIGNATURES)))
                .thenReturn(browser.mPackageInfo);
        resolveInfos.add(browser.mResolveInfo);
    }

    when(mPackageManager.queryIntentActivities(
            BROWSER_INTENT,
            PackageManager.GET_RESOLVED_FILTER))
            .thenReturn(resolveInfos);
}
 
Example 20
/**
 * Called when a registration token has been received.
 *
 * @param registrationId the registration ID received from C2DM
 */
private void onRegistered(String registrationId) {
  setRegistrationInProcess(false);
  C2DMSettings.setC2DMRegistrationId(context, registrationId);
  try {
    C2DMSettings.setApplicationVersion(context, getCurrentApplicationVersion(this));
  } catch (NameNotFoundException e) {
    logger.severe("Unable to find our own package name when storing application version: %s",
        e.getMessage());
  }
  for (C2DMObserver observer : observers) {
    onRegisteredSingleObserver(registrationId, observer);
  }
}
 
Example 21
/**
 * Internal methods for getting raw information
 */

private String getVersionName() {
    PackageInfo packageInfo;
    try {
        packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
        return packageInfo.versionName;
    } catch (NameNotFoundException e) {
        Diagnostics.getLogger().logError("Failed to get version name", e);
    }
    return null;
}
 
Example 22
Source Project: quickmark   Source File: About.java    License: MIT License 5 votes vote down vote up
public static String getVersion(Context context)// ��ȡ�汾��
{
	try {
		PackageInfo pi = context.getPackageManager().getPackageInfo(
				context.getPackageName(), 0);
		return pi.versionName;
	} catch (NameNotFoundException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		return "beta 1.0";
	}
}
 
Example 23
Source Project: XERUNG   Source File: Comman.java    License: Apache License 2.0 5 votes vote down vote up
public String getAppVersionName(Context context) {
	try {
		PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
		return packageInfo.versionName;
	} catch (NameNotFoundException e) {
		// should never happen
		throw new RuntimeException("Could not get package name: " + e);
	}
}
 
Example 24
Source Project: openboard   Source File: ApplicationUtils.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static int getActivityTitleResId(final Context context,
        final Class<? extends Activity> cls) {
    final ComponentName cn = new ComponentName(context, cls);
    try {
        final ActivityInfo ai = context.getPackageManager().getActivityInfo(cn, 0);
        if (ai != null) {
            return ai.labelRes;
        }
    } catch (final NameNotFoundException e) {
        Log.e(TAG, "Failed to get settings activity title res id.", e);
    }
    return 0;
}
 
Example 25
private int getPackageVersion(final String pkg) {
	try {
		return getPackageManager().getPackageInfo(pkg, 0).versionCode;
	} catch (final NameNotFoundException e) {
		return -1;
	}
}
 
Example 26
Source Project: atlas   Source File: FrameworkLifecycleHandler.java    License: Apache License 2.0 5 votes vote down vote up
private void starting() {
        if (RuntimeVariables.safeMode) {
            return;
        }

        if (BaselineInfoManager.instance().isUpdated("com.taobao.maindex")) {
//            AdditionalPackageManager.getInstance();
        }

        long time = System.currentTimeMillis();
        android.os.Bundle metaData = null;
        try {
            ApplicationInfo applicationInfo = RuntimeVariables.androidApplication.getPackageManager().getApplicationInfo(RuntimeVariables.androidApplication.getPackageName(),
                    PackageManager.GET_META_DATA);
            metaData = applicationInfo.metaData;
        } catch (NameNotFoundException e1) {
            e1.printStackTrace();
        }

        if (metaData != null) {
            String strApps = metaData.getString("application");
            if (StringUtils.isNotEmpty(strApps)) {
                String[] appClassNames = StringUtils.split(strApps, ",");
                if (appClassNames == null || appClassNames.length == 0) {
                    appClassNames = new String[]{strApps};
                }
                for (String appClassName : appClassNames) {
                    try {
                        Application app = newApplication(appClassName,
                                Framework.getSystemClassLoader());
                        app.onCreate();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        final long timediff = System.currentTimeMillis() - time;
    }
 
Example 27
Source Project: document-viewer   Source File: LogManager.java    License: GNU General Public License v3.0 5 votes vote down vote up
private static boolean isDebugEnabledByDefault(final Context context) {
    boolean debugEnabled = false;
    final PackageManager pm = context.getPackageManager();
    try {
        final PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
        final int flags = ApplicationInfo.FLAG_DEBUGGABLE | 0x100 /* ApplicationInfo.FLAG_TEST_ONLY */;
        debugEnabled = (pi.applicationInfo.flags & flags) != 0;
    } catch (final NameNotFoundException ex) {
        ex.printStackTrace();
    }
    return debugEnabled;
}
 
Example 28
Source Project: buddycloud-android   Source File: BuddycloudHTTPHelper.java    License: Apache License 2.0 5 votes vote down vote up
protected static void addUserAgentHeader(HttpRequestBase method,
		Context parent) {
	try {
		PackageInfo pInfo = parent.getPackageManager().getPackageInfo(
				parent.getPackageName(), 0);
		method.setHeader("User-Agent", "buddycloud for Android v"
				+ pInfo.versionCode);
	} catch (NameNotFoundException e) {
		e.printStackTrace();
	}
}
 
Example 29
Source Project: product-emm   Source File: Volley.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a default instance of the worker pool and calls {@link RequestQueue#start()} on it.
 *
 * @param context A {@link Context} to use for creating the cache dir.
 * @param stack An {@link HttpStack} to use for the network, or null for default.
 * @return A started {@link RequestQueue} instance.
 */
public static RequestQueue newRequestQueue(Context context, HttpStack stack) {
    File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR);

    String userAgent = "volley/0";
    try {
        String packageName = context.getPackageName();
        PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0);
        userAgent = packageName + "/" + info.versionCode;
    } catch (NameNotFoundException e) {
    }

    if (stack == null) {
        if (Build.VERSION.SDK_INT >= 9) {
            stack = new HurlStack();
        } else {
            // Prior to Gingerbread, HttpUrlConnection was unreliable.
            // See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html
            stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
        }
    }

    Network network = new BasicNetwork(stack);

    RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network);
    queue.start();

    return queue;
}
 
Example 30
Source Project: AndroidChromium   Source File: Preferences.java    License: Apache License 2.0 5 votes vote down vote up
private void ensureActivityNotExported() {
    if (sActivityNotExportedChecked) return;
    sActivityNotExportedChecked = true;
    try {
        ActivityInfo activityInfo = getPackageManager().getActivityInfo(getComponentName(), 0);
        // If Preferences is exported, then it's vulnerable to a fragment injection exploit:
        // http://securityintelligence.com/new-vulnerability-android-framework-fragment-injection
        if (activityInfo.exported) {
            throw new IllegalStateException("Preferences must not be exported.");
        }
    } catch (NameNotFoundException ex) {
        // Something terribly wrong has happened.
        throw new RuntimeException(ex);
    }
}