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

项目:Nird2    文件:ScreenFilterMonitorImpl.java   
private boolean isPlayServices(String pkg) {
    if (!PLAY_SERVICES_PACKAGE.equals(pkg)) return false;
    try {
        PackageInfo sigs = pm.getPackageInfo(pkg, GET_SIGNATURES);
        // The genuine Play Services app should have a single signature
        Signature[] signatures = sigs.signatures;
        if (signatures == null || signatures.length != 1) return false;
        // Extract the public key from the signature
        CertificateFactory certFactory =
                CertificateFactory.getInstance("X509");
        byte[] signatureBytes = signatures[0].toByteArray();
        InputStream in = new ByteArrayInputStream(signatureBytes);
        X509Certificate cert =
                (X509Certificate) certFactory.generateCertificate(in);
        byte[] publicKeyBytes = cert.getPublicKey().getEncoded();
        String publicKey = StringUtils.toHexString(publicKeyBytes);
        return PLAY_SERVICES_PUBLIC_KEY.equals(publicKey);
    } catch (NameNotFoundException | CertificateException e) {
        if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
        return false;
    }
}
项目:CorePatch    文件:PackageUtils.java   
/**
 * get app version code
 *
 * @param context
 * @return
 */
public static int getAppVersionCode(Context context) {
    if (context != null) {
        PackageManager pm = context.getPackageManager();
        if (pm != null) {
            PackageInfo pi;
            try {
                pi = pm.getPackageInfo(context.getPackageName(), 0);
                if (pi != null) {
                    return pi.versionCode;
                }
            } catch (NameNotFoundException e) {
                e.printStackTrace();
            }
        }
    }
    return -1;
}
项目:CSipSimple    文件:CallHandler.java   
@Override
public void onReceive(Context context, Intent intent) {
    if(SipManager.ACTION_GET_PHONE_HANDLERS.equals(intent.getAction())) {

        PendingIntent pendingIntent = null;
        String number = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
        // We must handle that clean way cause when call just to 
        // get the row in account list expect this to reply correctly
        if(number != null && PhoneCapabilityTester.isPhone(context)) {
            // Build pending intent
            Intent i = new Intent(Intent.ACTION_CALL);
            i.setData(Uri.fromParts("tel", number, null));
            pendingIntent = PendingIntent.getActivity(context, 0, i, 0);
        }

        // Retrieve and cache infos from the phone app 
        if(!sPhoneAppInfoLoaded) {
            List<ResolveInfo> callers = PhoneCapabilityTester.resolveActivitiesForPriviledgedCall(context);
            if(callers != null) {
                for(final ResolveInfo caller : callers) {
                    if(caller.activityInfo.packageName.startsWith("com.android")) {
                        PackageManager pm = context.getPackageManager();
                        Resources remoteRes;
                        try {
                            // We load the resource in the context of the remote app to have a bitmap to return.
                            remoteRes = pm.getResourcesForApplication(caller.activityInfo.applicationInfo);
                            sPhoneAppBmp = BitmapFactory.decodeResource(remoteRes, caller.getIconResource());
                        } catch (NameNotFoundException e) {
                            Log.e(THIS_FILE, "Impossible to load ", e);
                        }
                        break;
                    }
                }
            }
            sPhoneAppInfoLoaded = true;
        }


        //Build the result for the row (label, icon, pending intent, and excluded phone number)
        Bundle results = getResultExtras(true);
        if(pendingIntent != null) {
            results.putParcelable(CallHandlerPlugin.EXTRA_REMOTE_INTENT_TOKEN, pendingIntent);
        }
        results.putString(Intent.EXTRA_TITLE, context.getResources().getString(R.string.use_pstn));
        if(sPhoneAppBmp != null) {
            results.putParcelable(Intent.EXTRA_SHORTCUT_ICON, sPhoneAppBmp);
        }

        // This will exclude next time tel:xxx is raised from csipsimple treatment which is wanted
        results.putString(Intent.EXTRA_PHONE_NUMBER, number);

    }
}
项目:SimpleUILauncher    文件:IconCache.java   
/**
 * 根据ActivityInfo绘制图标
 * @param info
 * @return
 */
public Drawable getFullResIcon(ActivityInfo info) {
    Resources resources;
    try {
        resources = mPackageManager.getResourcesForApplication(
                info.applicationInfo);
    } catch (PackageManager.NameNotFoundException e) {
        resources = null;
    }
    if (resources != null) {
        int iconId = info.getIconResource();
        if (iconId != 0) {
            return getFullResIcon(resources, iconId);
        }
    }

    return getFullResDefaultActivityIcon();
}
项目:GitHub    文件:NonBitmapDrawableResourcesTest.java   
@Test
public void load_withApplicationIconResourceIdUri_asDrawable_withTransformation_nonNullDrawable()
    throws NameNotFoundException, ExecutionException, InterruptedException {
  for (String packageName : getInstalledPackages()) {
    int iconResourceId = getResourceId(packageName);

    Uri uri = new Uri.Builder()
        .scheme(ContentResolver.SCHEME_ANDROID_RESOURCE)
        .authority(packageName)
        .path(String.valueOf(iconResourceId))
        .build();

    Drawable drawable = Glide.with(context)
        .load(uri)
        .apply(centerCropTransform())
        .submit()
        .get();
    assertThat(drawable).isNotNull();
  }
}
项目:GitHub    文件:NonBitmapDrawableResourcesTest.java   
@Test
public void load_withApplicationIconResourceNameUri_asDrawable_withTransform_nonNullDrawable()
    throws ExecutionException, InterruptedException, NameNotFoundException {
  for (String packageName : getInstalledPackages()) {
    int iconResourceId = getResourceId(packageName);

    Context toUse = context.createPackageContext(packageName, /*flags=*/ 0);
    Resources resources = toUse.getResources();
    Uri uri = new Uri.Builder()
        .scheme(ContentResolver.SCHEME_ANDROID_RESOURCE)
        .authority(packageName)
        .path(resources.getResourceTypeName(iconResourceId))
        .path(resources.getResourceEntryName(iconResourceId))
        .path(String.valueOf(iconResourceId))
        .build();

    Drawable drawable = Glide.with(context)
        .load(uri)
        .apply(centerCropTransform())
        .submit()
        .get();
    assertThat(drawable).isNotNull();
  }
}
项目:GitHub    文件:NonBitmapDrawableResourcesTest.java   
@Test
public void load_withApplicationIconResourceNameUri_asBitmap_producesNonNullBitmap()
    throws ExecutionException, InterruptedException, NameNotFoundException {
  for (String packageName : getInstalledPackages()) {
    int iconResourceId = getResourceId(packageName);

    Context toUse = context.createPackageContext(packageName, /*flags=*/ 0);
    Resources resources = toUse.getResources();
    Uri uri = new Uri.Builder()
        .scheme(ContentResolver.SCHEME_ANDROID_RESOURCE)
        .authority(packageName)
        .path(resources.getResourceTypeName(iconResourceId))
        .path(resources.getResourceEntryName(iconResourceId))
        .path(String.valueOf(iconResourceId))
        .build();

    Bitmap bitmap = Glide.with(context)
        .asBitmap()
        .load(uri)
        .submit()
        .get();
    assertThat(bitmap).isNotNull();
  }
}
项目:localcloud_fe    文件: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);
    }
}
项目:cordova-plugin-x5-tbs    文件:X5WebViewClient.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);
  }
}
项目:LaunchEnr    文件:LauncherProvider.java   
/**
 * Creates workspace loader from an XML resource listed in the app restrictions.
 *
 * @return the loader if the restrictions are set and the resource exists; null otherwise.
 */
private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction(AppWidgetHost widgetHost) {
    Context ctx = getContext();
    UserManager um = (UserManager) ctx.getSystemService(Context.USER_SERVICE);
    Bundle bundle = um.getApplicationRestrictions(ctx.getPackageName());
    if (bundle == null) {
        return null;
    }

    String packageName = bundle.getString(RESTRICTION_PACKAGE_NAME);
    if (packageName != null) {
        try {
            Resources targetResources = ctx.getPackageManager()
                    .getResourcesForApplication(packageName);
            return AutoInstallsLayout.get(ctx, packageName, targetResources,
                    widgetHost, mOpenHelper);
        } catch (NameNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }
    return null;
}
项目:LoRaWAN-Smart-Parking    文件:CordovaWebViewClient.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 = this.cordova.getActivity().getPackageName();
    final PackageManager pm = this.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);
    }
}
项目:FlickLauncher    文件:Utilities.java   
static Pair<String, Resources> findSystemApk(String action, PackageManager pm) {
    final Intent intent = new Intent(action);
    for (ResolveInfo info : pm.queryBroadcastReceivers(intent, 0)) {
        if (info.activityInfo != null &&
                (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
            final String packageName = info.activityInfo.packageName;
            try {
                final Resources res = pm.getResourcesForApplication(packageName);
                return Pair.create(packageName, res);
            } catch (NameNotFoundException e) {
                Log.w(TAG, "Failed to find resources for " + packageName);
            }
        }
    }
    return null;
}
项目:LaunchEnr    文件:IconsManager.java   
Bitmap getDefaultAppDrawable(String packageName) {
    Drawable drawable = null;
    try {
        drawable = mPackageManager.getApplicationIcon(mPackageManager.getApplicationInfo(
                packageName, 0));
    } catch (NameNotFoundException e) {
        e.printStackTrace();
    }
    if (drawable == null) {
        return null;
    }
    if (drawable instanceof BitmapDrawable) {
        return generateBitmap(((BitmapDrawable) drawable).getBitmap());
    }
    return generateBitmap(Bitmap.createBitmap(drawable.getIntrinsicWidth(),
            drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888));
}
项目:XPrivacy    文件:ApplicationInfoEx.java   
public long getInstallTime(Context context) {
    if (mInstallTime == -1) {
        long now = System.currentTimeMillis();
        mInstallTime = now;
        for (String packageName : this.getPackageName())
            try {
                getPackageInfo(context, packageName);
                long time = mMapPkgInfo.get(packageName).firstInstallTime;
                if (time < mInstallTime)
                    mInstallTime = time;
            } catch (NameNotFoundException ex) {
            }
        if (mInstallTime == now)
            // no install time, so assume it is old
            mInstallTime = 0;
    }
    return mInstallTime;
}
项目:buildAPKsSamples    文件:ComponentFragment.java   
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup root,
        Bundle savedInstanceState) {
    View view;

    CharSequence app_name = "NOT FOUND";
    try {
        // Load resources from UIComponent APK, not from activity APK
        Resources res = (Resources) getActivity().getPackageManager()
                .getResourcesForApplication(
                        this.getClass().getPackage().getName());
        view = inflater.inflate(res.getXml(R.layout.component), null);
        app_name = res.getText(R.string.app_name);
    } catch (NameNotFoundException e) {
        // Failed to load resources from our own APK
        e.printStackTrace();
        TextView out = new TextView(getActivity());
        out.setText(app_name);
        view = out;
    }

    return view;
}
项目:boohee_v5.6    文件:Global.java   
public static void saveVersionCode() {
    Context context = getContext();
    if (context != null) {
        try {
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context
                    .getPackageName(), 0);
            if (packageInfo != null) {
                Editor edit = context.getSharedPreferences("openSdk.pref", 0).edit();
                edit.putInt("app.vercode", packageInfo.versionCode);
                edit.commit();
            }
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
    }
}
项目:JPush    文件:ExampleUtil.java   
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) {

    }
    return appKey;
}
项目:cordova-vuetify    文件: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);
    }
}
项目:condom    文件:CondomKitTest.java   
@Test @SuppressLint("HardwareIds") public void testNullDeviceIdKit() throws NameNotFoundException {
    final CondomContext condom = CondomContext.wrap(new ContextWrapper(context), "NullDeviceId",
            new CondomOptions().addKit(new NullDeviceIdKit()));
    final TelephonyManager tm = (TelephonyManager) condom.getSystemService(Context.TELEPHONY_SERVICE);
    assertNotNull(tm);
    assertTrue(tm.getClass().getName().startsWith(NullDeviceIdKit.class.getName()));
    final TelephonyManager app_tm = (TelephonyManager) condom.getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE);
    assertNotNull(app_tm);
    assertTrue(app_tm.getClass().getName().startsWith(NullDeviceIdKit.class.getName()));

    assertPermission(condom, READ_PHONE_STATE, true);

    assertNull(tm.getDeviceId());
    if (SDK_INT >= LOLLIPOP) {
        if (SDK_INT >= M) assertNull(tm.getDeviceId(0));
        assertNull(tm.getImei());
        assertNull(tm.getImei(0));
        if (SDK_INT >= O) assertNull(tm.getMeid());
        if (SDK_INT >= O) assertNull(tm.getMeid(0));
    }
    assertNull(tm.getSimSerialNumber());
    assertNull(tm.getLine1Number());
    assertNull(tm.getSubscriberId());
}
项目:ProgressManager    文件:a.java   
/**
 * Obtain an {@link Intent} that will launch an explicit target activity specified by
 * this activity's logical parent. The logical parent is named in the application's manifest
 * by the {@link android.R.attr#parentActivityName parentActivityName} attribute.
 * Activity subclasses may override this method to modify the Intent returned by
 * super.getParentActivityIntent() or to implement a different mechanism of retrieving
 * the parent intent entirely.
 *
 * @return a new Intent targeting the defined parent of this activity or null if
 *         there is no valid parent.
 */
@Nullable
public Intent getParentActivityIntent() {
    final String parentName = mActivityInfo.parentActivityName;
    if (TextUtils.isEmpty(parentName)) {
        return null;
    }

    // If the parent itself has no parent, generate a main activity intent.
    final ComponentName target = new ComponentName(this, parentName);
    try {
        final ActivityInfo parentInfo = getPackageManager().getActivityInfo(target, 0);
        final String parentActivity = parentInfo.parentActivityName;
        final Intent parentIntent = parentActivity == null
                ? Intent.makeMainActivity(target)
                : new Intent().setComponent(target);
        return parentIntent;
    } catch (NameNotFoundException e) {
        Log.e(TAG, "getParentActivityIntent: bad parentActivityName '" + parentName +
                "' in manifest");
        return null;
    }
}
项目:ProgressManager    文件:a.java   
/**
 * Obtain an {@link Intent} that will launch an explicit target activity specified by
 * this activity's logical parent. The logical parent is named in the application's manifest
 * by the {@link android.R.attr#parentActivityName parentActivityName} attribute.
 * Activity subclasses may override this method to modify the Intent returned by
 * super.getParentActivityIntent() or to implement a different mechanism of retrieving
 * the parent intent entirely.
 *
 * @return a new Intent targeting the defined parent of this activity or null if
 *         there is no valid parent.
 */
@Nullable
public Intent getParentActivityIntent() {
    final String parentName = mActivityInfo.parentActivityName;
    if (TextUtils.isEmpty(parentName)) {
        return null;
    }

    // If the parent itself has no parent, generate a main activity intent.
    final ComponentName target = new ComponentName(this, parentName);
    try {
        final ActivityInfo parentInfo = getPackageManager().getActivityInfo(target, 0);
        final String parentActivity = parentInfo.parentActivityName;
        final Intent parentIntent = parentActivity == null
                ? Intent.makeMainActivity(target)
                : new Intent().setComponent(target);
        return parentIntent;
    } catch (NameNotFoundException e) {
        Log.e(TAG, "getParentActivityIntent: bad parentActivityName '" + parentName +
                "' in manifest");
        return null;
    }
}
项目:XPrivacy    文件:Requirements.java   
public static void checkCompatibility(ActivityBase context) {
    for (String packageName : cIncompatible)
        try {
            ApplicationInfo appInfo = context.getPackageManager().getApplicationInfo(packageName, 0);
            if (appInfo.enabled) {
                String name = context.getPackageManager().getApplicationLabel(appInfo).toString();

                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
                alertDialogBuilder.setTitle(R.string.app_name);
                alertDialogBuilder.setMessage(String.format(context.getString(R.string.app_incompatible), name));
                alertDialogBuilder.setIcon(context.getThemed(R.attr.icon_launcher));
                alertDialogBuilder.setPositiveButton(context.getString(android.R.string.ok),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                            }
                        });
                AlertDialog alertDialog = alertDialogBuilder.create();
                alertDialog.show();
            }
        } catch (NameNotFoundException ex) {
        }
}
项目:letv    文件:rccccr.java   
private void b0449щ0449щ0449щ() {
    PackageManager packageManager = this.bн043Dнннн.getPackageManager();
    try {
        ApplicationInfo applicationInfo = packageManager.getApplicationInfo(this.bн043Dнннн.getPackageName(), 0);
        int bЗЗ0417ЗЗЗ = bЗЗ0417ЗЗЗ();
        switch ((bЗЗ0417ЗЗЗ * (bЗ0417ЗЗЗЗ + bЗЗ0417ЗЗЗ)) % b04170417ЗЗЗЗ) {
            case 0:
                break;
            default:
                b0417ЗЗЗЗЗ = 73;
                bЗ0417ЗЗЗЗ = 43;
                break;
        }
        this.b043Dннннн = applicationInfo.loadLabel(packageManager).toString();
    } catch (NameNotFoundException e) {
        this.b043Dннннн = "NOT_FOUND";
    }
}
项目:ProgressManager    文件:a.java   
/**
 * Obtain an {@link Intent} that will launch an explicit target activity specified by
 * this activity's logical parent. The logical parent is named in the application's manifest
 * by the {@link android.R.attr#parentActivityName parentActivityName} attribute.
 * Activity subclasses may override this method to modify the Intent returned by
 * super.getParentActivityIntent() or to implement a different mechanism of retrieving
 * the parent intent entirely.
 *
 * @return a new Intent targeting the defined parent of this activity or null if
 *         there is no valid parent.
 */
@Nullable
public Intent getParentActivityIntent() {
    final String parentName = mActivityInfo.parentActivityName;
    if (TextUtils.isEmpty(parentName)) {
        return null;
    }

    // If the parent itself has no parent, generate a main activity intent.
    final ComponentName target = new ComponentName(this, parentName);
    try {
        final ActivityInfo parentInfo = getPackageManager().getActivityInfo(target, 0);
        final String parentActivity = parentInfo.parentActivityName;
        final Intent parentIntent = parentActivity == null
                ? Intent.makeMainActivity(target)
                : new Intent().setComponent(target);
        return parentIntent;
    } catch (NameNotFoundException e) {
        Log.e(TAG, "getParentActivityIntent: bad parentActivityName '" + parentName +
                "' in manifest");
        return null;
    }
}
项目:ProgressManager    文件:a.java   
/**
 * Obtain an {@link Intent} that will launch an explicit target activity specified by
 * this activity's logical parent. The logical parent is named in the application's manifest
 * by the {@link android.R.attr#parentActivityName parentActivityName} attribute.
 * Activity subclasses may override this method to modify the Intent returned by
 * super.getParentActivityIntent() or to implement a different mechanism of retrieving
 * the parent intent entirely.
 *
 * @return a new Intent targeting the defined parent of this activity or null if
 *         there is no valid parent.
 */
@Nullable
public Intent getParentActivityIntent() {
    final String parentName = mActivityInfo.parentActivityName;
    if (TextUtils.isEmpty(parentName)) {
        return null;
    }

    // If the parent itself has no parent, generate a main activity intent.
    final ComponentName target = new ComponentName(this, parentName);
    try {
        final ActivityInfo parentInfo = getPackageManager().getActivityInfo(target, 0);
        final String parentActivity = parentInfo.parentActivityName;
        final Intent parentIntent = parentActivity == null
                ? Intent.makeMainActivity(target)
                : new Intent().setComponent(target);
        return parentIntent;
    } catch (NameNotFoundException e) {
        Log.e(TAG, "getParentActivityIntent: bad parentActivityName '" + parentName +
                "' in manifest");
        return null;
    }
}
项目:Leanplum-Android-SDK    文件:LocationManagerImplementation.java   
private boolean isMetaDataSet() {
  Context context = Leanplum.getContext();
  try {
    ApplicationInfo appInfo = context.getPackageManager().getApplicationInfo(
        context.getPackageName(), PackageManager.GET_META_DATA);
    if (appInfo != null) {
      if (appInfo.metaData != null) {
        Object value = appInfo.metaData.get(METADATA);
        if (value != null) {
          return true;
        }
      }
    }
    return false;
  } catch (NameNotFoundException e) {
    return false;
  }
}
项目:prevent    文件:PreventFragment.java   
@Override
protected Set<AppInfo> doInBackground(Void... params) {
    PreventActivity pa = wr.get();
    Set<AppInfo> applications = new TreeSet<AppInfo>();
    if (pa == null) {
        return applications;
    }
    PackageManager pm = pa.getPackageManager();
    Map<String, Set<Long>> running = pa.getRunningProcesses();
    int i = 1;
    for (String name : mAdapter.getNames()) {
        publishProgress(++i);
        ApplicationInfo info;
        try {
            info = pm.getApplicationInfo(name, 0);
        } catch (NameNotFoundException e) { // NOSONAR
            info = null;
        }
        if (info == null || !info.enabled) {
            continue;
        }
        String label = labelLoader.loadLabel(info);
        applications.add(new AppInfo(name, label, running.get(name)).setFlags(info.flags));
    }
    return applications;
}
项目:NoticeDog    文件:SMSApp.java   
public Drawable getAppIcon() {
    try {
        return this.context.getPackageManager().getApplicationIcon(getAppPackageName());
    } catch (NameNotFoundException e) {
        return null;
    }
}
项目:meipai-Android    文件:VCamera.java   
/**
 * 获取当前应用的版本号
 * @param context
 * @return
 */
public static int getVerCode(Context context) {
    int verCode = -1;
    try {
        verCode = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;
    } catch (NameNotFoundException e) {
    }
    return verCode;
}
项目:lineagex86    文件:ZenModeEventRuleSettings.java   
private static Context getContextForUser(Context context, UserHandle user) {
    try {
        return context.createPackageContextAsUser(context.getPackageName(), 0, user);
    } catch (NameNotFoundException e) {
        return null;
    }
}
项目:1946    文件:GcmPush.java   
/**
 * @return Application's version code from the {@code PackageManager}.
 */
private static int getAppVersion(Context context) 
{
    try {
        PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
        return packageInfo.versionCode;
    } catch (NameNotFoundException e) {
        // should never happen
        throw new RuntimeException("Could not get package name: " + e);
    }
}
项目:chromium-for-android-56-debug-video    文件:ManageSpaceActivity.java   
private void ensureActivityNotExported() {
    if (sActivityNotExportedChecked) return;
    sActivityNotExportedChecked = true;
    try {
        ActivityInfo activityInfo = getPackageManager().getActivityInfo(getComponentName(), 0);
        if (activityInfo.exported) {
            throw new IllegalStateException("ManageSpaceActivity must not be exported.");
        }
    } catch (NameNotFoundException ex) {
        // Something terribly wrong has happened.
        throw new RuntimeException(ex);
    }
}
项目:Exoplayer2Radio    文件:Util.java   
/**
 * Returns a user agent string based on the given application name and the library version.
 *
 * @param context A valid context of the calling application.
 * @param applicationName String that will be prefix'ed to the generated user agent.
 * @return A user agent string generated using the applicationName and the library version.
 */
public static String getUserAgent(Context context, String applicationName) {
  String versionName;
  try {
    String packageName = context.getPackageName();
    PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0);
    versionName = info.versionName;
  } catch (NameNotFoundException e) {
    versionName = "?";
  }
  return applicationName + "/" + versionName + " (Linux;Android " + Build.VERSION.RELEASE
      + ") " + ExoPlayerLibraryInfo.VERSION_SLASHY;
}
项目:GitHub    文件: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;
}
项目:AndroidBasicLibs    文件:SystemUtils.java   
public static String getAppVersionName(Context context) {
    String version = "0";
    try {
        version = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
    } catch (NameNotFoundException e) {
        e.printStackTrace();
    }
    return version;
}
项目:NoticeDog    文件:OverlayNotificationBarView.java   
private Drawable getActionIcon(String appId, int resourceId) {
    try {
        return this.context.getPackageManager().getResourcesForApplication(this.appManager.getAppById(appId).getAppPackageName()).getDrawable(resourceId);
    } catch (NameNotFoundException nnfe) {
        Log.d(TAG, "Caught PackageManager.NameNotFoundException when loading resource: " + Log.getStackTraceString(nnfe));
        return null;
    } catch (Exception e) {
        Log.d(TAG, "Caught exception when loading resource: " + Log.getStackTraceString(e));
        return null;
    }
}
项目:letv    文件:ShareCompat.java   
public CharSequence getCallingApplicationLabel() {
    CharSequence charSequence = null;
    if (this.mCallingPackage != null) {
        PackageManager pm = this.mActivity.getPackageManager();
        try {
            charSequence = pm.getApplicationLabel(pm.getApplicationInfo(this.mCallingPackage, 0));
        } catch (NameNotFoundException e) {
            Log.e(TAG, "Could not retrieve label for calling application", e);
        }
    }
    return charSequence;
}
项目:Nird2    文件:ScreenFilterMonitorImpl.java   
@Nullable
private String isOverlayApp(String pkg) {
    try {
        PackageInfo pkgInfo = pm.getPackageInfo(pkg, GET_PERMISSIONS);
        if (isOverlayApp(pkgInfo)) {
            return pkgToString(pkgInfo);
        }
    } catch (NameNotFoundException e) {
        if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
    }
    return null;
}
项目:AirQuickUtils    文件:AirSystem.java   
/**
 * Check whether certain apps are installed
 *
 * @param packageName name of the package (e.g. "com.example.app")
 * @return True if installed , Returns false if none is present
 */
public static boolean isInstalledApp( String packageName) {
    PackageManager pm = AirQuickUtils.getContext().getPackageManager();
    try {
        return (pm.getPackageInfo(packageName, PackageManager.GET_SIGNATURES) != null);
    } catch (PackageManager.NameNotFoundException e) {
        return false;
    }
}
项目:GravityBox    文件:UnlockActivity.java   
protected static void checkPolicyOk(final Context context, final CheckPolicyHandler policyHandler) {
    final CheckPolicyReceiver receiver = new CheckPolicyReceiver(context, policyHandler);;
    try {
        PackageInfo pkgInfo = context.getPackageManager()
                .getPackageInfo(PKG_UNLOCKER, 0);
        if (pkgInfo.versionCode < 16) {
            policyHandler.onPolicyResult(false);
            Toast.makeText(context, context.getString(R.string.msg_unlocker_old),
                    Toast.LENGTH_LONG).show();
            return;
        }
        Intent intent = new Intent(ACTION_CHECK_POLICY);
        intent.setComponent(new ComponentName(pkgInfo.packageName,
                pkgInfo.packageName+".CheckPolicyService"));
        receiver.register();
        context.startService(intent);
    } catch (NameNotFoundException nnfe) {
        policyHandler.onPolicyResult(false);
        Toast.makeText(context, context.getString(R.string.msg_unlocker_missing),
                Toast.LENGTH_LONG).show();
    } catch (Exception e) {
        receiver.unregister();
        policyHandler.onPolicyResult(false);
        Toast.makeText(context,
                String.format("%s: %s",
                context.getString(R.string.msg_unlocker_error),
                e.getMessage()),
                Toast.LENGTH_LONG).show();
    }
}