Why doesn't this code work on android 6 marshmallow Api 23?

mauriciosouza picture mauriciosouza · Sep 28, 2015 · Viewed 11.2k times · Source

Why doesn't this code work on android 6 marshmallow Api 23? It does not throw an Exception but the code within callStateListener does not work.

TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
PhoneStateListener callStateListener = new PhoneStateListener() {
    @Override
    public void onCallStateChanged(int state, String incomingNumber) {
        //if(logAtive) Log.i(LOG_TAG,incomingNumber + " " + state);
        if(state==TelephonyManager.CALL_STATE_RINGING){
            Toast.makeText(getApplicationContext(),"Hey, receive your call. Phone is ringing.",
                    Toast.LENGTH_LONG).show();
        }
        if(state==TelephonyManager.CALL_STATE_OFFHOOK){
            Toast.makeText(getApplicationContext(),"You are in a call. ",
                    Toast.LENGTH_LONG).show();
        }
        if(state==TelephonyManager.CALL_STATE_IDLE){
            Toast.makeText(getApplicationContext(),"You are in idle state… ",
                    Toast.LENGTH_LONG).show();
        }
    }
};

telephonyManager.listen(callStateListener, PhoneStateListener.LISTEN_CALL_STATE);

Permissions:

<uses-feature android:name="android.hardware.telephony" android:required="true" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.MODIFY_PHONE_STATE" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.PROCESS_INCOMING_CALLS" />

It works perfectly in Android 5.1.1 but not in 6 (API Level 23)

Answer

TonyB picture TonyB · Oct 31, 2015

I just ran into this and figured it out. It's because you are targeting android SDK 23. If you change your manifest file to target API 22 then it will start working even when installed and running on a Marshmallow device.

If you still want to target API 23 then you have to use the new runtime permission API to request permission usage first, otherwise it will simply be denied.

https://developer.android.com/training/permissions/requesting.html