Home » Android » java – android-RuntimePermissions sample code not working

java – android-RuntimePermissions sample code not working

Posted by: admin June 15, 2020 Leave a comment

Questions:

https://github.com/googlesamples/android-RuntimePermissions/

After cloning I imported the code in Android Studio 2.3.3 But app folder is not showing in Project>Android and also other android specific option like Android Monitor is absent. Build Project not working.

How I imported is as followed.
File > New > Import Project > android-RuntimePermissions > build.gradleand then clicked ok

I have added Kotlin plugin to android studio as the project have Kotlin module.

How to&Answers:

There’s an invalid settings.gradle file, which only tries to import Application module (which yet is not valid gradle module, as long as it does not have its own build.gradle file).

Inside root folder settings.gradle file put following line:

include ':kotlinApp'

Now instead of importing build.gradle import kotlinApp folder:

File -> Open… -> android-RuntimePermissions-master/kotlinApp

Answer:

Don’t open the root folder of the repo try opening (File -> Open) the kotlin folder of the app

enter image description here

If it prompts to download the kotlin library click it to download

Once it it done, wait for the gradle sync to complete, after which the app module will be visible and you’ll be able to build and deploy the app

enter image description here

Kudos!

Answer:

https://github.com/googlesamples/android-RuntimePermissions/

is the root directory of one android project which has Application as module.
Open root android project as show as below

Click ok button to open root project

Click ok button to open root project

But the issue is Application module doesn’t have build.gradle file. So it won’t load as a module.
Create one build.gradle file inside Application folder and paste the below code

    apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.2"
    defaultConfig {
        applicationId "com.example.android.system.runtimepermissions"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile "com.android.support:support-v13:26.0.0"
    compile "com.android.support:appcompat-v7:26.0.0"
    compile 'com.android.support:design:26.0.0'
    testCompile 'junit:junit:4.12'
}
repositories {
    mavenCentral()
}

There are some error inside styles.xml about resource not found. Please correct it and use.

https://github.com/googlesamples/android-RuntimePermissions/tree/master/kotlinApp

kotlinApp is another folder which have no connection with above project. It is another android project which have app as module
Open kotlinApp android project as show as below :

Open kotlinApp project

Click ok button to open kotlinApp android project

In short, this repository consist of two android project. One is root folder and another is kotlinApp folder.

Answer:

Only if you want to check runtime permission then simply run this code

if (ActivityCompat.checkSelfPermission(SplashActivity.this,
            Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED &&
            ActivityCompat.checkSelfPermission(SplashActivity.this,
                    Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions((SplashActivity.this),
                new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE_ASK_PERMISSIONS);
    }else{
    //ToDo write your code here which will work once you granted The permission.
   Log.e(TAG,"Permission already granted"); 
    }

and for on permission granted result

  @NonNull
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    switch (requestCode) {
        case REQUEST_CODE_ASK_PERMISSIONS:
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission Granted
//                    databaseHelper = new DatabaseHelper(getContext());
//                    getCategory();
                loadDB();
            } else if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) &&
                    ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE) &&
                    ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.CAMERA)) {
                // Permission Denied
                AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
                builder.setTitle("Need Storage Permission");
                builder.setMessage("This app needs storage permission");
                builder.setPositiveButton("Grant", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();


                        ActivityCompat.requestPermissions(getActivity(),
                                new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
                                        Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, REQUEST_CODE_ASK_PERMISSIONS);


                    }
                });
                builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });
                builder.show();
            }
            break;
        default:
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}

Answer:

Call this in onCreate method
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

        checkForPermission();
    }

Place this code outside OnCreate and then modify this code according to your needs. This is working and tested code

@RequiresApi(api = Build.VERSION_CODES.KITKAT)

public boolean checkForPermission() {

    List<String> permissionsNeeded = new ArrayList<String>();

    final List<String> permissionsList = new ArrayList<String>();


    addPermission(permissionsList, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    addPermission(permissionsList,Manifest.permission.READ_PHONE_STATE);
    addPermission(permissionsList,Manifest.permission.CALL_PHONE);
    addPermission(permissionsList,Manifest.permission.RECORD_AUDIO);
    addPermission(permissionsList,Manifest.permission.PROCESS_OUTGOING_CALLS);
    addPermission(permissionsList,Manifest.permission.CAPTURE_AUDIO_OUTPUT);
    addPermission(permissionsList,Manifest.permission.READ_SMS);



    if (permissionsList.size() > 0) {
        if (permissionsNeeded.size() > 0) {
            // Need Rationale
            ActivityCompat.requestPermissions(MainActivity.this, permissionsList.toArray(new String[permissionsList.size()]),
                    REQUEST_PERMISSION);

            return true;
        }
        ActivityCompat.requestPermissions(MainActivity.this, permissionsList.toArray(new String[permissionsList.size()]),
                REQUEST_PERMISSION);
        return false;
    }

    return true;

}
private boolean addPermission(List<String> permissionsList, String permission) {
    if (ContextCompat.checkSelfPermission(MainActivity.this, permission) != PackageManager.PERMISSION_GRANTED) {
        permissionsList.add(permission);
        // Check for Rationale Option
        if (!ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, permission))
            return false;
    }
    return true;
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    switch (requestCode) {
        case REQUEST_PERMISSION: {
            Map<String, Integer> perms = new HashMap<String, Integer>();
            // Initial
            perms.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);
            perms.put(Manifest.permission.READ_EXTERNAL_STORAGE,PackageManager.PERMISSION_GRANTED);
            perms.put(Manifest.permission.READ_SMS,PackageManager.PERMISSION_GRANTED);

            // Fill with results
            for (int i = 0; i < permissions.length; i++)
                perms.put(permissions[i], grantResults[i]);
            if (perms.get(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED && perms.get(Manifest.permission.READ_EXTERNAL_STORAGE)==PackageManager.PERMISSION_GRANTED && perms.get(Manifest.permission.READ_SMS)==PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(MainActivity.this, "You can enjoy all features of app now", Toast.LENGTH_SHORT).show();
            } else {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    checkForPermission();
                }
            }

        }
        break;
        default:
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}