Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to take read_phone_state permission in android 6.0

I got below error

java.lang.SecurityException: getDeviceId: Neither user 10250 nor current process has android.permission.READ_PHONE_STATE.

AndroidRuntime: FATAL EXCEPTION: main
Process: com.infyco.kp.new_tab, PID: 23149
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.infyco.kp.new_tab/com.infyco.kp.new_tab.Splashscreen}: java.lang.SecurityException: getDeviceId: Neither user 10257 nor current process has android.permission.READ_PHONE_STATE.

Here is my code:

  ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, 1);

it works for the SEND_SMS permission , but not with the READ_PHONE_STATE permission

  ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.SEND_SMS}, 1);
like image 330
Praviin Zurrunge Avatar asked Nov 19 '22 05:11

Praviin Zurrunge


1 Answers

You are requesting the permission with the same request code (here: 1).

Try this:

public  boolean isPermissionGranted() {
    if (Build.VERSION.SDK_INT >= 23) {
        if (checkSelfPermission(android.Manifest.permission.READ_PHONE_STATE)
                == PackageManager.PERMISSION_GRANTED) {
            Log.v("TAG","Permission is granted");
            return true;
        } else {

            Log.v("TAG","Permission is revoked");
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, 2);
            return false;
        }
    }
    else { //permission is automatically granted on sdk<23 upon installation
        Log.v("TAG","Permission is granted");
        return true;
    }
}


 @Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {

        case 2: {

            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(getApplicationContext(), "Permission granted", Toast.LENGTH_SHORT).show();
                //do your specific task after read phone state granted
            } else {
                Toast.makeText(getApplicationContext(), "Permission denied", Toast.LENGTH_SHORT).show();
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request
    }
 }

Use it like this:

if(isPermissionGranted()){
    //do your specific task after read phone state
}

Also, in your manifest, add:

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
like image 154
rafsanahmad007 Avatar answered Dec 19 '22 13:12

rafsanahmad007