Search code examples
javaandroidandroid-mediaplayerrunnable

How to stop a runnable in a mediaplayer?


I have a mp3 player that has a "Runnable" that is working even when the user already has exit the activity, is there a way to stop the runnable when the user press back: I have tryied adding flags using finish() but on my logs I can see that the runnable is still active, even after using 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);
}

Solution

  • you can try this code to stop runnable :

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