I'm making an app that the user can call his favorite contacts through my app. When the call starts the speaker turns on. In order to make a call im using this Intent.
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel: "+contactnum.get(0)));
startActivity(callIntent);
And when there's an out going call there's an Intent that starts a BroadcastReceiver
<receiver android:name=".MyBroadcast">
<intent-filter>
<action android:name="android.intent.action.NEW_OUTGOING_CALL" />
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
public class MyBroadcast extends BroadcastReceiver{
@Override
public void onReceive(final Context context, Intent intent){
// TODO Auto-generated method stub
PhoneStateListener phoneStateListener = new PhoneStateListener(){
@Override
public void onCallStateChanged(int state, String incomingNumber){
if(state == TelephonyManager.CALL_STATE_RINGING){
}
else if(state == TelephonyManager.CALL_STATE_IDLE){
AudioManager audioManager = (AudioManager) context
.getSystemService(Context.AUDIO_SERVICE);
audioManager.setSpeakerphoneOn(false);
}
else if(state == TelephonyManager.CALL_STATE_OFFHOOK){
AudioManager audioManager = (AudioManager) context
.getSystemService(Context.AUDIO_SERVICE);
audioManager.setSpeakerphoneOn(true);
}
super.onCallStateChanged(state, incomingNumber);
}
};
TelephonyManager mgr = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
if(mgr != null){
mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}
}
}
As you can see the onReceive is turning the speaker on when needed.
The problem is that the speaker doesn't always turn on, but only on the first call that the user makes. The weird part is that if the user makes a call while the app is running but not through my app it works properly, the speaker turns on every time. What can cause such a thing?
And something else, even when the app is not running it's like that the intent that starts the receiver keeps working, so when I make calls or get calls it turns the speaker although the app is not even running.