我开发了一个收音机应用程序,我需要在拨入/拨出电话时暂停收音机。我已经使用了PhoneStateListener,它在所有Android版本中都运行良好,除了在棒棒糖中。这是我用来处理电话的代码。我已经尝试了setStreamVolume和setStreamMute方法,但两者似乎都不适用于棒棒糖。请一些人帮我这个。
提前致谢。
PhoneStateListener phoneStateListener = new PhoneStateListener() {
@Override
public void onCallStateChanged(int state,
String incomingNumber) {
switch (state) {
case TelephonyManager.CALL_STATE_RINGING: // Incoming
// call:
// Pause
// music
if (Globals.isPlayerRunning) {
curVolume = audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC);
audioManager.setStreamVolume(
AudioManager.STREAM_MUSIC, 0, 0);
audioManager.setStreamMute(
AudioManager.STREAM_MUSIC, true);
isServiceMuteByCall = true;
}
break;
case TelephonyManager.CALL_STATE_IDLE: // Not in
// call:
// Play
// music
if (isServiceMuteByCall) {
isServiceMuteByCall = false;
audioManager.setStreamMute(
AudioManager.STREAM_MUSIC, false);
audioManager.setStreamVolume(
AudioManager.STREAM_MUSIC, curVolume,
AudioManager.FLAG_PLAY_SOUND);
}
break;
case TelephonyManager.CALL_STATE_OFFHOOK:// A call
// is
// dialing,
// active
// or
// on
// hold
if (Globals.isPlayerRunning) {
curVolume = audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC);
audioManager.setStreamMute(
AudioManager.STREAM_MUSIC, true);
audioManager.setStreamVolume(
AudioManager.STREAM_MUSIC, 0, 0);
isServiceMuteByCall = true;
}
break;
}
super.onCallStateChanged(state, incomingNumber);
}
};
if (mgr != null) {
mgr.listen(phoneStateListener,
PhoneStateListener.LISTEN_CALL_STATE);
}
答案 0 :(得分:3)
以上是上述问题的解决方案。这可以使用BroadcastReceiver解决。
创建一个扩展BroadcastReceiver的类,并在onreceive方法中检查下面的电话状态。
public class TelephonyManagerReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (TelephonyManager.ACTION_PHONE_STATE_CHANGED.equals(intent.getAction())) {
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
if (TelephonyManager.EXTRA_STATE_RINGING.equals(state)) {
//stop the player or mute the audio here
} else if (TelephonyManager.EXTRA_STATE_IDLE.equals(state)) {
//start the player or unmute the audio here
} else if (TelephonyManager.EXTRA_STATE_OFFHOOK.equals(state)) {
//stop the player or mute the audio here
}
}
}
}
之后在清单文件中添加上述广播接收器。
<receiver android:name="com.radioapp.util.TelephonyManagerReceiver" >
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
并确保您在清单中请求此权限:
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>