如何防止我的音乐播放器在我的 phone 响铃并挂断后启动?

How to prevent my music player from starting after my phone rings and I hang up?

此代码有效。我遇到的唯一问题是,当我不使用该应用程序并且 phone 响铃时,音乐会在我挂断后播放。

public void level_one(View view){

        mp3 = MediaPlayer.create(this, R.raw.alpha_12);

        PhoneStateListener phoneStateListener = new PhoneStateListener() {
            @Override
            public void onCallStateChanged(int state, String incomingNumber) {
                if (state == TelephonyManager.CALL_STATE_RINGING) {
                    mp3.pause();
                } else if(state == TelephonyManager.CALL_STATE_IDLE) {
                    mp3.start(); // Runs this line even if I didn't play
                } else if(state == TelephonyManager.CALL_STATE_OFFHOOK) {
                    mp3.pause();
                }
                super.onCallStateChanged(state, incomingNumber);
            }
        };
        TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        if(mgr != null) {
            mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
        }
    }

只需引入一个布尔值,它会跟踪之前是否播放过音乐。我刚刚编了你的周边 class 但你明白了。

public class MyClass
{
    private boolean isMusicPlaying = false;

    public void someFunctionWhichStartsMusic()
    {
        //start the music

        isMusicPlaying = true;
    }

    public void level_one(View view){

        mp3 = MediaPlayer.create(this, R.raw.alpha_12);

        PhoneStateListener phoneStateListener = new PhoneStateListener() {
            @Override
            public void onCallStateChanged(int state, String incomingNumber) {
                if (state == TelephonyManager.CALL_STATE_RINGING)
                {
                    mp3.pause();
                }
                else if(state == TelephonyManager.CALL_STATE_IDLE
                          && isMusicPlaying) // pay attention to this!
                {
                    mp3.start();
                }
                else if(state == TelephonyManager.CALL_STATE_OFFHOOK)
                {
                    mp3.pause();
                }
                super.onCallStateChanged(state, incomingNumber);
            }
        };
        TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        if(mgr != null) {
            mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
        }
    }
}