Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android - close app if user not granting WRITE_EXTERNAL_STORAGE permission

in android 6 or above when user open app first time ask him for some permission if he dont allow then exit app

some must required permission for my app is read and write to external storage, how to achieve this

i tried this

if (Build.VERSION.SDK_INT >= 23) {
                if (ContextCompat.checkSelfPermission(LoginActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(LoginActivity.this, android.Manifest.permission.READ_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(LoginActivity.this,
                            new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_EXTERNAL_STORAGE},
                            1);
                } else {
                    //do something
                }
            } else {
                    //do something
            }
like image 498
dharmx Avatar asked Jan 24 '26 16:01

dharmx


1 Answers

You need to read the results onRequestPermissionsResult() and if the user refused the permissions, call context.finish() or context.finishAffinity(). Something like... Edit: Take a look on the docs to learn how to handle the permissions: Android 6 Permissions

    @Override 
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
        switch (requestCode) {
            case MAIN_PERMISSIONS:
                if (grantResults.length > 0) {
                    // Validate the permissions result
                    if (permissionsOk) {
                        // All good
                    } else {
                        // Close your app
                        closeNow();
                    }
                }
                break;
        }
    }

    private void closeNow() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            finishAffinity();
        } else {
            finish();
        }
    }

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!