Detecting outgoing call and call hangup event in android

僤鯓⒐⒋嵵緔 提交于 2019-11-27 07:13:59
vendor

You should create a BroadcastReceiver:

public class CallReciever extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
                TelephonyManager.EXTRA_STATE_RINGING)) {

                // Phone number 
                String incomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);

                // Ringing state
                // This code will execute when the phone has an incoming call
        } else if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
                TelephonyManager.EXTRA_STATE_IDLE)
                || intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
                        TelephonyManager.EXTRA_STATE_OFFHOOK)) {

            // This code will execute when the call is answered or disconnected
        }

    }
}

You should register you application to listen to these intents in the manifest:

<receiver android:name=".CallReciever" >
            <intent-filter>
                <action android:name="android.intent.action.PHONE_STATE" />
            </intent-filter>
 </receiver>
Marian Klühspies

There is a simpler solution using only TelephonyManager and PhoneStateListener.You don´t even have to register a BroadcastReceiver.

public class MyPhoneStateListener extends PhoneStateListener {

    @Override
    public void onCallStateChanged(int state, String incomingNumber) {
        switch (state) {
            //Hangup
            case TelephonyManager.CALL_STATE_IDLE:
                break;
            //Outgoing
            case TelephonyManager.CALL_STATE_OFFHOOK:
                break;
            //Incoming
            case TelephonyManager.CALL_STATE_RINGING:
                break;
        }
    }
}

And to register it:

public static void registerListener(Context context) {
    ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)).listen(new MyPhoneStateListener(),
            PhoneStateListener.LISTEN_CALL_STATE);
}

You need to create a receiver for the following intent actions:

  1. Outgoing call - ACTION_NEW_OUTGOING_CALL
  2. Call hangup - ACTION_PHONE_STATE_CHANGED
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!