I want to play sound on any incoming or outgoing calls and stop when call disconnected. I've tried some codes and now I'm getting when my phone is ringing and answered and disconnected. But sound is not playing properly. I put the code for playing sound on CALL_STATE_RINGING. But it is playing when my call disconnected.
Here is the code which I've tried...
This is my Broadcast receiver class.
public class PhoneStateBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.listen(new CustomPhoneStateListener(context), PhoneStateListener.LISTEN_CALL_STATE);
}
}
And this is the class where I am getting STATE..
public class CustomPhoneStateListener extends PhoneStateListener {
//private static final String TAG = "PhoneStateChanged";
private Context context; //Context to make Toast if required
private static MediaPlayer mPlayer;
private boolean isRinging = false;
CustomPhoneStateListener(Context context) {
super();
this.context = context;
}
@Override
public void onCallStateChanged(int state, String incomingNumber) {
super.onCallStateChanged(state, incomingNumber);
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
//when Idle i.e no call
if (isRinging) {
mPlayer.stop();
Toast.makeText(context, "Phone state Idle", Toast.LENGTH_LONG).show();
}
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
//when Off hook i.e in call
//Make intent and start your service here
Toast.makeText(context, "Phone state Off hook", Toast.LENGTH_LONG).show();
break;
case TelephonyManager.CALL_STATE_RINGING:
//when Ringing
if (!isRinging) {
mPlayer = MediaPlayer.create(context, R.raw.ring_ring);
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mPlayer.start();
Toast.makeText(context, "Phone state Ringing", Toast.LENGTH_LONG).show();
/* mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);*/
isRinging = true;
}
break;
default:
break;
}
}
}