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.
Example 1
Project: android_9.0.0_r45   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
Project: StudentAttendanceCheck   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
Project: OsmGo   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
Project: reader   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
Project: PowerSwitch_Android   File: GeofenceApiHandler.java    License: GNU General Public License v3.0 6 votes vote down vote up
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
Project: FirefoxReality   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
Project: imsdk-android   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
Project: MVVMArms   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
Project: Conversations   File: UriHandlerActivity.java    License: GNU General Public License v3.0 6 votes vote down vote up
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
Project: Watch-Me-Build-a-Finance-Startup   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
Project: ti.goosh   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
Project: candybar-library   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
Project: a2cardboard   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
Project: esp-idf-provisioning-android   File: EspMainActivity.java    License: Apache License 2.0 6 votes vote down vote up
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
Project: fdroidclient   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
Project: tenor-android-core   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
Project: CapturePacket   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
Project: youqu_master   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
Project: Beginner-Level-Android-Studio-Apps   File: MainActivity.java    License: GNU General Public License v3.0 6 votes vote down vote up
@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
Project: AndroidComponentPlugin   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
Project: weex   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
Project: 365browser   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
Project: Bluefruit_LE_Connect_Android   File: MqttUartSettingsCodeReaderActivity.java    License: MIT License 6 votes vote down vote up
@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
Project: BeMusic   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
Project: LauncherTV   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
Project: Lunary-Ethereum-Wallet   File: AppLockUtils.java    License: GNU General Public License v3.0 5 votes vote down vote up
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
Project: sdl_java_suite   File: SdlRouterService.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@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
Project: retrowatch   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
Project: adt-leanback-support   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
Project: FireFiles   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;
}
 
Example 31
Project: lyft-android-sdk   File: DeepLink.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Attempts to deeplink to the Lyft app. If Lyft is not installed on the device,
 * the Play Store will be launched to the Lyft app details page.
 *
 * @param context Required for deeplinking.
 * @param deepLinkParams Used to construct the deeplink {@link Uri}.
 * @return true if Lyft app launched successfully.
 */
public static boolean launchLyftApp(Context context, DeepLinkParams deepLinkParams) {
    if (!isLyftInstalled(context)) {
        String url = "https://www.lyft.com/signup/SDKSIGNUP?clientId=" + deepLinkParams.getClientId()
                + "&sdkName=android&sdkVersion=" + SDK_VERSION;
        Uri webpage = Uri.parse(url);
        Intent intent = new Intent(Intent.ACTION_VIEW, webpage);
        if (intent.resolveActivity(context.getPackageManager()) != null) {
            context.startActivity(intent);
        }
        return false;
    }

    PackageManager packageManager = context.getPackageManager();

    Intent i = packageManager.getLaunchIntentForPackage(LYFT_PACKAGE_NAME);
    if (i == null) {
        return false;
    }

    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    String deepLinkString = createDeepLinkString(deepLinkParams);
    i.setData(Uri.parse(deepLinkString));
    context.startActivity(i);

    return true;
}
 
Example 32
Project: YalpStore   File: PermissionsComparator.java    License: GNU General Public License v2.0 5 votes vote down vote up
private Set<String> getOldPermissions(String packageName) {
    PackageManager pm = context.getPackageManager();
    try {
        PackageInfo pi = pm.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS);
        return new HashSet<>(Arrays.asList(
            null == pi.requestedPermissions
                ? new String[0]
                : pi.requestedPermissions
        ));
    } catch (PackageManager.NameNotFoundException e) {
        Log.e(getClass().getSimpleName(), "Package " + packageName + " doesn't seem to be installed");
    }
    return null;
}
 
Example 33
Project: ApkTrack   File: ReflectionUtil.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static List<String> getSourcePaths(Context context) throws PackageManager.NameNotFoundException, IOException {
    ApplicationInfo applicationInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(), 0);
    File sourceApk = new File(applicationInfo.sourceDir);
    File dexDir = new File(applicationInfo.dataDir, SECONDARY_FOLDER_NAME);

    List<String> sourcePaths = new ArrayList<String>();
    //default apk path
    sourcePaths.add(applicationInfo.sourceDir);

    String extractedFilePrefix = sourceApk.getName() + EXTRACTED_NAME_EXT;

    //get the dex number
    int totalDexNumber = getMultiDexPreferences(context).getInt(KEY_DEX_NUMBER, 1);

    //get other dexes
    for (int i = 2; i <= totalDexNumber; i++) {
        String fileName = extractedFilePrefix + i + EXTRACTED_SUFFIX;
        File extractedFile = new File(dexDir, fileName);
        if (extractedFile.isFile()) {
            sourcePaths.add(extractedFile.getAbsolutePath());
        } else {
            throw new IOException("Missing extracted secondary dex file '" +
                    extractedFile.getPath() + "'");
        }
    }

    return sourcePaths;
}
 
Example 34
Project: loco-answers   File: ProfileActivity.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    switch (requestCode) {
        case storageReadPermission: {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

            } else {
                finish();
            }
        }
    }
}
 
Example 35
Project: zom-android-matrix   File: ImageViewActivity.java    License: Apache License 2.0 5 votes vote down vote up
private boolean checkPermissions ()
{
    int permissionCheck = ContextCompat.checkSelfPermission(this,
            Manifest.permission.WRITE_EXTERNAL_STORAGE);


    if (permissionCheck ==PackageManager.PERMISSION_DENIED) {
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                1);
        return false;
    }

    return true;
}
 
Example 36
Project: MultiType-FilePicker   File: LocalFileUncaughtExceptionHandler.java    License: Apache License 2.0 5 votes vote down vote up
private int getVersionCode(){
    PackageManager packageManager = mContext.getPackageManager();
    PackageInfo packInfo = null;
    int version = 0;
    try {
        packInfo = packageManager.getPackageInfo(mContext.getPackageName(),0);
        version = packInfo.versionCode;
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }

    return version;
}
 
Example 37
Project: Android-RobotoTextView   File: RobotoTextAppearanceSpan.java    License: Apache License 2.0 5 votes vote down vote up
private int themeResId(Context context) {
    try {
        String packageName = context.getPackageName();
        PackageInfo packageInfo = context.getPackageManager()
                .getPackageInfo(packageName, PackageManager.GET_META_DATA);
        return packageInfo.applicationInfo.theme;
    } catch (PackageManager.NameNotFoundException e) {
        Log.w(getClass().getSimpleName(), e);
    }
    return -1;
}
 
Example 38
Project: IoT-Firstep   File: MainActivity.java    License: GNU General Public License v3.0 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 == SMS_REQ_CODE) {
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(this, "获取权限成功", Toast.LENGTH_LONG).show();
            doRegisterReceiver();
        } else {
            Toast.makeText(this, "没有权限接受短信", Toast.LENGTH_LONG).show();
        }
    }
}
 
Example 39
Project: AppFloater   File: FloatService.java    License: GNU General Public License v2.0 5 votes vote down vote up
private Drawable getPackageIcon(String appPackage) throws PackageManager.NameNotFoundException {
    Drawable draw = null;
    try {
        draw = packageManager.getApplicationIcon(appPackage);
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
    return draw;
}
 
Example 40
Project: TurboLauncher   File: LauncherModel.java    License: Apache License 2.0 5 votes vote down vote up
public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context) {
	PackageManager packageManager = context.getPackageManager();
	final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>();
	widgetsAndShortcuts.addAll(AppWidgetManager.getInstance(context)
			.getInstalledProviders());
	Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
	widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(
			shortcutsIntent, 0));
	Collections.sort(widgetsAndShortcuts,
			new LauncherModel.WidgetAndShortcutNameComparator(
					packageManager));
	return widgetsAndShortcuts;
}