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

项目:ROKOmoji.Emoji.Keyboard.App-Android    文件:KeyboardService.java   
private static boolean requestPermissionIfNeeded(String permission, Activity activity) {
    if (ContextCompat.checkSelfPermission(activity, permission) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(activity, new String[]{permission}, 1);
        return true;
    }
    return false;
}
项目:airgram    文件:DialogsActivity.java   
@TargetApi(Build.VERSION_CODES.M)
private void askForPermissons() {
    Activity activity = getParentActivity();
    if (activity == null) {
        return;
    }
    ArrayList<String> permissons = new ArrayList<>();
    if (activity.checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
        permissons.add(Manifest.permission.READ_CONTACTS);
        permissons.add(Manifest.permission.WRITE_CONTACTS);
        permissons.add(Manifest.permission.GET_ACCOUNTS);
    }
    if (activity.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        permissons.add(Manifest.permission.READ_EXTERNAL_STORAGE);
        permissons.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }
    String[] items = permissons.toArray(new String[permissons.size()]);
    activity.requestPermissions(items, 1);
}
项目:COB    文件:PermissionHelper.java   
private static void deliverPermissionResult(CordovaPlugin plugin, int requestCode, String[] permissions) {
    // Generate the request results
    int[] requestResults = new int[permissions.length];
    Arrays.fill(requestResults, PackageManager.PERMISSION_GRANTED);

    try {
        Method onRequestPermissionResult = CordovaPlugin.class.getDeclaredMethod(
                "onRequestPermissionResult", int.class, String[].class, int[].class);

        onRequestPermissionResult.invoke(plugin, requestCode, permissions, requestResults);
    } catch (NoSuchMethodException noSuchMethodException) {
        // Should never be caught since the plugin must be written for cordova-android 5.0.0+ if it
        // made it to this point
        LOG.e(LOG_TAG, "NoSuchMethodException when delivering permissions results", noSuchMethodException);
    } catch (IllegalAccessException illegalAccessException) {
        // Should never be caught; this is a public method
        LOG.e(LOG_TAG, "IllegalAccessException when delivering permissions results", illegalAccessException);
    } catch(InvocationTargetException invocationTargetException) {
        // This method may throw a JSONException. We are just duplicating cordova-android's
        // exception handling behavior here; all it does is log the exception in CordovaActivity,
        // print the stacktrace, and ignore it
        LOG.e(LOG_TAG, "InvocationTargetException when delivering permissions results", invocationTargetException);
    }
}
项目:Dispatch    文件:MainActivity.java   
private void getLocationPermission() {
/*
 * Request location permission, so that we can get the location of the
 * device. The result of the permission request is handled by a callback,
 * onRequestPermissionsResult.
 */
    if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
            android.Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {
        mLocationPermissionGranted = true;
    } else {
        ActivityCompat.requestPermissions(this,
                new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
                PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
    }
}
项目:AndroidBasicLibs    文件:AppUtil.java   
/**
 * 获取渠道,用于打包
 *
 * @param context
 * @param metaName
 * @return
 */
public static String getAppSource(Context context, String metaName) {
    String result = null;
    try {
        ApplicationInfo appInfo = context.getPackageManager()
                .getApplicationInfo(context.getPackageName(),
                        PackageManager.GET_META_DATA);
        if (appInfo.metaData != null) {
            result = appInfo.metaData.getString(metaName);
        }
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
        JLog.e(e.toString());
    }
    return result;
}
项目:Hands-On-Android-UI-Development    文件:AttachmentPagerFragment.java   
public void onAttachClick() {
    final int permissionStatus = ContextCompat.checkSelfPermission(
            getContext(),
            Manifest.permission.READ_EXTERNAL_STORAGE
    );

    if (permissionStatus != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(
                getActivity(),
                new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                REQUEST_ATTACH_PERMISSION
        );

        return;
    }

    final Intent attach = new Intent(Intent.ACTION_GET_CONTENT)
            .addCategory(Intent.CATEGORY_OPENABLE)
            .setType("*/*");

    startActivityForResult(attach, REQUEST_ATTACH_FILE);
}
项目:DroidPlugin    文件:IPackageManagerHookHandle.java   
@Override
protected boolean beforeInvoke(Object receiver, Method method, Object[] args) throws Throwable {
    //API 2.3, 4.01, 4.0.3_r1,
/* public int getApplicationEnabledSetting(String packageName) throws RemoteException;*/
    //API 4.1.1_r1, 4.2_r1, 4.3_r1, 4.4_r1, 5.0.2_r1
/*public int getApplicationEnabledSetting(String packageName, int userId) throws RemoteException;*/
    if (args != null) {
        final int index = 0;
        if (args.length > index && args[index] instanceof String) {
            String packageName = (String) args[index];
            if (PluginManager.getInstance().isPluginPackage(packageName)) {
                //DO NOTHING
                setFakedResult(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT);
                return true;
            }
        }
    }
    return super.beforeInvoke(receiver, method, args);
}
项目:lostfilm-android-client    文件:PlayerActivity.java   
@Override
public void onNext(DownloadLink[] downloadLinks) {
    String[] strings = new String[downloadLinks.length];
    for (int i = 0; i < downloadLinks.length; i++) {
        strings[i] = downloadLinks[i].getName();
    }
    new AlertDialog.Builder(this).setItems(strings, (dialogInterface, i) -> {
        mSelectedLink = downloadLinks[i];
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) ==
                PackageManager.PERMISSION_GRANTED) {
            loadMovie();
        } else {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    MY_PERMISSIONS_REQUEST_PLAY_MOVIE);
        }
    }).show();
}
项目:BeaconMqtt    文件:MainActivity.java   
private void checkPermissions() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        // Android M Permission check
        if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            final AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(R.string.location_access_title);
            builder.setMessage(R.string.location_access_message);
            builder.setPositiveButton(android.R.string.ok, null);
            builder.setOnDismissListener(new DialogInterface.OnDismissListener() {

                @RequiresApi(api = Build.VERSION_CODES.M)
                public void onDismiss(DialogInterface dialog) {
                    requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);
                }
            });
            builder.show();
        }
    }
}
项目:Android-Practice    文件:MainActivity.java   
public static String getKeyHash(final Context context) {
    PackageInfo packageInfo = getPackageInfo(context, PackageManager.GET_SIGNATURES);
    if (packageInfo == null)
        return null;

    for (Signature signature : packageInfo.signatures) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(signature.toByteArray());
            return android.util.Base64.encodeToString(md.digest(), android.util.Base64.NO_WRAP);
        } catch (NoSuchAlgorithmException e) {
            //Log.w(TAG, "Unable to get MessageDigest. signature=" + signature, e);
        }
    }
    return null;
}
项目:buildAPKsSamples    文件:MarketDetector.java   
public static int detect(Context c) {
    if (Build.VERSION.SDK_INT < 5)
        return APPSTORE;

    PackageManager pm = c.getPackageManager();

    String installer = pm.getInstallerPackageName(c.getPackageName());

    if (installer != null && installer.equals("com.android.vending")) 
        return MARKET;

    if (Build.MODEL.equalsIgnoreCase("Kindle Fire")) 
        return APPSTORE;

    try {
        if (pm.getPackageInfo("com.amazon.venezia", 0) != null) 
            return APPSTORE;
    } catch (NameNotFoundException e) {
    }

    return MARKET;
}
项目:VirtualHook    文件:VPackageManagerService.java   
@Override
protected ResolveInfo newResult(VPackage.ServiceIntentInfo filter, int match, int userId) {
    final VPackage.ServiceComponent service = filter.service;
    PackageSetting ps = (PackageSetting) service.owner.mExtras;
    ServiceInfo si = PackageParserEx.generateServiceInfo(service, mFlags, ps.readUserState(userId), userId);
    if (si == null) {
        return null;
    }
    final ResolveInfo res = new ResolveInfo();
    res.serviceInfo = si;
    if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
        res.filter = filter.filter;
    }
    res.priority = filter.filter.getPriority();
    res.preferredOrder = service.owner.mPreferredOrder;
    res.match = match;
    res.isDefault = filter.hasDefault;
    res.labelRes = filter.labelRes;
    res.nonLocalizedLabel = filter.nonLocalizedLabel;
    res.icon = filter.icon;
    return res;
}
项目:simple-share-android    文件:IconUtils.java   
public static Drawable loadPackagePathIcon(Context context, String path, String mimeType){
    int icon =  sMimeIcons.get(mimeType);
     if (path != null) {
         final PackageManager pm = context.getPackageManager();
try {
    final PackageInfo packageInfo = pm.getPackageArchiveInfo(path, PackageManager.GET_ACTIVITIES);
    if (packageInfo != null) {
        packageInfo.applicationInfo.sourceDir = packageInfo.applicationInfo.publicSourceDir = path;
        // know issue with nine patch image instead of drawable
        return pm.getApplicationIcon(packageInfo.applicationInfo);
    }
} catch (Exception e) {
    return ContextCompat.getDrawable(context, icon);
}
     } else {
         return ContextCompat.getDrawable(context, icon);
     }
     return null;
 }
项目:Paper-Launcher    文件:ApplicationInfoLoader.java   
public static List<ApplicationInfo> loadAppList(Context context) {
    List<ApplicationInfo> applicationInfoList = context.getPackageManager().getInstalledApplications(PackageManager.GET_META_DATA);
    Collections.sort(applicationInfoList, new ApplicationInfo.DisplayNameComparator(context.getPackageManager()));

    final ArrayList<ApplicationInfo> filteredApplicationInfoList = new ArrayList<>();
    for (ApplicationInfo applicationInfo : applicationInfoList) {
        if (context.getPackageManager().getLaunchIntentForPackage(applicationInfo.packageName) == null
                || applicationInfo.packageName.equals(context.getPackageName())) {
            continue;
        }

        filteredApplicationInfoList.add(applicationInfo);
    }

    return filteredApplicationInfoList;
}
项目:ProgressManager    文件:a.java   
private void dispatchRequestPermissionsResultToFragment(int requestCode, Intent data,
                                                        Fragment fragment) {
    // If the package installer crashed we may have not data - best effort.
    String[] permissions = (data != null) ? data.getStringArrayExtra(
            PackageManager.EXTRA_REQUEST_PERMISSIONS_NAMES) : new String[0];
    final int[] grantResults = (data != null) ? data.getIntArrayExtra(
            PackageManager.EXTRA_REQUEST_PERMISSIONS_RESULTS) : new int[0];
    fragment.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
项目:Clases-2017c1    文件:SelectPictureActivity.java   
public static void grantPermissionsToUri(Context context, Intent intent, Uri uri) {
    List<ResolveInfo> resInfoList = context.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
    for (ResolveInfo resolveInfo : resInfoList) {
        String packageName = resolveInfo.activityInfo.packageName;
        context.grantUriPermission(packageName, uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
    }
}
项目:BaseCore    文件:PhoneUtils.java   
public static boolean checkPermission(Context context, String permission) {
    boolean result = false;
    if (Build.VERSION.SDK_INT >= 23) {
        try {
            Class<?> clazz = Class.forName("android.content.Context");
            Method method = clazz.getMethod("checkSelfPermission", String.class);
            int rest = (Integer) method.invoke(context, permission);
            if (rest == PackageManager.PERMISSION_GRANTED) {
                result = true;
            } else {
                result = false;
            }
        } catch (Exception e) {
            result = false;
        }
    } else {
        PackageManager pm = context.getPackageManager();
        if (pm.checkPermission(permission, context.getPackageName()) == PackageManager.PERMISSION_GRANTED) {
            result = true;
        }
    }
    return result;
}
项目:punti-burraco    文件:TripleFragment.java   
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {

        case STORAGE_PERMISSION_SCREENSHOT:
        {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted, yay!
                openScreen();

            } else {

                // permission denied, boo!
                Toast.makeText(getActivity(), getString(R.string.marshmallow_alert_2), Toast.LENGTH_LONG).show();

            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request
    }
}
项目:AndiCar    文件:GPSTrackControllerDialogActivity.java   
@Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {

        if (grantResults.length == 0 || grantResults[0] == PackageManager.PERMISSION_DENIED) {
            if (requestCode == ConstantValues.REQUEST_LOCATION_ACCESS) {
                Toast.makeText(this, R.string.error_069, Toast.LENGTH_LONG).show();
            }
            else {
                Toast.makeText(this, R.string.error_070, Toast.LENGTH_LONG).show();
            }
            finish();
        } else {
//            if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
            if (!FileUtils.isFileSystemAccessGranted(this)) {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, ConstantValues.REQUEST_ACCESS_EXTERNAL_STORAGE);
            }
        }
    }
项目:MVVMFrames    文件:ManifestParser.java   
public List<ConfigModule> parse() {
    List<ConfigModule> modules = new ArrayList<ConfigModule>();
    try {
        ApplicationInfo appInfo = context.getPackageManager().getApplicationInfo(
                context.getPackageName(), PackageManager.GET_META_DATA);
        if (appInfo.metaData != null) {
            for (String key : appInfo.metaData.keySet()) {
                if (MODULE_VALUE.equals(appInfo.metaData.get(key))) {
                    modules.add(parseModule(key));
                }
            }
        }
    } catch (PackageManager.NameNotFoundException e) {
        throw new RuntimeException("Unable to find metadata to parse ConfigModule", e);
    }

    return modules;
}
项目:localcloud_fe    文件:PermissionHelper.java   
private static void deliverPermissionResult(CordovaPlugin plugin, int requestCode, String[] permissions) {
    // Generate the request results
    int[] requestResults = new int[permissions.length];
    Arrays.fill(requestResults, PackageManager.PERMISSION_GRANTED);

    try {
        Method onRequestPermissionResult = CordovaPlugin.class.getDeclaredMethod(
                "onRequestPermissionResult", int.class, String[].class, int[].class);

        onRequestPermissionResult.invoke(plugin, requestCode, permissions, requestResults);
    } catch (NoSuchMethodException noSuchMethodException) {
        // Should never be caught since the plugin must be written for cordova-android 5.0.0+ if it
        // made it to this point
        LOG.e(LOG_TAG, "NoSuchMethodException when delivering permissions results", noSuchMethodException);
    } catch (IllegalAccessException illegalAccessException) {
        // Should never be caught; this is a public method
        LOG.e(LOG_TAG, "IllegalAccessException when delivering permissions results", illegalAccessException);
    } catch(InvocationTargetException invocationTargetException) {
        // This method may throw a JSONException. We are just duplicating cordova-android's
        // exception handling behavior here; all it does is log the exception in CordovaActivity,
        // print the stacktrace, and ignore it
        LOG.e(LOG_TAG, "InvocationTargetException when delivering permissions results", invocationTargetException);
    }
}
项目:Paper-Melody    文件:MainActivity.java   
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == REQUEST_PERMISSION) {
        if (android.os.Build.VERSION.SDK_INT >= 23) {
            for (int i = 0; i < permissions.length; ++i) {
                // 检查该权限是否已经获取
                int per = ContextCompat.checkSelfPermission(this, permissions[i]);
                // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
                if (per != PackageManager.PERMISSION_GRANTED) {
                    // 提示用户应该去应用设置界面手动开启权限
                    showDialogTipUserGoToAppSetting();
                } else {
                    if (dialog != null && dialog.isShowing()) {
                        dialog.dismiss();
                    }
                }
            }
        }
    }
}
项目:Remindy    文件:EditImageAttachmentActivity.java   
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode){
        case REQUEST_TAKE_PICTURE_PERMISSION:
            for (int result : grantResults) {
                if(result != PackageManager.PERMISSION_GRANTED) {
                    BaseTransientBottomBar.BaseCallback<Snackbar> callback = new BaseTransientBottomBar.BaseCallback<Snackbar>() {
                        @Override
                        public void onDismissed(Snackbar transientBottomBar, int event) {
                            super.onDismissed(transientBottomBar, event);
                            handleImageCapture();
                        }
                    };
                    SnackbarUtil.showSnackbar(mContainer, SnackbarUtil.SnackbarType.NOTICE, R.string.activity_edit_image_attachment_snackbar_error_no_permissions, SnackbarUtil.SnackbarDuration.SHORT, callback);
                    return;
                }
            }

            //Permissions granted
            dispatchTakePictureIntent();
            break;
    }
}
项目:chips-input-layout    文件:ContactLoadingActivity.java   
protected void loadContactsWithRuntimePermission() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        // Runtime permission must be granted for
        // (1) Reading contacts
        // (2) Sending SMS messages
        String[] permissions = new String[] {
                Manifest.permission.READ_CONTACTS,
                Manifest.permission.READ_PHONE_STATE
        };

        // If the app doesn't have all the permissions above, request for them!
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED
                && ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
            getSupportLoaderManager().initLoader(0, null, this);
        } else {
            ActivityCompat.requestPermissions(this, permissions, 0);
        }
    } else {
        // APIs older than Lollipop don't have runtime permissions :)
        getSupportLoaderManager().initLoader(0, null, this);
    }
}
项目:EasyReader    文件:FeedbackActivity.java   
/**
 * 判断 用户是否安装QQ客户端
 */
public static boolean hasQQClientAvailable(Context context) {
    final PackageManager packageManager = context.getPackageManager();
    List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
    if (pinfo != null) {
        for (int i = 0; i < pinfo.size(); i++) {
            String pn = pinfo.get(i).packageName;
            LogUtils.e("pn = " + pn);
            if (pn.equalsIgnoreCase("com.tencent.qqlite") || pn.equalsIgnoreCase("com.tencent.mobileqq")) {
                return true;
            }
        }
    }
    return false;
}
项目:fussroll    文件:ContactsFragment.java   
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    switch (requestCode) {
        case CheckForContactsPermission.MY_PERMISSIONS_REQUEST_READ_CONTACTS: {
            if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //Log.i("ContactsFragment", "Dialog : Permission is granted");
                if(!onCreatePerm)
                    onCreatePerm = true;
                getPhoneNumbers();
            }
            else {
                //Log.i("ContactsFragment", "Dialog : Permission is not yet granted");
            }
        }
    }
}
项目:android_permission    文件:MainFragment.java   
@Override
public void onClick(View v) {
    int id = v.getId();
    if (R.id.get_contact_btn == id) {
        if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
            if (shouldShowRequestPermissionRationale(Manifest.permission.READ_CONTACTS)) {
                new AlertDialog.Builder(getContext()).setMessage("xxxx")
                        .setCancelable(false)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, 1);
                            }
                        }).create().show();
            } else {
                requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, 1);
            }

        } else {
            readContacts();
        }
    }
}
项目:YiZhi    文件:PersonalUpperPresenter.java   
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                       @NonNull int[] grantResults) {
    if (requestCode == WRITE_EXTERNAL_STORAGE_REQUEST_CODE) {
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // Permission Granted
            if (mIView != null)
                mIView.gotoSystemCamera(tempFile, REQUEST_CAMERA);
        }
    } else if (requestCode == READ_EXTERNAL_STORAGE_REQUEST_CODE) {
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // Permission Granted
            if (mIView != null)
                mIView.gotoSystemPhoto(REQUEST_PHOTO);
        }
    }
}
项目:EazyBaseMVP    文件:ManifestParser.java   
public List<ConfigModule> parse() {
    List<ConfigModule> configModules = new ArrayList<>();
    try {
        ApplicationInfo appInfo = context.getPackageManager().getApplicationInfo(context.getPackageName()
                , PackageManager.GET_META_DATA);

        if (appInfo.metaData != null) {
            for (String key : appInfo.metaData.keySet()) {
                if (MODULE_VALUE.equals(appInfo.metaData.get(key))) {
                    configModules.add(parseModule(key));
                }
            }
        }
    } catch (PackageManager.NameNotFoundException ex) {
        throw new RuntimeException("Unable to find metadata to parse ConfigModule", ex);
    }
    return configModules;
}
项目:FirebasePost    文件:PermissionsHelper.java   
/**
 * use for get {@link PermissionInfo} of all @param required
 *
 * @param context
 * @param required
 * @return
 */
private static List<PermissionInfo> getPermissions(Context context, List<String> required) {

    List<PermissionInfo> permissionInfoList = new ArrayList<>();

    PackageManager pm = context.getPackageManager();
    for (String permission : required) {
        PermissionInfo pinfo = null;
        try {
            pinfo = pm.getPermissionInfo(permission, PackageManager.GET_META_DATA);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            continue;
        }

        permissionInfoList.add(pinfo);
    }
    return permissionInfoList;
}
项目:RLibrary    文件:RCrashHandler.java   
/**
 * INTERNAL method used to get the first activity with an intent-filter <action android:name="cat.ereza.customactivityoncrash.RESTART" />,
 * If there is no activity with that intent filter, this returns null.
 *
 * @param context A valid context. Must not be null.
 * @return A valid activity class, or null if no suitable one is found
 */
@SuppressWarnings("unchecked")
private static Class<? extends Activity> getRestartActivityClassWithIntentFilter(Context context) {
    List<ResolveInfo> resolveInfos = context.getPackageManager().queryIntentActivities(
            new Intent().setAction(INTENT_ACTION_RESTART_ACTIVITY),
            PackageManager.GET_RESOLVED_FILTER);

    for (ResolveInfo info : resolveInfos) {
        if (info.activityInfo.packageName.equalsIgnoreCase(context.getPackageName())) {
            try {
                return (Class<? extends Activity>) Class.forName(info.activityInfo.name);
            } catch (ClassNotFoundException e) {
                //Should not happen, print it to the log!
                Log.e("TAG", "Failed when resolving the restart activity class via intent filter, stack trace follows!", e);
            }
        }
    }

    return null;
}
项目:BuddyBook    文件:InsertEditBookActivity.java   
@RequiresApi(api = Build.VERSION_CODES.M)
@Override
public void onRequestPermissionsResult(int requestCode,
                                       @NonNull String[] permissions,
                                       @NonNull int[] grantResults) {

    if (grantResults.length != 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        if (requestCode == RC_HANDLE_WRITE_PERM) {
            callPickPhoto();
        } else if (requestCode == RC_CAMERA_PERM) {

            int rc = ActivityCompat.checkSelfPermission(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if (rc == PackageManager.PERMISSION_GRANTED) {
                callCamera();
            } else {
                requestWriteExternalStoragePermission(RC_CAMERA_PERM);
            }
        }
    }
}
项目:GitHub    文件:Utils.java   
static boolean hasPermission(Context context, String permission) {
  return context.checkCallingOrSelfPermission(permission) == PackageManager.PERMISSION_GRANTED;
}
项目:MoligyMvpArms    文件:DeviceUtils.java   
/**
 * 当前的包是否存在
 *
 * @param context
 * @param pckName
 * @return
 */
public static boolean isPackageExist(Context context, String pckName) {
    try {
        PackageInfo pckInfo = context.getPackageManager()
                .getPackageInfo(pckName, 0);
        if (pckInfo != null)
            return true;
    } catch (PackageManager.NameNotFoundException e) {
        Log.e("TDvice", e.getMessage());
    }
    return false;
}
项目:prevent    文件:PreventActivity.java   
private boolean isInternal() {
    PackageManager pm = getPackageManager();
    try {
        String source = pm.getApplicationInfo(getPackageName(), 0).sourceDir;
        if (source.startsWith(Environment.getDataDirectory().getAbsolutePath()) || source.startsWith(Environment.getRootDirectory().getAbsolutePath())) {
            return true;
        }
    } catch (PackageManager.NameNotFoundException e) { // NOSONAR
        // do nothing
    }
    return false;
}
项目:GCSApp    文件:VersionUtil.java   
/**
 * 获取版本号
 * 也可使用 BuildConfig.VERSION_NAME 替换
 *
 * @param context 上下文
 * @return 版本号
 */
public static String getVersionName(Context context) {
    PackageManager packageManager = context.getPackageManager();
    String packageName = context.getPackageName();
    try {
        PackageInfo packageInfo = packageManager.getPackageInfo(packageName, 0);
        return packageInfo.versionName;
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
    return "1.0.0";
}
项目:keepass2android    文件:PluginManager.java   
Resources getResources(Context context) {
    PackageManager packageManager = context.getPackageManager();
    Resources res = null;
    try {
        ApplicationInfo appInfo = packageManager.getApplicationInfo(mPackageName, 0);
        res = packageManager.getResourcesForApplication(appInfo);
    } catch (NameNotFoundException e) {
        Log.i(TAG, "couldn't get resources");
    }
    return res;
}
项目:RxJava2-weather-example    文件:MainActivity.java   
private void checkLocationPermission() {
    final String locationPermission = Manifest.permission.ACCESS_FINE_LOCATION;
    try {
        if (ActivityCompat.checkSelfPermission(this, locationPermission) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{locationPermission}, REQUEST_CODE_PERMISSION);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
项目:sflauncher    文件:MainActivity.java   
private void refreshAppList(){
    new Thread(new Runnable(){

        @Override
        public void run() {
            PackageManager pm = getPackageManager();
            Intent intent = new Intent(Intent.ACTION_MAIN, null);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            List<ResolveInfo> resolves = pm.queryIntentActivities(intent, 0);
            List<App> myApps = new ArrayList<>();
            for(ResolveInfo r : resolves){
                String packageName = r.activityInfo.packageName;
                if(!packageName.equals("xyz.jathak.sflauncher")) {
                    App app = new App(r, MainActivity.this);
                    myApps.add(app);
                }
                Thread.yield();
            }
            Collections.sort(myApps);
            apps = myApps;
            toolbar.post(new Runnable(){

                @Override
                public void run() {
                    navigationDrawerAdapter.notifyDataSetChanged();
                    restoreCards();
                    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
                    if(prefs.getBoolean("firstLaunch",true)){
                        addDefaultCards();
                        cards.add(1,new Card.Tutorial(MainActivity.this));
                        SharedPreferences.Editor e = prefs.edit();
                        e.putBoolean("firstLaunch",false);
                        e.apply();
                    }
                    refreshThemes();
                }
            });
        }
    }).start();
}
项目:cordova-plugin-webview-checker    文件:WebViewChecker.java   
public void isAppEnabled(String packagename, CallbackContext callbackContext) {
  PackageManager packageManager = this.cordova.getActivity().getPackageManager();

  try {
    Boolean enabled = packageManager.getApplicationInfo(packagename, 0).enabled;
    callbackContext.success(enabled.toString());
  } catch (PackageManager.NameNotFoundException e) {
    callbackContext.error("Package not found");
  }
}