Java Code Examples for android.content.pm.PackageManager

The following examples show how to use android.content.pm.PackageManager. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: android_9.0.0_r45   Source File: WebViewUpdateService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * This is called from DeveloperSettings when the user changes WebView provider.
 */
@Override // Binder call
public String changeProviderAndSetting(String newProvider) {
    if (getContext().checkCallingPermission(
                android.Manifest.permission.WRITE_SECURE_SETTINGS)
            != PackageManager.PERMISSION_GRANTED) {
        String msg = "Permission Denial: changeProviderAndSetting() from pid="
                + Binder.getCallingPid()
                + ", uid=" + Binder.getCallingUid()
                + " requires " + android.Manifest.permission.WRITE_SECURE_SETTINGS;
        Slog.w(TAG, msg);
        throw new SecurityException(msg);
    }

    long callingId = Binder.clearCallingIdentity();
    try {
        return WebViewUpdateService.this.mImpl.changeProviderAndSetting(
                newProvider);
    } finally {
        Binder.restoreCallingIdentity(callingId);
    }
}
 
Example 2
Source Project: StudentAttendanceCheck   Source File: CheckInActivity.java    License: MIT 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 12345: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted, yay! Do the
                // contacts-related task you need to do.
                Toast.makeText(this, "permission is granted", Toast.LENGTH_SHORT).show();
                updateLocation();
                addEvents();

            } else {

                // permission denied, boo! Disable the
                // functionality that depends on this permission.
                Toast.makeText(this, "permission is denied", Toast.LENGTH_SHORT).show();
            }
            return;
        }

    }
}
 
Example 3
Source Project: OsmGo   Source File: Geolocation.java    License: MIT License 6 votes vote down vote up
@Override
protected void handleRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
  super.handleRequestPermissionsResult(requestCode, permissions, grantResults);

  PluginCall savedCall = getSavedCall();
  if (savedCall == null) {
    return;
  }

  for(int result : grantResults) {
    if (result == PackageManager.PERMISSION_DENIED) {
      savedCall.error("User denied location permission");
      return;
    }
  }

  if (savedCall.getMethodName().equals("getCurrentPosition")) {
    sendLocation(savedCall);
  } else if (savedCall.getMethodName().equals("watchPosition")) {
    startWatch(savedCall);
  } else {
    savedCall.resolve();
    savedCall.release(bridge);
  }
}
 
Example 4
Source Project: reader   Source File: CordovaWebViewClient.java    License: MIT License 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 5
private void addGeofence(GeofencingRequest geofencingRequest,
                         PendingIntent geofencePendingIntent) {
    if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager
            .PERMISSION_GRANTED) {
        return;
    }

    LocationServices.GeofencingApi.addGeofences(
            googleApiClient,
            geofencingRequest,
            geofencePendingIntent
    ).setResultCallback(new ResultCallback<Status>() {
        @Override
        public void onResult(@NonNull Status status) {
            switch (status.getStatusCode()) {
                case CommonStatusCodes.SUCCESS:
                    StatusMessageHandler.showInfoMessage(context, R.string.geofence_enabled, Snackbar.LENGTH_SHORT);
            }

            Log.d(GeofenceApiHandler.class, status.toString());
        }
    });
}
 
Example 6
Source Project: FirefoxReality   Source File: PermissionDelegate.java    License: Mozilla Public License 2.0 6 votes vote down vote up
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    if (requestCode != PERMISSION_REQUEST_CODE || mCallback == null) {
        return;
    }

    boolean granted = true;
    for (int result: grantResults) {
        if (result != PackageManager.PERMISSION_GRANTED) {
            granted = false;
            break;
        }
    }

    if (granted) {
        mCallback.grant();
    } else {
        mCallback.reject();
    }
}
 
Example 7
Source Project: imsdk-android   Source File: ImageGridActivity.java    License: MIT License 6 votes vote down vote up
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == REQUEST_PERMISSION_STORAGE) {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            new ImageDataSource(this, null, this);
        } else {
            showToast("权限被禁止,无法选择本地图片");
        }
    } else if (requestCode == REQUEST_PERMISSION_CAMERA) {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            imagePicker.takePicture(this, ImagePicker.REQUEST_CODE_TAKE);
        } else {
            showToast("权限被禁止,无法打开相机");
        }
    }
}
 
Example 8
Source Project: MVVMArms   Source File: ManifestArmsParser.java    License: Apache License 2.0 6 votes vote down vote up
public List<ConfigArms> parse() {
    List<ConfigArms> armses = 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))) {
                    Log.d("Arms ---> ",
                            String.format("Find ConfigArms in [%s]", key));
                    armses.add(parseModule(key));
                }
            }
        }
    } catch (PackageManager.NameNotFoundException e) {
        throw new RuntimeException("Unable to find metadata to parse ConfigArms", e);
    }

    return armses;
}
 
Example 9
public static void scan(final Activity activity, final boolean provisioning) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M || ContextCompat.checkSelfPermission(activity, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
        final Intent intent = new Intent(activity, UriHandlerActivity.class);
        intent.setAction(UriHandlerActivity.ACTION_SCAN_QR_CODE);
        if (provisioning) {
            intent.putExtra(EXTRA_ALLOW_PROVISIONING, true);
        }
        intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
        activity.startActivity(intent);
    } else {
        activity.requestPermissions(
                new String[]{Manifest.permission.CAMERA},
                provisioning ? REQUEST_CAMERA_PERMISSIONS_TO_SCAN_AND_PROVISION : REQUEST_CAMERA_PERMISSIONS_TO_SCAN
        );
    }
}
 
Example 10
Source Project: Watch-Me-Build-a-Finance-Startup   Source File: LoginActivity.java    License: MIT License 6 votes vote down vote up
private boolean mayRequestContacts() {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
        return true;
    }
    if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
        return true;
    }
    if (shouldShowRequestPermissionRationale(READ_CONTACTS)) {
        Snackbar.make(mEmailView, R.string.permission_rationale, Snackbar.LENGTH_INDEFINITE)
                .setAction(android.R.string.ok, new View.OnClickListener() {
                    @Override
                    @TargetApi(Build.VERSION_CODES.M)
                    public void onClick(View v) {
                        requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
                    }
                });
    } else {
        requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
    }
    return false;
}
 
Example 11
Source Project: ti.goosh   Source File: BadgeUtils.java    License: MIT License 6 votes vote down vote up
private static String getLauncherClassName(Context context) {
    PackageManager pm = context.getPackageManager();

    Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_LAUNCHER);

    List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, 0);
    for (ResolveInfo resolveInfo : resolveInfos) {
        String pkgName = resolveInfo.activityInfo.applicationInfo.packageName;
        if (pkgName.equalsIgnoreCase(context.getPackageName())) {
            String className = resolveInfo.activityInfo.name;
            return className;
        }
    }
    return null;
}
 
Example 12
Source Project: candybar-library   Source File: LocaleHelper.java    License: Apache License 2.0 6 votes vote down vote up
@Nullable
public static String getOtherAppLocaleName(@NonNull Context context, @NonNull Locale locale, @NonNull String packageName) {
    try {
        PackageManager packageManager = context.getPackageManager();
        ApplicationInfo info = packageManager.getApplicationInfo(packageName, PackageManager.GET_META_DATA);

        Resources res = packageManager.getResourcesForApplication(packageName);
        Context otherAppContext = context.createPackageContext(packageName, Context.CONTEXT_IGNORE_SECURITY);
        Configuration configuration = new Configuration();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            configuration = res.getConfiguration();
            configuration.setLocale(locale);
            return otherAppContext.createConfigurationContext(configuration).getString(info.labelRes);
        }

        configuration.locale = locale;
        res.updateConfiguration(configuration, context.getResources().getDisplayMetrics());
        return res.getString(info.labelRes);
    } catch (Exception e) {
        LogUtil.e(Log.getStackTraceString(e));
    }
    return null;
}
 
Example 13
Source Project: a2cardboard   Source File: SystemWebViewClient.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 14
private void initViews() {

        ivEsp = findViewById(R.id.iv_esp);
        btnAddDevice = findViewById(R.id.btn_provision_device);
        btnAddDevice.findViewById(R.id.iv_arrow).setVisibility(View.GONE);
        btnAddDevice.setOnClickListener(addDeviceBtnClickListener);

        TextView tvAppVersion = findViewById(R.id.tv_app_version);

        String version = "";
        try {
            PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
            version = pInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        String appVersion = getString(R.string.app_version) + " - v" + version;
        tvAppVersion.setText(appVersion);
    }
 
Example 15
Source Project: fdroidclient   Source File: Utils.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * If app has an iconUrl we feed that to UIL, otherwise we ask the PackageManager which will
 * return the app's icon directly when the app is installed.
 * We fall back to the placeholder icon otherwise.
 */
public static void setIconFromRepoOrPM(@NonNull App app, ImageView iv, Context context) {
    if (app.getIconUrl(iv.getContext()) == null) {
        try {
            iv.setImageDrawable(context.getPackageManager().getApplicationIcon(app.packageName));
        } catch (PackageManager.NameNotFoundException e) {
            DisplayImageOptions options = Utils.getRepoAppDisplayImageOptions();
            iv.setImageDrawable(options.shouldShowImageForEmptyUri()
                    ? options.getImageForEmptyUri(FDroidApp.getInstance().getResources())
                    : null);
        }
    } else {
        ImageLoader.getInstance().displayImage(
                app.getIconUrl(iv.getContext()), iv, Utils.getRepoAppDisplayImageOptions());
    }
}
 
Example 16
Source Project: tenor-android-core   Source File: StringConstant.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Get string from given package with given resource name
 *
 * @param context      given context
 * @param packageName  the package name
 * @param resourceName the resource name
 * @return the string that the resource represents
 */
@NonNull
public static String getString(@NonNull final Context context,
                               @NonNull final String packageName,
                               @NonNull final String resourceName) {

    PackageManager pm = context.getPackageManager();

    try {
        //I want to use the clear_activities string in Package com.android.settings
        Resources res = pm.getResourcesForApplication(packageName);
        int resourceId = res.getIdentifier(packageName + ":string/" + resourceName, null, null);
        if (resourceId != 0) {
            return pm.getText(packageName, resourceId, null).toString();
        }
    } catch (Exception ignored) {
    }
    return EMPTY;
}
 
Example 17
Source Project: CapturePacket   Source File: MainActivity.java    License: MIT License 6 votes vote down vote up
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == REQUEST_STORAGE) {
        for (int i = 0; i < permissions.length; i++) {
            if (Manifest.permission.WRITE_EXTERNAL_STORAGE.equals(permissions[i])) {
                if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                    bindCaptureService();
                } else {
                    Snackbar snackbar = Snackbar.make(getWindow().getDecorView(), "需要允许读写SD卡的权限!", Snackbar.LENGTH_INDEFINITE);
                    snackbar.setAction("去设置", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                            intent.setData(Uri.parse("package:"+getPackageName()));
                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                            finish();
                        }
                    });
                    snackbar.show();
                }
            }
        }
    }
}
 
Example 18
Source Project: youqu_master   Source File: ImgSelActivity.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_img_sel);
    Constant.imageList.clear();
    config = Constant.config;

    if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED) {
        //申请权限
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                STORAGE_REQUEST_CODE);
    } else {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.fmImageList, ImgSelFragment.instance(config), null)
                .commit();
    }

    initView();
    if (!FileUtils.isSdCardAvailable()) {
        Toast.makeText(this, "SD卡不可用", Toast.LENGTH_SHORT).show();
    }
}
 
Example 19
@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    if (grantResults.length > 0) {
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            //Do the stuff that requires permission...
            tvfileName.setText(R.string.choose_file);
        } else if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                //Show permission explanation dialog...
            } else {
                tvfileName.setText(R.string.permission_required);
                changeBackgroundColor(uploadToServer, R.color.backgroundColor, R.color.errorColor);
                changeStatusBarColor(R.color.errorColor);
                //Never ask again selected, or device policy prohibits the app from having that permission.
                //So, disable that feature, or fall back to another situation...
            }
        }
    }
}
 
Example 20
Source Project: AndroidComponentPlugin   Source File: ContextImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public int checkPermission(String permission, int pid, int uid) {
    if (permission == null) {
        throw new IllegalArgumentException("permission is null");
    }

    final IActivityManager am = ActivityManager.getService();
    if (am == null) {
        // Well this is super awkward; we somehow don't have an active
        // ActivityManager instance. If we're testing a root or system
        // UID, then they totally have whatever permission this is.
        final int appId = UserHandle.getAppId(uid);
        if (appId == Process.ROOT_UID || appId == Process.SYSTEM_UID) {
            Slog.w(TAG, "Missing ActivityManager; assuming " + uid + " holds " + permission);
            return PackageManager.PERMISSION_GRANTED;
        }
    }

    try {
        return am.checkPermission(permission, pid, uid);
    } catch (RemoteException e) {
        throw e.rethrowFromSystemServer();
    }
}
 
Example 21
Source Project: weex   Source File: IndexActivity.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean onOptionsItemSelected(MenuItem item) {
  int id = item.getItemId();
  if (id == R.id.action_refresh) {
    if(!TextUtils.equals(CURRENT_IP,DEFAULT_IP)){
      createWeexInstance();
      return true;
    }
  } else if (id == R.id.action_scan) {
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
      if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
        Toast.makeText(this, "please give me the permission", Toast.LENGTH_SHORT).show();
      } else {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, CAMARA_PERMISSION_REQUEST_CODE);
      }
    } else {
      startActivity(new Intent(this, CaptureActivity.class));
    }
    return true;
  }
  return super.onOptionsItemSelected(item);
}
 
Example 22
Source Project: 365browser   Source File: BeamController.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * If the device has NFC, construct a BeamCallback and pass it to Android.
 *
 * @param activity Activity that is sending out beam messages.
 * @param provider Provider that returns the URL that should be shared.
 */
public static void registerForBeam(final Activity activity, final BeamProvider provider) {
    final NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(activity);
    if (nfcAdapter == null) return;
    if (ApiCompatibilityUtils.checkPermission(
            activity, Manifest.permission.NFC, Process.myPid(), Process.myUid())
            == PackageManager.PERMISSION_DENIED) {
        return;
    }
    try {
        final BeamCallback beamCallback = new BeamCallback(activity, provider);
        nfcAdapter.setNdefPushMessageCallback(beamCallback, activity);
        nfcAdapter.setOnNdefPushCompleteCallback(beamCallback, activity);
    } catch (IllegalStateException e) {
        Log.w("BeamController", "NFC registration failure. Can't retry, giving up.");
    }
}
 
Example 23
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_mqttsettingscodereader);

    mPreview = (CameraSourcePreview) findViewById(R.id.preview);
    mGraphicOverlay = (GraphicOverlay<BarcodeGraphic>) findViewById(R.id.graphicOverlay);

    // Check for the camera permission before accessing the camera.  If the
    // permission is not granted yet, request permission.
    int rc = ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
    if (rc == PackageManager.PERMISSION_GRANTED) {
        createCameraSource(kAutoFocus, kUseFlash);
    } else {
        requestCameraPermission();
    }

    //gestureDetector = new GestureDetector(this, new CaptureGestureListener());
    scaleGestureDetector = new ScaleGestureDetector(this, new ScaleListener());
}
 
Example 24
Source Project: BeMusic   Source File: CrashHandler.java    License: Apache License 2.0 5 votes vote down vote up
public static String getAppVersion (Context context) {
    try {
        PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
        return info.versionName;
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
    return "";
}
 
Example 25
Source Project: LauncherTV   Source File: ApplicationFragment.java    License: Apache License 2.0 5 votes vote down vote up
private void updateApplications() {
	PackageManager pm = getActivity().getPackageManager();
	SharedPreferences prefs = getActivity().getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE);

	for (int y = 0; y < mGridY; y++) {
		for (int x = 0; x < mGridX; x++) {
			ApplicationView app = mApplications[y][x];
			setApplication(pm, app, prefs.getString(app.getPreferenceKey(), null));
		}
	}
}
 
Example 26
public static boolean hasDeviceFingerprintSupport(Context context) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        FingerprintManager fingerprintManager = (FingerprintManager) context.getSystemService(Context.FINGERPRINT_SERVICE);
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED) {
            return false;
        }
        return fingerprintManager.isHardwareDetected() && fingerprintManager.hasEnrolledFingerprints();
    } else {
        return false;
    }
}
 
Example 27
@SuppressWarnings("SameParameterValue")
private boolean permissionCheck(String permissionToCheck){
	if(permissionToCheck == null){
		throw new IllegalArgumentException("permission is null");
	}
	return PackageManager.PERMISSION_GRANTED == getBaseContext().checkPermission(permissionToCheck, android.os.Process.myPid(), android.os.Process.myUid());
}
 
Example 28
Source Project: retrowatch   Source File: GmailContract.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Check if the installed Gmail app supports querying for label information.
 *
 * @param c an application Context
 * @return true if it's safe to make label API queries
 */
public static boolean canReadLabels(Context c) {
    boolean supported = false;

    try {
        final PackageInfo info = c.getPackageManager().getPackageInfo(PACKAGE,
                PackageManager.GET_PROVIDERS | PackageManager.GET_PERMISSIONS);
        boolean allowRead = false;
        if (info.permissions != null) {
            for (int i = 0, len = info.permissions.length; i < len; i++) {
                final PermissionInfo perm = info.permissions[i];
                if (PERMISSION.equals(perm.name)
                        && perm.protectionLevel < PermissionInfo.PROTECTION_SIGNATURE) {
                    allowRead = true;
                    break;
                }
            }
        }
        if (allowRead && info.providers != null) {
            for (int i = 0, len = info.providers.length; i < len; i++) {
                final ProviderInfo provider = info.providers[i];
                if (AUTHORITY.equals(provider.authority) &&
                        TextUtils.equals(PERMISSION, provider.readPermission)) {
                    supported = true;
                }
            }
        }
    } catch (NameNotFoundException e) {
        // Gmail app not found
    }
    return supported;
}
 
Example 29
Source Project: adt-leanback-support   Source File: ShareCompat.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get the icon of the calling application as a Drawable if data
 * about the calling package is available.
 *
 * <p><em>Note:</em> This data may have been provided voluntarily by the calling
 * application. As such it should not be trusted for accuracy in the context of
 * security or verification.</p>
 *
 * @return The calling application's icon or null if unknown
 */
public Drawable getCallingApplicationIcon() {
    if (mCallingPackage == null) return null;

    PackageManager pm = mActivity.getPackageManager();
    try {
        return pm.getApplicationIcon(mCallingPackage);
    } catch (NameNotFoundException e) {
        Log.e(TAG, "Could not retrieve icon for calling application", e);
    }
    return null;
}
 
Example 30
Source Project: FireFiles   Source File: PermissionUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Check that all given permissions have been granted by verifying that each entry in the
 * given array is of the value {@link PackageManager#PERMISSION_GRANTED}.
 *
 * @see Activity#onRequestPermissionsResult(int, String[], int[])
 */
public static boolean verifyPermissions(int[] grantResults) {
    // At least one result must be checked.
    if(grantResults.length < 1){
        return false;
    }

    // Verify that each required permission has been granted, otherwise return false.
    for (int result : grantResults) {
        if (result != PackageManager.PERMISSION_GRANTED) {
            return false;
        }
    }
    return true;
}