Sobes.tech
Junior — Middle

How to implement making incoming and outgoing calls on the Android platform?

sobes.tech AI

Answer from AI

Standard platform APIs are used for implementing incoming and outgoing calls on Android.

Outgoing calls: To make an outgoing call, you can use an Intent with the action Intent.ACTION_CALL or Intent.ACTION_DIAL.

  • ACTION_DIAL opens the phone app with the number but does not automatically make the call.
  • ACTION_CALL immediately initiates the call but requires the CALL_PHONE permission.

Example code for an outgoing call:

Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:+1234567890"));
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
    context.startActivity(callIntent);
} else {
    // Request permission from the user
}

Incoming calls: To handle incoming calls, you need to use TelephonyManager and PhoneStateListener or BroadcastReceiver to listen to call state changes.

Example using PhoneStateListener:

TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
PhoneStateListener callStateListener = new PhoneStateListener() {
    @Override
    public void onCallStateChanged(int state, String phoneNumber) {
        switch (state) {
            case TelephonyManager.CALL_STATE_RINGING:
                // Incoming call
                break;
            case TelephonyManager.CALL_STATE_OFFHOOK:
                // Call is active
                break;
            case TelephonyManager.CALL_STATE_IDLE:
                // Call ended or no calls
                break;
        }
    }
};
telephonyManager.listen(callStateListener, PhoneStateListener.LISTEN_CALL_STATE);

Additional permissions such as READ_PHONE_STATE may be required for full call handling.

Note that starting from Android 6.0 (API 23), you need to request permissions from the user at runtime.