當我點擊主頁按鈕或當我接聽電話時,我的歌曲不停止播放?當歌曲停止時,我的計時器也不停止?有沒有辦法阻止我的計時器?你可以幫我嗎?mediaplayer在退出應用程序或電話鈴響時停止播放歌曲
public class MainActivity extends Activity {
private Button start, stop;
private MediaPlayer mp;
private TextView display, comment;
private TextView timerValue;
private long startTime = 0L;
private Handler customHandler = new Handler();
long timeInMilliseconds = 0L;
long timeSwapBuff = 0L;
long updatedTime = 0L;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
timerValue = (TextView) findViewById(R.id.timerValue);
start = (Button) findViewById(R.id.bStart);
start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mp = MediaPlayer.create(MainActivity.this, R.raw.splahsound);
mp.start();
startTime = SystemClock.uptimeMillis();
customHandler.postDelayed(updateTimerThread, 0);
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
mp.stop();
mp.reset();
mp.release(); // free up memory
mp = null;
}
});
}
});
stop = (Button) findViewById(R.id.bDur);
stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mp != null) {
try {
mp.stop();
mp.reset();
mp.release();
mp = null;
} catch (Exception e) {
Log.d("error", e.toString());
}
}
timeSwapBuff += timeInMilliseconds;
customHandler.removeCallbacks(updateTimerThread);
}
});
}
@Override
protected void onPause() {
super.onPause();
}
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));
customHandler.postDelayed(this, 0);
}
};
}
你必須使用服務! – Mahfa