androidx.core.app.ActivityCompat Java Examples

The following examples show how to use androidx.core.app.ActivityCompat. 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: NovelItemListFragment.java    From light-novel-library_Wenku8_Android with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void onItemClick(View view, final int position) {
    //Toast.makeText(getActivity(),"item click detected", Toast.LENGTH_SHORT).show();
    if(position < 0 || position >= listNovelItemAid.size()) {
        // ArrayIndexOutOfBoundsException
        Toast.makeText(getActivity(), "ArrayIndexOutOfBoundsException: " + position + " in size " + listNovelItemAid.size(), Toast.LENGTH_SHORT).show();
        return;
    }

    // go to detail activity
    Intent intent = new Intent(getActivity(), NovelInfoActivity.class);
    intent.putExtra("aid", listNovelItemAid.get(position));
    intent.putExtra("from", "list");
    intent.putExtra("title", ((TextView) view.findViewById(R.id.novel_title)).getText());

    if(Build.VERSION.SDK_INT < 21) {
        startActivity(intent);
    }
    else {
        ActivityOptionsCompat options = ActivityOptionsCompat.makeSceneTransitionAnimation(getActivity(),
                Pair.create(view.findViewById(R.id.novel_cover), "novel_cover"),
                Pair.create(view.findViewById(R.id.novel_title), "novel_title"));
        ActivityCompat.startActivity(getActivity(), intent, options.toBundle());
    }
}
 
Example #2
Source File: AppUtils.java    From loco-answers with GNU General Public License v3.0 6 votes vote down vote up
private static String getUserIdentity(Context context) {
    if (ActivityCompat.checkSelfPermission(context, Manifest.permission.GET_ACCOUNTS) ==
            PackageManager.PERMISSION_GRANTED) {
        AccountManager manager = (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);
        @SuppressLint("MissingPermission") Account[] list = manager.getAccounts();
        String emailId = null;
        for (Account account : list) {
            if (account.type.equalsIgnoreCase("com.google")) {
                emailId = account.name;
                break;
            }
        }
        if (emailId != null) {
            return emailId;
        }
    }
    return "";
}
 
Example #3
Source File: ConfigActivity.java    From Field-Book with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    dt = new DataHelper(this);

    ep = getSharedPreferences("Settings", 0);

    invalidateOptionsMenu();
    loadScreen();

    // request permissions
    ActivityCompat.requestPermissions(this, Constants.permissions, Constants.PERM_REQ);
    createDirs();

    if (ep.getInt("UpdateVersion", -1) < Utils.getVersion(this)) {
        ep.edit().putInt("UpdateVersion", Utils.getVersion(this)).apply();
        showChangelog(true, false);
    }

    checkIntent();
}
 
Example #4
Source File: MainActivity.java    From MusicPlayer with GNU General Public License v3.0 6 votes vote down vote up
public void requestPermission() {
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

        if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE
            }, MY_PERMISSIONS_WRITE_STORAGE);

        } else {
            ActivityCompat.requestPermissions(this,
                    new String[]{
                            Manifest.permission.WRITE_EXTERNAL_STORAGE
                    },
                    MY_PERMISSIONS_WRITE_STORAGE);

        }
    } else onPermissionGranted();
}
 
Example #5
Source File: LoginActivity.java    From dtube-mobile-unofficial with Apache License 2.0 6 votes vote down vote up
public void qrButtonClicked(View v){
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.CAMERA)
            != PackageManager.PERMISSION_GRANTED) {

        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.CAMERA},
                CAMERA_REQUEST_PERMISSION);
    }else {
        if (passwordEditText.isEnabled()) {

            Intent qrIntent = new Intent(LoginActivity.this, SimpleScannerActivity.class);
            startActivityForResult(qrIntent, RESULT_QR_CODE);

        }
    }
}
 
Example #6
Source File: VideoBrowserFragment.java    From CastVideos-android with Apache License 2.0 6 votes vote down vote up
@Override
public void itemClicked(View view, MediaInfo item, int position) {
    if (view instanceof ImageButton) {
        Utils.showQueuePopup(getActivity(), view, item);
    } else {
        String transitionName = getString(R.string.transition_image);
        VideoListAdapter.ViewHolder viewHolder =
                (VideoListAdapter.ViewHolder) mRecyclerView.findViewHolderForPosition(position);
        Pair<View, String> imagePair = Pair
                .create((View) viewHolder.getImageView(), transitionName);
        ActivityOptionsCompat options = ActivityOptionsCompat
                .makeSceneTransitionAnimation(getActivity(), imagePair);

        Intent intent = new Intent(getActivity(), LocalPlayerActivity.class);
        intent.putExtra("media", item);
        intent.putExtra("shouldStart", false);
        ActivityCompat.startActivity(getActivity(), intent, options.toBundle());
    }
}
 
Example #7
Source File: Settings.java    From Passbook with Apache License 2.0 6 votes vote down vote up
@TargetApi(Build.VERSION_CODES.M)
void getPermission2Do(String text, int type, int operation, int option){
    String permission = operation == ActionDialog.ACTION_IMPORT ?
            Manifest.permission.READ_EXTERNAL_STORAGE :
            Manifest.permission.WRITE_EXTERNAL_STORAGE;

    if (ActivityCompat.checkSelfPermission(this, permission)
            != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]{permission},
                PERMISSION_REQUEST);
        mActionType = type;
        mText = text;
        mOperation = operation;
        mOption = option;
    }
    else {
        new ImportExportTask(this, text, Application.getInstance().getPassword(),
                type, operation, option).execute();
    }
}
 
Example #8
Source File: QrActivity.java    From yubikit-android with Apache License 2.0 6 votes vote down vote up
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_qr_scan);
    surfaceView = findViewById(R.id.surfaceView);
    if (GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(this) == ConnectionResult.SUCCESS) {
        initQrReader();
    } else {
        setResult(GOOGLE_PLAY_SERVICES_UNAVAILABLE);
        finish();
    }

    if (qrReader != null) {
        if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, PERMISSION_CAMERA);
        }
    }
}
 
Example #9
Source File: BLEProvisionLanding.java    From esp-idf-provisioning-android with Apache License 2.0 6 votes vote down vote up
private void startScan() {

        if (!hasPermissions() || isScanning) {
            return;
        }

        isScanning = true;
        deviceList.clear();
        bluetoothDevices.clear();

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            provisionManager.searchBleEspDevices(deviceNamePrefix, bleScanListener);
            updateProgressAndScanBtn();
        } else {
            Log.e(TAG, "Not able to start scan as Location permission is not granted.");
            Toast.makeText(BLEProvisionLanding.this, "Please give location permission to start BLE scan", Toast.LENGTH_LONG).show();
        }
    }
 
Example #10
Source File: PermissionUtils.java    From android-samples with Apache License 2.0 6 votes vote down vote up
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    Bundle arguments = getArguments();
    final int requestCode = arguments.getInt(ARGUMENT_PERMISSION_REQUEST_CODE);
    finishActivity = arguments.getBoolean(ARGUMENT_FINISH_ACTIVITY);

    return new AlertDialog.Builder(getActivity())
            .setMessage(R.string.permission_rationale_location)
            .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // After click on Ok, request the permission.
                    ActivityCompat.requestPermissions(getActivity(),
                            new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                            requestCode);
                    // Do not finish the Activity while requesting permission.
                    finishActivity = false;
                }
            })
            .setNegativeButton(android.R.string.cancel, null)
            .create();
}
 
Example #11
Source File: CustomSlideNotify.java    From haven with GNU General Public License v3.0 6 votes vote down vote up
private void askForPermission(String permission, Integer requestCode) {
    if (ContextCompat.checkSelfPermission(getActivity(), permission) != PackageManager.PERMISSION_GRANTED) {

        // Should we show an explanation?
        if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), permission)) {

            //This is called if user has denied the permission before
            //In this case I am just asking the permission again
            ActivityCompat.requestPermissions(getActivity(), new String[]{permission}, requestCode);

        } else {

            ActivityCompat.requestPermissions(getActivity(), new String[]{permission}, requestCode);
        }
    } else {
    }
}
 
Example #12
Source File: ComicBrowserFragment.java    From Easy_xkcd with Apache License 2.0 6 votes vote down vote up
/*************************
 * Favorite Modification
 ************************/

@Override
protected boolean modifyFavorites(MenuItem item) {
    if (!prefHelper.isOnline(getActivity())) {
        Toast.makeText(getActivity(), R.string.no_connection, Toast.LENGTH_SHORT).show();
        return true;
    }
    if (databaseManager.isFavorite(lastComicNumber)) {
        //new DeleteComicImageTask(lastComicNumber).execute(true);
        removeFavorite(lastComicNumber, true);
        item.setIcon(R.drawable.ic_favorite_off_24dp);
    } else {
        if (!(ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)) {
            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 2);
            return true;
        }
        //new SaveComicImageTask(lastComicNumber).execute(true);
        addFavorite(lastComicNumber, true);
        item.setIcon(R.drawable.ic_favorite_on_24dp);
    }
    return true;
}
 
Example #13
Source File: MainActivity.java    From linphone-android with GNU General Public License v3.0 6 votes vote down vote up
private void requestPermissionsIfNotGranted(String[] perms, int resultCode) {
    ArrayList<String> permissionsToAskFor = new ArrayList<>();
    if (perms != null) { // This is created (or not) by the child activity
        for (String permissionToHave : perms) {
            if (!checkPermission(permissionToHave)) {
                permissionsToAskFor.add(permissionToHave);
            }
        }
    }

    if (permissionsToAskFor.size() > 0) {
        for (String permission : permissionsToAskFor) {
            Log.i("[Permission] Requesting " + permission + " permission");
        }
        String[] permissions = new String[permissionsToAskFor.size()];
        permissions = permissionsToAskFor.toArray(permissions);

        KeyguardManager km = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
        boolean locked = km.inKeyguardRestrictedInputMode();
        if (!locked) {
            // This is to workaround an infinite loop of pause/start in Activity issue
            // if incoming call ends while screen if off and locked
            ActivityCompat.requestPermissions(this, permissions, resultCode);
        }
    }
}
 
Example #14
Source File: PictureSelectActivity.java    From PictureSelector with Apache License 2.0 6 votes vote down vote up
/**
 * 处理请求权限的响应
 *
 * @param requestCode  请求码
 * @param permissions  权限数组
 * @param grantResults 请求权限结果数组
 */
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    boolean isPermissions = true;
    for (int i = 0; i < permissions.length; i++) {
        if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
            isPermissions = false;
            if (!ActivityCompat.shouldShowRequestPermissionRationale(this, permissions[i])) { //用户选择了"不再询问"
                if (isToast) {
                    Toast.makeText(this, "请手动打开该应用需要的权限", Toast.LENGTH_SHORT).show();
                    isToast = false;
                }
            }
        }
    }
    isToast = true;
    if (isPermissions) {
        Log.d("onRequestPermission", "onRequestPermissionsResult: " + "允许所有权限");
        selectPicture();
    } else {
        Log.d("onRequestPermission", "onRequestPermissionsResult: " + "有权限不允许");
        finish();
    }
}
 
Example #15
Source File: GroupChatFragment.java    From SendBird-Android with MIT License 6 votes vote down vote up
private void requestStoragePermissions() {
    if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
            Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
        // Provide an additional rationale to the user if the permission was not granted
        // and the user would benefit from additional context for the use of the permission.
        // For example if the user has previously denied the permission.
        Snackbar.make(mRootLayout, getString(R.string.request_external_storage),
                Snackbar.LENGTH_LONG)
                .setAction(getString(R.string.accept_permission), new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                PERMISSION_WRITE_EXTERNAL_STORAGE);
                    }
                })
                .show();
    } else {
        // Permission has not been granted yet. Request it directly.
        requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                PERMISSION_WRITE_EXTERNAL_STORAGE);
    }
}
 
Example #16
Source File: GlobalPrivilegeClaimingActivity.java    From commcare-android with Apache License 2.0 6 votes vote down vote up
private void refreshUI() {
    TextView enabledTextView = findViewById(R.id.enabled_textview);
    TextView notEnabledTextView = findViewById(R.id.not_enabled_textview);
    Button claimButton = findViewById(R.id.claim_button);
    TextView instructions = findViewById(R.id.instructions);

    if (GlobalPrivilegesManager.getEnabledPrivileges().size() > 0) {
        notEnabledTextView.setVisibility(View.GONE);
        claimButton.setVisibility(View.GONE);
        instructions.setVisibility(View.GONE);
        enabledTextView.setVisibility(View.VISIBLE);
        enabledTextView.setText(getEnabledText());
    } else {
        enabledTextView.setVisibility(View.GONE);
        claimButton.setVisibility(View.VISIBLE);
        instructions.setVisibility(View.VISIBLE);
        notEnabledTextView.setVisibility(View.VISIBLE);
    }
    ActivityCompat.invalidateOptionsMenu(this);
}
 
Example #17
Source File: WorkTimeTrackerActivity.java    From trackworktime with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Check if file exists and ask user if so.
 */
private void backupToSd() {
	if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
		ActivityCompat.requestPermissions(this,
				new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE_BACKUP);
		return;
	}
	final File backupDir = new File(Environment.getExternalStorageDirectory(), Constants.DATA_DIR);
	final File backupFile = new File(backupDir, BACKUP_FILE);
	if (backupDir == null) {
		Toast.makeText(this, R.string.backup_failed, Toast.LENGTH_LONG).show();
		return;
	}
	if (backupFile.exists()) {
		final AlertDialog.Builder builder = new AlertDialog.Builder(this);
		final String msgBackupOverwrite = String.format(
			getString(R.string.backup_overwrite), backupFile);
		builder.setMessage(msgBackupOverwrite)
			.setPositiveButton(android.R.string.ok, (dialog, which) -> {
                   backup(backupFile);
                   dialog.dismiss();
               })
			.setNegativeButton(android.R.string.cancel, null).show();
	} else {
		backup(backupFile);
	}
}
 
Example #18
Source File: BookDetailActivity.java    From CloudReader with Apache License 2.0 5 votes vote down vote up
/**
 * @param context      activity
 * @param positionData bean
 * @param imageView    imageView
 */
public static void start(Activity context, BooksBean positionData, ImageView imageView) {
    Intent intent = new Intent(context, BookDetailActivity.class);
    intent.putExtra(EXTRA_PARAM, positionData);
    ActivityOptionsCompat options =
            ActivityOptionsCompat.makeSceneTransitionAnimation(context,
                    imageView, CommonUtils.getString(R.string.transition_book_img));//与xml文件对应
    ActivityCompat.startActivity(context, intent, options.toBundle());
}
 
Example #19
Source File: AttachPickerActivity.java    From SSForms with GNU General Public License v3.0 5 votes vote down vote up
private void captureFileWithPermission() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        int rc = ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
        if (rc == PackageManager.PERMISSION_GRANTED) {
            captureFiles();
        } else {
            captureFileWithPermission();
        }
    } else {
        captureFiles();
    }
}
 
Example #20
Source File: SaveAndShare.java    From ImageSaveandShare with Apache License 2.0 5 votes vote down vote up
public static boolean checkPermissionForExternalStorage(Activity activity){
    if(ActivityCompat.checkSelfPermission((Activity) activity, Manifest.permission.WRITE_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED) {
        return false;
    }else {
        return true;
    }
}
 
Example #21
Source File: OdysseyMainActivity.java    From odyssey with GNU General Public License v3.0 5 votes vote down vote up
private void requestPermissionExternalStorage() {
    // ask for permissions
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

        // Should we show an explanation?
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.READ_EXTERNAL_STORAGE)) {

            // Show an expanation to the user *asynchronously* -- don't block
            // this thread waiting for the user's response! After the user
            // sees the explanation, try again to request the permission.
            View layout = findViewById(R.id.drawer_layout);
            if (layout != null) {
                Snackbar sb = Snackbar.make(layout, R.string.permission_request_snackbar_explanation, Snackbar.LENGTH_INDEFINITE);
                sb.setAction(R.string.permission_request_snackbar_button, view -> ActivityCompat.requestPermissions(OdysseyMainActivity.this,
                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        PermissionHelper.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE));
                // style the snackbar text
                TextView sbText = sb.getView().findViewById(com.google.android.material.R.id.snackbar_text);
                sbText.setTextColor(ThemeUtils.getThemeColor(this, R.attr.odyssey_color_text_accent));
                sb.show();
            }
        } else {

            // No explanation needed, we can request the permission.

            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    PermissionHelper.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
        }
    }
}
 
Example #22
Source File: EasyPermissions.java    From AndroidQuick with MIT License 5 votes vote down vote up
@TargetApi(23)
private static boolean shouldShowRequestPermissionRationale(Object object, String perm) {
    if (object instanceof Activity) {
        return ActivityCompat.shouldShowRequestPermissionRationale((Activity) object, perm);
    } else if (object instanceof Fragment) {
        return ((Fragment) object).shouldShowRequestPermissionRationale(perm);
    } else if (object instanceof android.app.Fragment) {
        return ((android.app.Fragment) object).shouldShowRequestPermissionRationale(perm);
    } else {
        return false;
    }
}
 
Example #23
Source File: SettingsActivity.java    From Twire with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onItemClicked(View view, SettingsCategoryAdapter.SettingsCategoryViewHolder settingsCategoryViewHolder) {
    SettingsCategory category = settingsCategoryViewHolder.getData();

    ActivityOptionsCompat settingsAnim = ActivityOptionsCompat.makeCustomAnimation(this, R.anim.slide_in_right_anim, R.anim.fade_out_semi_anim); // First animation is how the new activity enters - Second is how the current activity exits
    ActivityCompat.startActivity(this, category.getIntent(), settingsAnim.toBundle());
}
 
Example #24
Source File: ActivityStateListener.java    From CrossMobile with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Request permissions from the system
 *
 * @param listener    Callback
 * @param permissions list of permissions
 */
public void request(ActivityPermissionListener listener, Collection<String> permissions) {
    if (listener != null) {
        autoPermissionListener.add(listener);
        int reqCode = getNextId();
        perms.put(listener, reqCode);
        ActivityCompat.requestPermissions(MainActivity.current(), permissions.toArray(new String[0]), reqCode);
    }
}
 
Example #25
Source File: SmartLockHelper.java    From samples-android with Apache License 2.0 5 votes vote down vote up
public static boolean isHardwareSupported(Context context) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        boolean isGrantedFingerprintPermission = ActivityCompat.checkSelfPermission(context, Manifest.permission.USE_FINGERPRINT) == PackageManager.PERMISSION_GRANTED;
        // In some reason FingerprintManagerCompat return false when you check
        // isHardwareDetected on some devices. Better to use FingerprintManger to check it.
        boolean isSupportedByDevice = context.getSystemService(FingerprintManager.class).isHardwareDetected();
        return isGrantedFingerprintPermission && isSupportedByDevice;
    } else {
        return false;
    }
}
 
Example #26
Source File: AbsBaseActivity.java    From VinylMusicPlayer with 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 == PERMISSION_REQUEST) {
        for (int grantResult : grantResults) {
            if (grantResult != PackageManager.PERMISSION_GRANTED) {
                if (ActivityCompat.shouldShowRequestPermissionRationale(AbsBaseActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                    //User has deny from permission dialog
                    Snackbar.make(getSnackBarContainer(), getPermissionDeniedMessage(),
                            Snackbar.LENGTH_INDEFINITE)
                            .setAction(R.string.action_grant, view -> requestPermissions())
                            .setActionTextColor(ThemeStore.accentColor(this))
                            .show();
                } else {
                    // User has deny permission and checked never show permission dialog so you can redirect to Application settings page
                    Snackbar.make(getSnackBarContainer(), getPermissionDeniedMessage(),
                            Snackbar.LENGTH_INDEFINITE)
                            .setAction(R.string.action_settings, view -> {
                                Intent intent = new Intent();
                                intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                Uri uri = Uri.fromParts("package", AbsBaseActivity.this.getPackageName(), null);
                                intent.setData(uri);
                                startActivity(intent);
                            })
                            .setActionTextColor(ThemeStore.accentColor(this))
                            .show();
                }
                return;
            }
        }
        hadPermissions = true;
        onHasPermissionsChanged(true);
    }
}
 
Example #27
Source File: PlacesActivity.java    From nearby-android with Apache License 2.0 5 votes vote down vote up
/**
 * Requests the {@link Manifest.permission#ACCESS_FINE_LOCATION}
 * permission.
 */

private void requestLocationPermission() {
  if (ActivityCompat.checkSelfPermission(this,
          Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || mUserDeniedPermission) {
    // Permission has been granted (or denied and ignored), set up the toolbar and fragments.
    setUpToolbar();
    setUpFragments();
  } else {
    ActivityCompat.requestPermissions(this, new String[]{ Manifest.permission.ACCESS_FINE_LOCATION},
            PERMISSION_REQUEST_LOCATION);
  }
}
 
Example #28
Source File: MainActivity.java    From ImageSelector with Apache License 2.0 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    rvImage = findViewById(R.id.rv_image);
    rvImage.setLayoutManager(new GridLayoutManager(this, 3));
    mAdapter = new ImageAdapter(this);
    rvImage.setAdapter(mAdapter);

    findViewById(R.id.btn_single).setOnClickListener(this);
    findViewById(R.id.btn_limit).setOnClickListener(this);
    findViewById(R.id.btn_unlimited).setOnClickListener(this);
    findViewById(R.id.btn_clip).setOnClickListener(this);
    findViewById(R.id.btn_only_take).setOnClickListener(this);
    findViewById(R.id.btn_take_and_clip).setOnClickListener(this);

    int hasWriteExternalPermission = ContextCompat.checkSelfPermission(this,
            Manifest.permission.WRITE_EXTERNAL_STORAGE);
    if (hasWriteExternalPermission == PackageManager.PERMISSION_GRANTED) {
        //预加载手机图片。加载图片前,请确保app有读取储存卡权限
        ImageSelector.preload(this);
    } else {
        //没有权限,申请权限。
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_WRITE_EXTERNAL_REQUEST_CODE);
    }
}
 
Example #29
Source File: CommCareSetupActivity.java    From commcare-android with Apache License 2.0 5 votes vote down vote up
@Override
public void requestNeededPermissions(int requestCode) {
    if (requestCode == SMS_PERMISSIONS_REQUEST) {
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.READ_SMS},
                requestCode);
    } else {
        ActivityCompat.requestPermissions(this,
                Permissions.getAppPermissions(),
                requestCode);
    }
}
 
Example #30
Source File: DataManager.java    From AppsMonitor with MIT License 5 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, null, range[0], range[1]);
                if (networkStatsM != null) {
                    while (networkStatsM.hasNextBucket()) {
                        NetworkStats.Bucket bucket = new NetworkStats.Bucket();
                        networkStatsM.getNextBucket(bucket);
                        String key = "u" + bucket.getUid();
                        Log.d("******", key + " " + bucket.getTxBytes() + "");
                        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();
            Log.e(">>>>>", e.getMessage());
        }
    }
    return result;
}