Java Code Examples for android.content.pm.PackageManager

The following are top voted examples for showing how to use android.content.pm.PackageManager. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: ROKOmoji.Emoji.Keyboard.App-Android   File: KeyboardService.java   Source Code and License 9 votes vote down vote up
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;
}
 
Example 2
Project: airgram   File: DialogsActivity.java   Source Code and License 8 votes vote down vote up
@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);
}
 
Example 3
Project: COB   File: PermissionHelper.java   Source Code and License 7 votes vote down vote up
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);
    }
}
 
Example 4
Project: Dispatch   File: MainActivity.java   Source Code and License 6 votes vote down vote up
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);
    }
}
 
Example 5
Project: AndroidBasicLibs   File: AppUtil.java   Source Code and License 6 votes vote down vote up
/**
 * 获取渠道,用于打包
 *
 * @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;
}
 
Example 6
Project: Hands-On-Android-UI-Development   File: AttachmentPagerFragment.java   Source Code and License 6 votes vote down vote up
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);
}
 
Example 7
Project: DroidPlugin   File: IPackageManagerHookHandle.java   Source Code and License 6 votes vote down vote up
@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);
}
 
Example 8
Project: lostfilm-android-client   File: PlayerActivity.java   Source Code and License 6 votes vote down vote up
@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();
}
 
Example 9
Project: BeaconMqtt   File: MainActivity.java   Source Code and License 6 votes vote down vote up
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();
        }
    }
}
 
Example 10
Project: Android-Practice   File: MainActivity.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 11
Project: buildAPKsSamples   File: MarketDetector.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 12
Project: AppsTimeline   File: DataManager.java   Source Code and License 6 votes vote down vote up
private Map<String, Long> getMobileData(Context context, TelephonyManager tm, NetworkStatsManager nsm, int offset) {
    Map<String, Long> result = new HashMap<>();
    if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
        long[] range = AppUtil.getTimeRange(SortEnum.getSortEnum(offset));
        NetworkStats networkStatsM;
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                networkStatsM = nsm.querySummary(ConnectivityManager.TYPE_MOBILE, tm.getSubscriberId(), range[0], range[1]);
                if (networkStatsM != null) {
                    while (networkStatsM.hasNextBucket()) {
                        NetworkStats.Bucket bucket = new NetworkStats.Bucket();
                        networkStatsM.getNextBucket(bucket);
                        String key = "u" + bucket.getUid();
                        if (result.containsKey(key)) {
                            result.put(key, result.get(key) + bucket.getTxBytes() + bucket.getRxBytes());
                        } else {
                            result.put(key, bucket.getTxBytes() + bucket.getRxBytes());
                        }
                    }
                }
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }
    return result;
}
 
Example 13
Project: VirtualHook   File: VPackageManagerService.java   Source Code and License 6 votes vote down vote up
@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;
}
 
Example 14
Project: simple-share-android   File: IconUtils.java   Source Code and License 6 votes vote down vote up
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;
 }
 
Example 15
Project: Paper-Launcher   File: ApplicationInfoLoader.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 16
Project: ProgressManager   File: a.java   Source Code and License 6 votes vote down vote up
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);
}
 
Example 17
Project: Clases-2017c1   File: SelectPictureActivity.java   Source Code and License 6 votes vote down vote up
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);
    }
}
 
Example 18
Project: BaseCore   File: PhoneUtils.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 19
Project: punti-burraco   File: TripleFragment.java   Source Code and License 6 votes vote down vote up
@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
    }
}
 
Example 20
Project: AndiCar   File: GPSTrackControllerDialogActivity.java   Source Code and License 6 votes vote down vote up
@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);
            }
        }
    }
 
Example 21
Project: MVVMFrames   File: ManifestParser.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 22
Project: localcloud_fe   File: PermissionHelper.java   Source Code and License 6 votes vote down vote up
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);
    }
}
 
Example 23
Project: Paper-Melody   File: MainActivity.java   Source Code and License 6 votes vote down vote up
@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();
                    }
                }
            }
        }
    }
}
 
Example 24
Project: Remindy   File: EditImageAttachmentActivity.java   Source Code and License 6 votes vote down vote up
@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;
    }
}
 
Example 25
Project: chips-input-layout   File: ContactLoadingActivity.java   Source Code and License 6 votes vote down vote up
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);
    }
}
 
Example 26
Project: EasyReader   File: FeedbackActivity.java   Source Code and License 6 votes vote down vote up
/**
 * 判断 用户是否安装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;
}
 
Example 27
Project: fussroll   File: ContactsFragment.java   Source Code and License 6 votes vote down vote up
@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");
            }
        }
    }
}
 
Example 28
Project: android_permission   File: MainFragment.java   Source Code and License 6 votes vote down vote up
@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();
        }
    }
}
 
Example 29
Project: YiZhi   File: PersonalUpperPresenter.java   Source Code and License 6 votes vote down vote up
@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);
        }
    }
}
 
Example 30
Project: EazyBaseMVP   File: ManifestParser.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 31
Project: FirebasePost   File: PermissionsHelper.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
}
 
Example 32
Project: RLibrary   File: RCrashHandler.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
}
 
Example 33
Project: BuddyBook   File: InsertEditBookActivity.java   Source Code and License 6 votes vote down vote up
@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);
            }
        }
    }
}
 
Example 34
Project: GitHub   File: Utils.java   Source Code and License 5 votes vote down vote up
static boolean hasPermission(Context context, String permission) {
  return context.checkCallingOrSelfPermission(permission) == PackageManager.PERMISSION_GRANTED;
}
 
Example 35
Project: MoligyMvpArms   File: DeviceUtils.java   Source Code and License 5 votes vote down vote up
/**
 * 当前的包是否存在
 *
 * @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;
}
 
Example 36
Project: prevent   File: PreventActivity.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 37
Project: GCSApp   File: VersionUtil.java   Source Code and License 5 votes vote down vote up
/**
 * 获取版本号
 * 也可使用 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";
}
 
Example 38
Project: keepass2android   File: PluginManager.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 39
Project: RxJava2-weather-example   File: MainActivity.java   Source Code and License 5 votes vote down vote up
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();
    }
}
 
Example 40
Project: sflauncher   File: MainActivity.java   Source Code and License 5 votes vote down vote up
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();
}
 
Example 41
Project: cordova-plugin-webview-checker   File: WebViewChecker.java   Source Code and License 5 votes vote down vote up
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");
  }
}
 
Example 42
Project: AndroidUtilCode-master   File: AppUtils.java   Source Code and License 5 votes vote down vote up
/**
 * 获取App名称
 *
 * @param packageName 包名
 * @return App名称
 */
public static String getAppName(String packageName) {
    if (isSpace(packageName)) return null;
    try {
        PackageManager pm = Utils.getContext().getPackageManager();
        PackageInfo pi = pm.getPackageInfo(packageName, 0);
        return pi == null ? null : pi.applicationInfo.loadLabel(pm).toString();
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 43
Project: MediaNotification   File: PlayerData.java   Source Code and License 5 votes vote down vote up
public boolean isInstalled(PackageManager packageManager) {
    try {
        packageManager.getPackageInfo(packageName, PackageManager.GET_META_DATA);
    } catch (PackageManager.NameNotFoundException e) {
        return false;
    }

    return true;
}
 
Example 44
Project: puremadrid   File: DeviceInfo.java   Source Code and License 5 votes vote down vote up
public static int getVersionCode(Context context) {
    PackageInfo pInfo = null;
    try {
        pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
    } catch (PackageManager.NameNotFoundException e) {
        return -1;
    }
    return pInfo.versionCode;
}
 
Example 45
Project: ZhidaoDaily-android   File: AppUtils.java   Source Code and License 5 votes vote down vote up
public String getAppCurrentVersion(Context context) {
    PackageManager manager = context.getPackageManager();
    try {
        PackageInfo packageInfo = manager.getPackageInfo(context.getPackageName(), 0);
        return packageInfo.versionName;
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
        return "1.0";
    }
}
 
Example 46
Project: CSipSimple   File: MenuBuilder.java   Source Code and License 5 votes vote down vote up
public int addIntentOptions(int group, int id, int categoryOrder, ComponentName caller,
        Intent[] specifics, Intent intent, int flags, MenuItem[] outSpecificItems) {
    PackageManager pm = mContext.getPackageManager();
    final List<ResolveInfo> lri =
            pm.queryIntentActivityOptions(caller, specifics, intent, 0);
    final int N = lri != null ? lri.size() : 0;

    if ((flags & FLAG_APPEND_TO_GROUP) == 0) {
        removeGroup(group);
    }

    for (int i=0; i<N; i++) {
        final ResolveInfo ri = lri.get(i);
        Intent rintent = new Intent(
            ri.specificIndex < 0 ? intent : specifics[ri.specificIndex]);
        rintent.setComponent(new ComponentName(
                ri.activityInfo.applicationInfo.packageName,
                ri.activityInfo.name));
        final MenuItem item = add(group, id, categoryOrder, ri.loadLabel(pm))
                .setIcon(ri.loadIcon(pm))
                .setIntent(rintent);
        if (outSpecificItems != null && ri.specificIndex >= 0) {
            outSpecificItems[ri.specificIndex] = item;
        }
    }

    return N;
}
 
Example 47
Project: treetracker-android   File: NoteFragment.java   Source Code and License 5 votes vote down vote up
private void takePicture() {
	if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
		ActivityCompat.requestPermissions( getActivity(), new String[] {  Manifest.permission.CAMERA  },
				Permissions.MY_PERMISSION_CAMERA);
	} else {
		Intent takePictureIntent = new Intent(getActivity(), CameraActivity.class);
		startActivityForResult(takePictureIntent, ValueHelper.INTENT_CAMERA);
	}
}
 
Example 48
Project: Brevent   File: BreventActivity.java   Source Code and License 5 votes vote down vote up
private boolean isSystemPackage(String packageName) {
    try {
        return isSystemPackage(getPackageManager().getApplicationInfo(packageName, 0).flags);
    } catch (PackageManager.NameNotFoundException e) {
        return false;
    }
}
 
Example 49
Project: HeadlineNews   File: PermissionUtils.java   Source Code and License 5 votes vote down vote up
/**
 * 获取请求权限中需要授权的权限
 */
private static String[] getDeniedPermissions(final Context context, final String[] permissions) {
    List<String> deniedPermissions = new ArrayList<>();
    for (String permission : permissions) {
        if (ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_DENIED) {
            deniedPermissions.add(permission);
        }
    }
    return deniedPermissions.toArray(new String[deniedPermissions.size()]);
}
 
Example 50
Project: FinalProject   File: StartPage03.java   Source Code and License 5 votes vote down vote up
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                       @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        if (requestCode == getResources().getInteger(R.integer.contacts_request)) {
            contactMethod();
        }
    }
}
 
Example 51
Project: Leanplum-Android-SDK   File: Util.java   Source Code and License 5 votes vote down vote up
/**
 * Set install time from package manager and update time from apk file modification time.
 */
private static void setInstallTime(Map<String, Object> params, PackageManager packageManager,
    String packageName) {
  try {
    PackageInfo info = packageManager.getPackageInfo(packageName, 0);
    params.put(Params.INSTALL_DATE, "" + (info.firstInstallTime / 1000.0));
  } catch (NameNotFoundException e) {
    Log.w("Failed to find package info: " + e);
  }
}
 
Example 52
Project: LocationProvider   File: CheckPermissionsActivity.java   Source Code and License 5 votes vote down vote up
/**
 * 获取权限集中需要申请权限的列表
 * 
 * @param permissions
 * @return
 * @since 2.5.0
 *
 */
private List<String> findDeniedPermissions(String[] permissions) {
	List<String> needRequestPermissonList = new ArrayList<String>();
	for (String perm : permissions) {
		if (ContextCompat.checkSelfPermission(this,
				perm) != PackageManager.PERMISSION_GRANTED
				|| ActivityCompat.shouldShowRequestPermissionRationale(
						this, perm)) {
			needRequestPermissonList.add(perm);
		} 
	}
	return needRequestPermissonList;
}
 
Example 53
Project: Remindy   File: LocationBasedReminderDetailFragment.java   Source Code and License 5 votes vote down vote up
@Override
@SuppressWarnings({"MissingPermission"})
public void onRequestPermissionsResult(int requestCode,
                                       @NonNull String permissions[],
                                       @NonNull int[] grantResults) {
    switch (requestCode) {
        case PERMISSION_REQUEST_ACCESS_FINE_LOCATION_SHOW_ICON_IN_MAP:
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
                setUpMap();
            //TODO: Else Error message no permissions!
            break;
    }

}
 
Example 54
Project: tensorflow-classifier-android   File: CameraActivity.java   Source Code and License 5 votes vote down vote up
@Override
public void onRequestPermissionsResult(
    final int requestCode, final String[] permissions, final int[] grantResults) {
  if (requestCode == PERMISSIONS_REQUEST) {
    if (grantResults.length > 0
        && grantResults[0] == PackageManager.PERMISSION_GRANTED
        && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
      setFragment();
    } else {
      requestPermission();
    }
  }
}
 
Example 55
Project: FileDownloader-master   File: DownloadLaunchRunnableTest.java   Source Code and License 5 votes vote down vote up
private static void mockContextNoWifiState(Context context) {
    when(context.checkCallingOrSelfPermission(anyString())).thenReturn(PackageManager.PERMISSION_GRANTED);
    final ConnectivityManager connectivityManager = mock(ConnectivityManager.class);
    when(context.getSystemService(Context.CONNECTIVITY_SERVICE)).thenReturn(connectivityManager);

    // not wifi.
    when(connectivityManager.getActiveNetworkInfo()).thenReturn(null);
}
 
Example 56
Project: Calendouer   File: MainActivity.java   Source Code and License 5 votes vote down vote up
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == LOCATION_PERM) {
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            getWeatherBtn.setOnClickListener(null);

            mLocationClient.startLocation();
        } else {
            getWeatherBtn.setText(getString(R.string.need_location_premission));
        }
    }
}
 
Example 57
Project: ucar-weex-core   File: AppUtil.java   Source Code and License 5 votes vote down vote up
/**
 * 返回当前程序版本名
 */
public static String getAppVersionName(Context context) {
    String versionName = "";
    try {
        PackageManager pm = context.getPackageManager();
        PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
        versionName = pi.versionName;
        if (versionName == null || versionName.length() <= 0) {
            return "";
        }
    } catch (Exception e) {
    }
    return versionName;
}
 
Example 58
Project: chromium-for-android-56-debug-video   File: AppBannerInfoBarDelegateAndroid.java   Source Code and License 5 votes vote down vote up
@CalledByNative
private void openWebApk() {
    Context context = ContextUtils.getApplicationContext();
    PackageManager packageManager = getPackageManager(context);

    if (InstallerDelegate.isInstalled(packageManager, mWebApkPackage)) {
        openApp(context, mWebApkPackage);
    }
}
 
Example 59
Project: MKAPP   File: Util.java   Source Code and License 5 votes vote down vote up
public static int getSelfVersionCode(Context context) {
    try {
        PackageInfo pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
        return pInfo.versionCode;
    } catch (PackageManager.NameNotFoundException ex) {
        return -1;
    }
}
 
Example 60
Project: MVP-Android   File: DeviceUtils.java   Source Code and License 5 votes vote down vote up
public static String getDeviceEmailAddress(Activity activity) {
    Pattern emailPattern = Patterns.EMAIL_ADDRESS;
    if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.GET_ACCOUNTS) != PackageManager.PERMISSION_GRANTED) {
        return "";
    }
    Account[] accounts = AccountManager.get(activity).getAccounts();
    for (Account account : accounts) {
        if (emailPattern.matcher(account.name).matches()) {
            return account.name;
        }
    }
    return "";
}