0

I am trying to calculate the duration of a media file and updating the list upon retrieval. I am using asyncTask for calculating the duration. But app hangs for the duration till it is calculating the size. Why is it happening? Is there a better approach?

My async task is:- ew LongOperation().execute(mFileMang.getCurrentDir()+"/" + mDataSource.get(position));

 private class LongOperation extends AsyncTask<String, Void, String> {

     @Override
     protected String doInBackground(String... params) {

            MediaPlayer mp = MediaPlayer.create(mContext,  Uri.parse(params[0]));
            long duration = mp.getDuration();
            mp.reset();
            mp.release();

               String finalTimerString = "";
               String secondsString = "";
               String minutesString = "";
               // Convert total duration into time
               int hours = (int)( duration / (1000*60*60));
               int minutes = (int)(duration % (1000*60*60)) / (1000*60);
               int seconds = (int) ((duration % (1000*60*60)) % (1000*60) / 1000);
               // Add hours if there
               if(hours > 0){
               finalTimerString = hours + ":";
               }

               // Prepending 0 to seconds if it is one digit
               if(seconds < 10){
               secondsString = "0" + seconds;
               }else{
               secondsString = "" + seconds;}

               if(minutes < 10){
                   minutesString = "0" + minutes;
               }else{
                   minutesString = "" + minutes;}


               duration_video = finalTimerString = finalTimerString + minutesString + ":" + secondsString;

               return null;
     }      

     @Override
     protected void onPostExecute(String result) {

           //might want to change "executed" for the returned string passed into onPostExecute() but that is upto you
     }

     @Override
     protected void onPreExecute() {
     }

     @Override
     protected void onProgressUpdate(Void... values) {
     }

}

Mukesh Kumar Singh
  • 4,512
  • 2
  • 22
  • 30
Payal
  • 903
  • 1
  • 9
  • 28
  • You should step through it with a debugger or log steps so you can tell *exactly* where it's hanging. At that point it'll be more obvious what's causing it. On first glance, the code looks fine. – Geobits Oct 10 '13 at 13:50

1 Answers1

-2

AsyncTask should not be used for long operations (no more then 2 to 3 seconds). I don't know if this is the case but since you called your task LongOperation I assume it is running longer.

You can find more info about it Here

Community
  • 1
  • 1
Dage
  • 226
  • 1
  • 10