简体   繁体   中英

How to detect TelephonyManager outgoing call connected State on Android

We have 3 States according to this documentation Fields

Below code shows Ringing State how we can detect via TelephonyManager outgoing call connected State on Android

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test_layout);
   }

   public class myPhoneStateChangeListener extends PhoneStateListener {
       @Override
       public void onCallStateChanged(int state, String incomingNumber) {
           super.onCallStateChanged(state, incomingNumber);
           if (state == TelephonyManager.CALL_STATE_RINGING) {
               String phoneNumber =   incomingNumber;
           }
       }
   }
}

Thanks in advance. if you need anything from me please ask in the comment section.

Well, It's very easy just add the code below inside your myPhoneStateChangeListener 's onCallStateChanged method

if(TelephonyManager.CALL_STATE_OFFHOOK==state) {
    // phone picked up
}
if(TelephonyManager.CALL_STATE_IDLE==state) {
    // either phone hanged up or ringing stopped
}

or you can refer to this solution

Alternatively, You can also use BroadcastReciever to check the state change.

public class PhoneStateReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle bundle = intent.getExtras();

        assert bundle != null;
        String phoneState = bundle.getString(TelephonyManager.EXTRA_STATE);
        Log.d("phoneCallReceiver", phoneState);

        if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_IDLE)) {
            Log.d("phoneCallReceiver", "phone hanged up");
        }
        if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
            Log.d("phoneCallReceiver", "phone picked up");
        }
        if (phoneState.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
            Log.d("phoneCallReceiver", "phone ringing");
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM