如何停止媒体播放器中的可运行程序?

How to stop a runnable in a mediaplayer?

我有一个带有 "Runnable" 的 mp3 播放器,即使用户已经退出 activity,它也能正常工作,有没有办法在用户按下后退时停止运行:我尝试使用 finish() 添加标志,但在我的日志中我可以看到 runnable 仍然处于活动状态,即使在使用 removeCallbacks

     private Runnable UpdateSongTime = new Runnable() {
            @Override
            public void run() {
                sTime = mPlayer.getCurrentPosition();
                Log.e(TAG, "CURRENT TIME: " + sTime);
                startTime.setText(String.format("%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes(sTime),
                        TimeUnit.MILLISECONDS.toSeconds(sTime) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(sTime))) );
                songPrgs.setProgress(sTime);
                hdlr.postDelayed(this, 100);
            }
        };




      public void onBackPressed() {
          stopPlayer ()
                    Intent intent = new Intent(getApplicationContext(), activity.class);  
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK |Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NO_HISTORY);
                    finish();
                    startActivity(intent);

        }

public void stopPlayer () {
    mPlayer.stop();
    Handler handler = new Handler();
    handler.removeCallbacks(UpdateSongTime);
}

你可以试试这个代码来停止运行:

Handler handler = new Handler();
handler.removeCallbacks(runnable);