2017-01-23 54 views
2

此代碼的工作。我唯一的問題是,當我不使用的應用程序,電話鈴聲響起,音樂播放我掛斷了。暫停音樂手機響起時?

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); 
     } 
    } 

回答

1

只要引入一個布爾值來跟蹤音樂是否在先播放。我剛剛完成了你的周圍班級,但你明白了。

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); 
     } 
    } 
} 
相關問題