i am trying to play a song by using MediaPlayer from the given list.i want include time duration for the song from starting to ending of the song. how to add time and how to update that time from 0:00 to till the end of that song
            Asked
            
        
        
            Active
            
        
            Viewed 2.0k times
        
    7
            
            
        - 
                    Please refer this one http://stackoverflow.com/questions/5548922/how-do-i-correctly-display-the-position-duration-of-a-mediaplayer – Anand Savjani Jul 31 '16 at 13:20
 
2 Answers
21
            You can use the method getCurrentPosition() which gives you the current position in milliseconds.
You can also use the method getDuration() to get the full length of the song.
You can use a separate thread to update the timer.
        keyser
        
- 18,829
 - 16
 - 59
 - 101
 
14
            
            
        To show the playing time, I've used Timer and TimerTask, which updates TextView tv every 1000ms. Note that not using tv.post(Runnable action) for setting text in Text View would not block the UI thread and may cause problems.
if (player != null) {
    player.start();
    timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (player != null && player.isPlaying()) {
                        tv.post(new Runnable() {
                            @Override
                            public void run() {
                                tv.setText(player.getCurrentPosition());
                            }
                        });
                    } else {
                        timer.cancel();
                        timer.purge();
                    }
                }
            });
        }
    }, 0, 1000);
}
        Micer
        
- 8,731
 - 3
 - 79
 - 73