下面列出了怎么用android.content.pm.PackageManager.NameNotFoundException的API类实例代码及写法,或者点击链接到github查看源代码。
@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);
}
}
/**
* 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");
}
@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);
}
/**
* 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;
}
@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);
}
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);
}
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;
}
@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");
}
/**
* 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);
}
/**
* 获取版本信息
*
* @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;
}
@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);
}
/**
* 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;
}
/**
* 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;
}
/**
* 获取 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;
}
@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");
}
/**
* 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;
}
}
/**
* 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);
}
/**
* 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);
}
/**
* 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);
}
}
/**
* 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;
}
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";
}
}
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);
}
}
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;
}
}
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;
}
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;
}
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();
}
}
/**
* 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;
}
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);
}
}