Java 电话状态侦听器

Java 电话状态侦听器,java,android,Java,Android,我希望你做得很好 我有一个音乐应用程序,如果手机正在响,如果当前有电话,我想暂停音乐 看看下面的代码 我目前拥有的代码可以工作,但效率不高 如果有人在WhatsApp上给我打电话,代码会按照它的意图执行 但是,如果有人定期打电话给我,当电话铃声响起时,音乐会暂停,但当我接听电话时,音乐会消失(音量降低),我仍然可以听到背景音乐播放 How do I stop the music from playing in the background after I answer the call? 代码

我希望你做得很好

我有一个音乐应用程序,如果手机正在响,如果当前有电话,我想暂停音乐

看看下面的代码

我目前拥有的代码可以工作,但效率不高

如果有人在WhatsApp上给我打电话,代码会按照它的意图执行

但是,如果有人定期打电话给我,当电话铃声响起时,音乐会暂停,但当我接听电话时,音乐会消失(音量降低),我仍然可以听到背景音乐播放

How do I stop the music from playing in the background after I answer the call?
代码:

private void callStateListener() {
        telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        //Listening for phone calls
        phoneStateListener = new PhoneStateListener() {
            @Override
            public void onCallStateChanged(int state, String incomingNumber) {
                switch (state) {
                    //if the user is on a call or if phone is ringing, pause
                    case TelephonyManager.CALL_STATE_OFFHOOK:
                    case TelephonyManager.CALL_STATE_RINGING:
                        if (mediaPlayer != null || mediaPlayer.isPlaying()){
                            pause();
                            Intent pause = new Intent("PAUSE");
                            sendBroadcast(pause); //todo test if pause/play image when call
                        }
                        break;
                    case TelephonyManager.CALL_STATE_IDLE:
                        // start playing whe the phone is in idle mode
                        if (mediaPlayer != null && RequestAudioFocus()) {
                            play();
                        } else {
                            Toast.makeText(getApplicationContext(), "Another app is currently playing audio", Toast.LENGTH_SHORT).show();
                        }
                        break;
                }
            }
        };
        telephonyManager.listen(phoneStateListener,
                PhoneStateListener.LISTEN_CALL_STATE);
    }