There are a few things you can do:
First of all, you can listen for changes in the call state using a PhoneStateListener
.
You can register the listener in the TelephonyManager:
PhoneStateListener phoneStateListener = new PhoneStateListener() {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
if (state == TelephonyManager.CALL_STATE_RINGING) {
//Incoming call: Pause music
} else if(state == TelephonyManager.CALL_STATE_IDLE) {
//Not in call: Play music
} else if(state == TelephonyManager.CALL_STATE_OFFHOOK) {
//A call is dialing, active or on hold
}
super.onCallStateChanged(state, incomingNumber);
}
};
TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
if(mgr != null) {
mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}
Remember to unregister the listener when it's no longer needed using the PhoneStateListener.LISTEN_NONE
:
TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
if(mgr != null) {
mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);
}
For more information read the documentation.
Another thing you can do is listening for the broadcast android.intent.action.PHONE_STATE
. It will contain the extra TelephonyManager.EXTRA_STATE
which will give you information about the call. Take a look at the documentation here.
Please note that you'll need the android.permission.READ_PHONE_STATE
-permission in both cases.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…