android.content.pm.PackageManager.NameNotFoundException源码实例Demo

类android.content.pm.PackageManager.NameNotFoundException源码实例Demo

下面列出了android.content.pm.PackageManager.NameNotFoundException 类实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: AndroidPirateBox   文件: AbstractPluginActivity.java
@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);
    }
}
 
源代码2 项目: stitch-android-sdk   文件: Stitch.java
/**
 * 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");
}
 
源代码3 项目: document-viewer   文件: AboutActivity.java
@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);
}
 
源代码4 项目: xmall   文件: SystemWebViewClient.java
/**
 * 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);
    }
}
 
/**
 * 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;
}
 
源代码6 项目: AppAuth-Android   文件: BrowserSelectorTest.java
@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);
}
 
源代码7 项目: 365browser   文件: AndroidTiclManifest.java
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);
}
 
源代码8 项目: Trebuchet   文件: LauncherActivityInfoCompatV16.java
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;
}
 
源代码9 项目: AndroidComponentPlugin   文件: ContextImpl.java
@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");
}
 
源代码10 项目: bankomatinfos   文件: ChangeLog.java
/**
 * 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);
}
 
源代码11 项目: android-project-wo2b   文件: ManifestTools.java
/**
 * 获取版本信息
 * 
 * @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;
}
 
源代码12 项目: AppAuth-Android   文件: BrowserSelectorTest.java
@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);
}
 
源代码13 项目: sdl_java_suite   文件: RouterServiceValidator.java
/**
 * 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;
}
 
源代码14 项目: zen4android   文件: 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.
 */
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;
}
 
源代码15 项目: iMoney   文件: ExampleUtil.java
/**
 * 获取 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;
}
 
源代码16 项目: AndroidComponentPlugin   文件: ContextImpl.java
@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");
}
 
源代码17 项目: LaunchEnr   文件: IconCache.java
/**
 * 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;
    }
}
 
源代码18 项目: 365browser   文件: AboutChromePreferences.java
/**
 * 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);
}
 
源代码19 项目: AppAuth-Android   文件: BrowserSelectorTest.java
/**
 * 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);
}
 
源代码20 项目: android-chromium   文件: C2DMManager.java
/**
 * 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);
  }
}
 
源代码21 项目: shinny-futures-android   文件: DeviceInfo.java
/**
 * 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;
}
 
源代码22 项目: quickmark   文件: About.java
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";
	}
}
 
源代码23 项目: XERUNG   文件: Comman.java
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);
	}
}
 
源代码24 项目: openboard   文件: ApplicationUtils.java
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;
}
 
private int getPackageVersion(final String pkg) {
	try {
		return getPackageManager().getPackageInfo(pkg, 0).versionCode;
	} catch (final NameNotFoundException e) {
		return -1;
	}
}
 
源代码26 项目: atlas   文件: FrameworkLifecycleHandler.java
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;
    }
 
源代码27 项目: document-viewer   文件: LogManager.java
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;
}
 
源代码28 项目: buddycloud-android   文件: BuddycloudHTTPHelper.java
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();
	}
}
 
源代码29 项目: product-emm   文件: Volley.java
/**
 * 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;
}
 
源代码30 项目: AndroidChromium   文件: Preferences.java
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);
    }
}
 
如果文章对您有帮助,请点击页面广告。以鼓励作者做出的努力。
 类所在包
 类方法
 同包方法