Search code examples
androidmultithreadingmedia-playerdecrement

Running a thread for some seconds


I am using a media player instance to play a music file.I want to play the song for certain time then stop playing.I'm using a thread with counter decrementing but some how tis not workin properly.


Solution

  • you have to use handler for that

    try this

    in your onCreate use this 
    
      //start media player
      mp.start();
    
    
      mTimer.sendMessageDelayed(new Message(),5*10000);
    

    create a class in you activity class as

        private MusicTimer mTimer = new MusicTimer();
    
        private class MusicTimer extends Handler
        {
           @Override
           handleMessage(Message msg)
           {
               onTimerExpire();
           }  
    
    
    
            public void onTimerExpire()
            {
               //stop player here
            }
    
    }
    

    make media player object member variable this will play that for five seconde then stop nthat