我正在创建一个应用,用户可以通过我的应用调用他最喜欢的联系人。 通话开始时,扬声器开启。 为了使用此Intent进行调用。
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel: "+contactnum.get(0)));
startActivity(callIntent);
当有一个外出呼叫时,会有一个Intent启动一个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);
}
}
}
正如您所见,onReceive在需要时打开扬声器。
问题在于扬声器并不总是打开,而是仅在用户进行的第一次通话时打开。奇怪的是,如果用户在应用程序运行时拨打电话但未通过我的应用程序正常工作,则扬声器每次都会打开。 什么可能导致这样的事情?
还有别的东西,即使应用程序没有运行它就像启动接收器的意图一直在工作,所以当我拨打电话或接听电话时它会转动扬声器,尽管应用程序甚至没有运行。
答案 0 :(得分:1)
好的,我让它工作了。
我已经更改了Intent Filter,因此它只有一个动作
<action android:name="android.intent.action.PHONE_STATE" />
当TelephonyManager处于摘机状态时,我设置了audioManager模式
audioManager.setMode(AudioManager.MODE_IN_CALL);
在设置扬声器之前,它正常工作。
更新
当应用程序没有运行时,它仍在工作,但后来我发现了这个问题My Broadcast receiver get execute even if my application is not working 我意识到我应该在我的主要活动中注册接收器,并在活动的onDestroy中取消注册。