Search code examples
javaandroidpermissionstelephonymanager

Possible to use TelephonyManager without permission READ_PHONE_STATE


I made a music player app and for pausing the song when the phone gets called i use this code.

But this needs the permission READ_PHONE_STATE which maybe scares off some users, so i would like to know if it's possible to achieve the same thing another way without asking for this permission?

My code

private void callStateListener(){
        //incomingCallPause: checkbox value if user wants to pause when there is an incoming call.
        incomingCallPause = storageUtil.loadSwitchOnCall();
        mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        mPhoneStateListener = new PhoneStateListener(){
            @Override
            public void onCallStateChanged(int state, String incomingNumber) {
                switch (state) {
                    case TelephonyManager.CALL_STATE_OFFHOOK:
                        if (mediaPlayer != null){
                            pauseSong();
                        }
                        break;
                    case TelephonyManager.CALL_STATE_RINGING:
                        if (incomingCallPause && mediaPlayer != null) {
                            pauseSong();
                            NotificationBuilder(PlaybackStatus.PAUSED);
                            incomingCall = true;
                        }
                        break;
                    case TelephonyManager.CALL_STATE_IDLE:
                        if (mediaPlayer != null) {
                            if (incomingCall) {
                                incomingCall = false;
                                NotificationBuilder(PlaybackStatus.PLAYING);
                                if (!mediaPlayer.isPlaying()){
                                    mediaPlayer.start();
                                }
                            }
                        }
                        break;
                }
                super.onCallStateChanged(state, incomingNumber);
            }
        };

Solution

  • As per Android official document you need to define manifest permission to use TelephonyManager.

    Requires Manifest.permission.READ_PHONE_STATE

    Referral link: https://developer.android.com/reference/android/telephony/TelephonyManager