我的应用程序使用 MediaPlayer 类,我需要在来电时静音,但是当应用程序进入后台时(例如按下主页按钮时),音频会继续播放。
public static class ReceptorLlamadas extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
call(context);
}
private void call(Context context) {
PhoneCallListener phoneListener = new PhoneCallListener();
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.listen(phoneListener, PhoneStateListener.LISTEN_CALL_STATE);
}
private class PhoneCallListener extends PhoneStateListener {
public boolean isPhoneCalling = false;
Boolean wasRinging = false;
@Override
public void onCallStateChanged(int state, String incomingNumber) {
if (TelephonyManager.CALL_STATE_RINGING == state) {
// phone ringing
//Aquí ya detectas que el teléfono esta recibiendo una llamada entrante
}
if (TelephonyManager.CALL_STATE_OFFHOOK == state) {
// active
isPhoneCalling = true;
if (mPlayer != null && mPlayer.isPlaying()) {
mPlayer.setVolume(0,0);
}
}
if (TelephonyManager.CALL_STATE_IDLE == state) {
isPhoneCalling = false;
}
}
}
我添加到 manifest.xml
<receiver android:name=".MainActivity$ReceptorLlamadas">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
您
TelephonyManager
可以收集手机的不同状态:}