2

在我的秒錶應用程序中,開始按鈕應該啓動聲音,暫停按鈕應該停止聲音。用這個scenerio,我的程序工作正常。如何在應用程序關閉/最小化時停止MediaPlayer聲音?

但在播放聲音時,如果我回去或最小化應用程序,聲音不會停止。它一直在玩(所有的時間,即使是設備閒置)。而奇怪的是,當我重新打開應用程序停止聲音時,它永遠不會停止。 如何解決這個問題?

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    timerValue = (TextView) findViewById(R.id.timerValue); 

    startButton = (Button) findViewById(R.id.startButton); 
    mp = MediaPlayer.create(getApplicationContext(), R.raw.sound); 
    startButton.setOnClickListener(new View.OnClickListener() { 

     public void onClick(View view) { 
      startTime = SystemClock.uptimeMillis(); 
      customHandler.postDelayed(updateTimerThread, 0); 

       mp.start(); 
       mp.setLooping(true); 


     } 
    }); 

    pauseButton = (Button) findViewById(R.id.pauseButton); 

    pauseButton.setOnClickListener(new View.OnClickListener() { 

     public void onClick(View view) { 

      timeSwapBuff += timeInMilliseconds; 
      customHandler.removeCallbacks(updateTimerThread); 
      if(mp.isPlaying()) 
      { 
       mp.pause(); 

      } 
     } 
    }); 
    resetButton = (Button) findViewById(R.id.reset); 


    resetButton.setOnClickListener(new View.OnClickListener() { 

     public void onClick(View view) { 

      timerValue.setText("" + 00 + ":" 
        + String.format("%02d", 00) + ":" 
        + String.format("%03d", 00)); 
      startTime = SystemClock.uptimeMillis(); 
      timeSwapBuff = 0; 

     } 
    }); 

} 

private Runnable updateTimerThread = new Runnable() { 

    public void run() { 

     timeInMilliseconds = SystemClock.uptimeMillis() - startTime; 

     updatedTime = timeSwapBuff + timeInMilliseconds; 

     int secs = (int) (updatedTime/1000); 
     int mins = secs/60; 
     secs = secs % 60; 
     int milliseconds = (int) (updatedTime % 1000); 
     timerValue.setText("" + mins + ":" 
       + String.format("%02d", secs) + ":" 
       + String.format("%03d", milliseconds)); 
     customHandler.postDelayed(this, 0); 
    } 

}; 

回答

3

您可以使用Android生命週期。

我認爲你可以在onStop()onDestroy()

示例代碼中調用mp.pause();

@Override 
    protected void onStop() { 
     super.onPause(); 
     mp.pause(); 
    } 

    @Override 
    protected void onDestroy() { 
     super.onDestroy(); 
     mp.pause(); 
    } 
+0

現在我知道你爲什麼有這麼多的聲望!謝謝,它的作品。 – Riyana 2015-03-24 22:35:38

+0

很高興幫助,歡呼! – bjiang 2015-03-24 22:37:20

0

你應該訪問相同的MediaPlayer對象
把它公開,也許工作
這個解決方案爲我:創建一個類並定義靜態MediaPlayer對象和靜態方法(暫停,停止等)
也可以覆蓋onPause方法活動課並停止媒體播放器

0

要停止播放,請致電mp.pause()右側的onPause()函數。然而,你的onStop()應該更像:

@Override 
    protected void onStop() { 
     super.onStop();  // <<-------ENSURE onStop() 
     mp.stop(); 
     mp.release(); 
    } 

如果你在你的設備中的菜單和主頁按鈕,你應該檢查你的應用程序按下這些按鈕以及後的恢復。

Kf

相關問題