Java Code Examples for android.app.Activity#checkSelfPermission()

The following examples show how to use android.app.Activity#checkSelfPermission() . 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 check out the related API usage on the sidebar.
Example 1
Source File: Downloader.java    From Xposed-SoundCloudDownloader with GNU General Public License v3.0 6 votes vote down vote up
private static boolean validatePermissions(final Activity activity) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (activity.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED && activity.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            return true;
        } else {
            AlertDialog.Builder alert = new AlertDialog.Builder(activity);
            alert.setTitle("Permission Error");
            alert.setMessage("Grant permissions in the next dialog and retry download.");
            alert.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    dialog.dismiss();
                    ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
                }
            });
            alert.show();
            return false;
        }
    } else {
        XposedBridge.log("[SoundCloud Downloader] SDK < 23, permissions must be granted manually?");
        return true;
    }
}
 
Example 2
Source File: ContactsActivity.java    From TelePlus-Android with GNU General Public License v2.0 6 votes vote down vote up
@TargetApi(Build.VERSION_CODES.M)
private void askForPermissons(boolean alert) {
    Activity activity = getParentActivity();
    if (activity == null || !UserConfig.getInstance(currentAccount).syncContacts || activity.checkSelfPermission(Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
        return;
    }
    if (alert && askAboutContacts) {
        AlertDialog.Builder builder = AlertsCreator.createContactsPermissionDialog(activity, new MessagesStorage.IntCallback() {
            @Override
            public void run(int param) {
                askAboutContacts = param != 0;
                MessagesController.getGlobalNotificationsSettings().edit().putBoolean("askAboutContacts", askAboutContacts).commit();
                askForPermissons(false);
            }
        });
        showDialog(builder.create());
        return;
    }
    ArrayList<String> permissons = new ArrayList<>();
    permissons.add(Manifest.permission.READ_CONTACTS);
    permissons.add(Manifest.permission.WRITE_CONTACTS);
    permissons.add(Manifest.permission.GET_ACCOUNTS);
    String[] items = permissons.toArray(new String[permissons.size()]);
    activity.requestPermissions(items, 1);
}
 
Example 3
Source File: Shared.java    From Xposed-SoundCloudDownloader with GNU General Public License v3.0 6 votes vote down vote up
public static boolean validatePermissions(final Activity activity) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (activity.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            return true;
        } else {
            AlertDialog.Builder alert = new AlertDialog.Builder(activity);
            alert.setTitle("Permission Error");
            alert.setMessage("Grant permissions in the next dialog and retry download.");
            alert.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    dialog.dismiss();
                    ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                }
            });
            alert.show();
            return false;
        }
    } else {
        return true;
    }
}
 
Example 4
Source File: Util.java    From TelePlus-Android with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Checks whether it's necessary to request the {@link permission#READ_EXTERNAL_STORAGE}
 * permission read the specified {@link Uri}s, requesting the permission if necessary.
 *
 * @param activity The host activity for checking and requesting the permission.
 * @param uris {@link Uri}s that may require {@link permission#READ_EXTERNAL_STORAGE} to read.
 * @return Whether a permission request was made.
 */
@TargetApi(23)
public static boolean maybeRequestReadExternalStoragePermission(Activity activity, Uri... uris) {
  if (Util.SDK_INT < 23) {
    return false;
  }
  for (Uri uri : uris) {
    if (Util.isLocalFileUri(uri)) {
      if (activity.checkSelfPermission(permission.READ_EXTERNAL_STORAGE)
          != PackageManager.PERMISSION_GRANTED) {
        activity.requestPermissions(new String[] {permission.READ_EXTERNAL_STORAGE}, 0);
        return true;
      }
      break;
    }
  }
  return false;
}
 
Example 5
Source File: PermissionUtils.java    From TikTok with Apache License 2.0 6 votes vote down vote up
/**
 * 检查某个权限是否被永久拒绝
 *
 * @param activity              Activity对象
 * @param permission            请求的权限
 */
static boolean checkSinglePermissionPermanentDenied(Activity activity, String permission) {

    //安装权限和浮窗权限不算,本身申请方式和危险权限申请方式不同,因为没有永久拒绝的选项,所以这里返回false
    if (permission.equals(RequestPermissions.REQUEST_INSTALL_PACKAGES) || permission.equals(RequestPermissions.SYSTEM_ALERT_WINDOW)) {
        return false;
    }

    //检测8.0的两个新权限
    if (permission.equals(RequestPermissions.ANSWER_PHONE_CALLS) || permission.equals(RequestPermissions.READ_PHONE_NUMBERS)) {

        //检查当前的安卓版本是否符合要求
        if (!isOverOreo()) {
            return false;
        }
    }

    if (PermissionUtils.isOverMarshmallow()) {
        if (activity.checkSelfPermission(permission) == PackageManager.PERMISSION_DENIED  &&
                !activity.shouldShowRequestPermissionRationale(permission)) {
            return true;
        }
    }
    return false;
}
 
Example 6
Source File: PermissionUtils.java    From MNVideoPlayer with GNU General Public License v3.0 6 votes vote down vote up
/**
     * 检查某个权限是否被永久拒绝
     *
     * @param activity              Activity对象
     * @param permission            请求的权限
     */
    static boolean checkSinglePermissionPermanentDenied(Activity activity, String permission) {

//        // 安装权限和浮窗权限不算,本身申请方式和危险权限申请方式不同,因为没有永久拒绝的选项,所以这里返回false
//        if (permission.equals(Permission.REQUEST_INSTALL_PACKAGES) || permission.equals(Permission.SYSTEM_ALERT_WINDOW)) {
//            return false;
//        }

        // 检测8.0的两个新权限
        if (permission.equals(Permission.ANSWER_PHONE_CALLS) || permission.equals(Permission.READ_PHONE_NUMBERS)) {

            // 检查当前的安卓版本是否符合要求
            if (!isOverOreo()) {
                return false;
            }
        }

        if (PermissionUtils.isOverMarshmallow()) {
            if (activity.checkSelfPermission(permission) == PackageManager.PERMISSION_DENIED  &&
                    !activity.shouldShowRequestPermissionRationale(permission)) {
                return true;
            }
        }
        return false;
    }
 
Example 7
Source File: Util.java    From recent-images with MIT License 6 votes vote down vote up
public static void checkPermission(Activity activity, String[] permissions,
                                   OnPermissionCallback permissionsResultCallback) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        boolean req = false;

        for (int i = 0; i < permissions.length; i++) {
            if (activity.checkSelfPermission(permissions[i]) == PackageManager.PERMISSION_DENIED) {
                req = true;
            }
        }
        if (!req)
            permissionsResultCallback.onPermissionGranted();
        else {
            permissionMap.clear();

            permissionStringRes = R.string.pleaseEnablePermission;
            permissionMap.put(PERMISSION_REQUEST_CODE, new Pair<>(new Pair<>(activity,
                    permissionsResultCallback), permissions));

            activity.requestPermissions(permissions, PERMISSION_REQUEST_CODE);

        }
    } else {
        permissionsResultCallback.onPermissionGranted();
    }
}
 
Example 8
Source File: ContactsActivity.java    From Telegram-FOSS with GNU General Public License v2.0 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.M)
private void askForPermissons(boolean alert) {
    Activity activity = getParentActivity();
    if (activity == null || !UserConfig.getInstance(currentAccount).syncContacts || activity.checkSelfPermission(Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
        return;
    }
    if (alert && askAboutContacts) {
        AlertDialog.Builder builder = AlertsCreator.createContactsPermissionDialog(activity, param -> {
            askAboutContacts = param != 0;
            if (param == 0) {
                return;
            }
            askForPermissons(false);
        });
        showDialog(builder.create());
        return;
    }
    ArrayList<String> permissons = new ArrayList<>();
    permissons.add(Manifest.permission.READ_CONTACTS);
    permissons.add(Manifest.permission.WRITE_CONTACTS);
    permissons.add(Manifest.permission.GET_ACCOUNTS);
    String[] items = permissons.toArray(new String[0]);
    try {
        activity.requestPermissions(items, 1);
    } catch (Exception e) {
        FileLog.e(e);
    }
}
 
Example 9
Source File: PermissionUtil.java    From PrayTime-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Returns true if the Activity has access to a given permission.
 * Always returns true on platforms below M.
 *
 * @see Activity#checkSelfPermission(String)
 */
public static boolean hasSelfPermission(Activity activity, String permission) {
    // Below Android M all permissions are granted at install time and are already available.
    if (!isMNC()) {
        return true;
    }
    return activity.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED;
}
 
Example 10
Source File: PermissionUtil.java    From bither-android with Apache License 2.0 5 votes vote down vote up
public static boolean isWriteExternalStoragePermission(Activity activity, int requestCode) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (activity.checkSelfPermission(PERMISSION_WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            activity.requestPermissions(new String[]{PERMISSION_WRITE_EXTERNAL_STORAGE}, requestCode);
            return false;
        }
    }
    return true;
}
 
Example 11
Source File: Permission.java    From evercam-android with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Check if the permission is granted or not on Android M (6.0) or above
 * Always return true for Android versions below 6.0, the permission to be checked
 * has to be defined in AndroidManifest.xml
 */
public static boolean isGranted(Activity activity, String permission) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        return activity.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED;
    }
    return true;
}
 
Example 12
Source File: VoIPHelper.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
public static void startCall(TLRPC.User user, final Activity activity, TLRPC.TL_userFull userFull){
	if(userFull!=null && userFull.phone_calls_private){
		new AlertDialog.Builder(activity)
				.setTitle(LocaleController.getString("VoipFailed", R.string.VoipFailed))
				.setMessage(AndroidUtilities.replaceTags(LocaleController.formatString("CallNotAvailable", R.string.CallNotAvailable,
						ContactsController.formatName(user.first_name, user.last_name))))
				.setPositiveButton(LocaleController.getString("OK", R.string.OK), null)
				.show();
		return;
	}
	if (ConnectionsManager.getInstance(UserConfig.selectedAccount).getConnectionState() != ConnectionsManager.ConnectionStateConnected) {
		boolean isAirplaneMode = Settings.System.getInt(activity.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 0) != 0;
		AlertDialog.Builder bldr = new AlertDialog.Builder(activity)
				.setTitle(isAirplaneMode ? LocaleController.getString("VoipOfflineAirplaneTitle", R.string.VoipOfflineAirplaneTitle) : LocaleController.getString("VoipOfflineTitle", R.string.VoipOfflineTitle))
				.setMessage(isAirplaneMode ? LocaleController.getString("VoipOfflineAirplane", R.string.VoipOfflineAirplane) : LocaleController.getString("VoipOffline", R.string.VoipOffline))
				.setPositiveButton(LocaleController.getString("OK", R.string.OK), null);
		if (isAirplaneMode) {
			final Intent settingsIntent = new Intent(Settings.ACTION_AIRPLANE_MODE_SETTINGS);
			if (settingsIntent.resolveActivity(activity.getPackageManager()) != null) {
				bldr.setNeutralButton(LocaleController.getString("VoipOfflineOpenSettings", R.string.VoipOfflineOpenSettings), new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						activity.startActivity(settingsIntent);
					}
				});
			}
		}
		bldr.show();
		return;
	}
	if (Build.VERSION.SDK_INT >= 23 && activity.checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
		activity.requestPermissions(new String[]{Manifest.permission.RECORD_AUDIO}, 101);
	} else {
		initiateCall(user, activity);
	}
}
 
Example 13
Source File: ContactsActivity.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void onResume() {
    super.onResume();
    if (listViewAdapter != null) {
        listViewAdapter.notifyDataSetChanged();
    }
    if (checkPermission && Build.VERSION.SDK_INT >= 23) {
        Activity activity = getParentActivity();
        if (activity != null) {
            checkPermission = false;
            if (activity.checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
                if (activity.shouldShowRequestPermissionRationale(Manifest.permission.READ_CONTACTS)) {
                    AlertDialog.Builder builder = AlertsCreator.createContactsPermissionDialog(activity, new MessagesStorage.IntCallback() {
                        @Override
                        public void run(int param) {
                            askAboutContacts = param != 0;
                            MessagesController.getGlobalNotificationsSettings().edit().putBoolean("askAboutContacts", askAboutContacts).commit();
                            askForPermissons(false);
                        }
                    });
                    showDialog(permissionDialog = builder.create());
                } else {
                    askForPermissons(true);
                }
            }
        }
    }
}
 
Example 14
Source File: ChatAttachAlertLocationLayout.java    From Telegram-FOSS with GNU General Public License v2.0 5 votes vote down vote up
@Override
void onShow() {
    parentAlert.actionBar.setTitle(LocaleController.getString("ShareLocation", R.string.ShareLocation));
    if (mapView.getParent() == null) {
        mapViewClip.addView(mapView, 0, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, overScrollHeight + AndroidUtilities.dp(10), Gravity.TOP | Gravity.LEFT));
        mapViewClip.addView(overlayView, 1, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, overScrollHeight + AndroidUtilities.dp(10), Gravity.TOP | Gravity.LEFT));
    }
    searchItem.setVisibility(VISIBLE);

    if (mapView != null && mapsInitialized) {
        try {
            mapView.onResume();
        } catch (Throwable e) {
            FileLog.e(e);
        }
    }
    onResumeCalled = true;
    fixLayoutInternal(true);
    if (checkPermission && Build.VERSION.SDK_INT >= 23) {
        Activity activity = getParentActivity();
        if (activity != null) {
            checkPermission = false;
            if (activity.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                activity.requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, 2);
            }
        }
    }
    layoutManager.scrollToPositionWithOffset(0, 0);

    updateClipView();
}
 
Example 15
Source File: CompatibilityImpl.java    From Overchan-Android with GNU General Public License v3.0 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.M)
public static boolean hasAccessStorage(Activity activity) {
    if (activity.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        activity.requestPermissions(new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, 0);
        return false;
    } else {
        return true;
    }
}
 
Example 16
Source File: MainActivity.java    From IPTVFree with Apache License 2.0 5 votes vote down vote up
/**
 * Request permission on android M
 * @param activity Activity
 */
public void requestWriteExternalStoragePermission(Activity activity)
{
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        int hasWriteExternalStoragePermission = activity.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        List<String> permissions = new ArrayList<String>();
        if (hasWriteExternalStoragePermission != PackageManager.PERMISSION_GRANTED) {
            permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }
        if (!permissions.isEmpty()) {
            activity.requestPermissions(permissions.toArray(new String[permissions.size()]), REQUEST_WRITE_EXTERNAL_STORAGE_PERMISSIONS);
        }
    }
}
 
Example 17
Source File: VoIPHelper.java    From Telegram with GNU General Public License v2.0 5 votes vote down vote up
public static void startCall(TLRPC.User user, final Activity activity, TLRPC.UserFull userFull) {
	if (userFull != null && userFull.phone_calls_private) {
		new AlertDialog.Builder(activity)
				.setTitle(LocaleController.getString("VoipFailed", R.string.VoipFailed))
				.setMessage(AndroidUtilities.replaceTags(LocaleController.formatString("CallNotAvailable", R.string.CallNotAvailable,
						ContactsController.formatName(user.first_name, user.last_name))))
				.setPositiveButton(LocaleController.getString("OK", R.string.OK), null)
				.show();
		return;
	}
	if (ConnectionsManager.getInstance(UserConfig.selectedAccount).getConnectionState() != ConnectionsManager.ConnectionStateConnected) {
		boolean isAirplaneMode = Settings.System.getInt(activity.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 0) != 0;
		AlertDialog.Builder bldr = new AlertDialog.Builder(activity)
				.setTitle(isAirplaneMode ? LocaleController.getString("VoipOfflineAirplaneTitle", R.string.VoipOfflineAirplaneTitle) : LocaleController.getString("VoipOfflineTitle", R.string.VoipOfflineTitle))
				.setMessage(isAirplaneMode ? LocaleController.getString("VoipOfflineAirplane", R.string.VoipOfflineAirplane) : LocaleController.getString("VoipOffline", R.string.VoipOffline))
				.setPositiveButton(LocaleController.getString("OK", R.string.OK), null);
		if (isAirplaneMode) {
			final Intent settingsIntent = new Intent(Settings.ACTION_AIRPLANE_MODE_SETTINGS);
			if (settingsIntent.resolveActivity(activity.getPackageManager()) != null) {
				bldr.setNeutralButton(LocaleController.getString("VoipOfflineOpenSettings", R.string.VoipOfflineOpenSettings), (dialog, which) -> activity.startActivity(settingsIntent));
			}
		}
		bldr.show();
		return;
	}
	if (Build.VERSION.SDK_INT >= 23 && activity.checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
		activity.requestPermissions(new String[]{Manifest.permission.RECORD_AUDIO}, 101);
	} else {
		initiateCall(user, activity);
	}
}
 
Example 18
Source File: Helper.java    From xmrwallet with Apache License 2.0 5 votes vote down vote up
static public boolean getWritePermission(Activity context) {
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
        if (context.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_DENIED) {
            Timber.w("Permission denied to WRITE_EXTERNAL_STORAGE - requesting it");
            String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
            context.requestPermissions(permissions, PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
            return false;
        } else {
            return true;
        }
    } else {
        return true;
    }
}
 
Example 19
Source File: CameraActivity.java    From io2015-codelabs with Apache License 2.0 5 votes vote down vote up
static public boolean needPermissions(Activity activity) {
    Log.d(TAG, "needPermissions: ");
    return activity.checkSelfPermission(Manifest.permission.CAMERA)
            != PackageManager.PERMISSION_GRANTED
            || activity.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED;
}
 
Example 20
Source File: Helper.java    From xmrwallet with Apache License 2.0 5 votes vote down vote up
static public boolean getCameraPermission(Activity context) {
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
        if (context.checkSelfPermission(Manifest.permission.CAMERA)
                == PackageManager.PERMISSION_DENIED) {
            Timber.w("Permission denied for CAMERA - requesting it");
            String[] permissions = {Manifest.permission.CAMERA};
            context.requestPermissions(permissions, PERMISSIONS_REQUEST_CAMERA);
            return false;
        } else {
            return true;
        }
    } else {
        return true;
    }
}