Reputation: 339
I am working on an android application extending activity and implementing Runnable.
The problem is that the run() function is not launched and I'm not sure if implementing Runnable make it launch automaticly as AsyncTask?
Here is my code
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener, Runnable {
...
@Override
public void run() {
// mediaPlayer is myMediaPlayer
// progress is my SeekBar
Log.w("Tunesto", "testabababab");
int currentPosition = 0;
int total = mediaPlayer.getDuration();
progress.setMax(total);
while (mediaPlayer != null && currentPosition < total) {
try {
Thread.sleep(1000);
currentPosition = mediaPlayer.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
progress.setProgress(currentPosition);
Log.w("MyApp", String.valueOf(currentPosition));
}
}
}
Obviously if I launch Run fro, the UI Thread it will freeze the screen because of the sleep method, so how should I do to let the Run method to run?
Thank you!
Upvotes: 1
Views: 3352
Reputation: 41945
You will have to use AsyncTask
in Android.
Steps to perform:
AsyncTask
doInBackground
method, where your logic should resideexecute
method on your nested class instance from where you need to call run()
The fact is i'm not sure if it's possible to stop an asyntask?
You can cancel the async task using the cancel()
method on the AsyncTask
. Refer to Android Documentation for more details on this.
Edit
To move your code inside the run()
function to an AsyncTask
, you will put anything that is "setting up" UI
stuff inside onPreExecute()
such as creating a ProgressBar
. Then put your work in such as calling sleep()
and other things that can't be done on the UI Thread
inside doInBackground()
. If you need to update your seek bar you can do that in onProgressUpdate()
by calling publishProgress()
inside doInBackground()
. Finally, if you need to dismiss the ProgressBar
or do some ending UI
stuff you will do that in onPostExecute()
.
The reason for that explanation is because all methods of AsyncTask
run on the UI Thread
except for doInBackground()
.
Vogella: Background tasks in Android
Upvotes: 3
Reputation: 3033
new Thread(this).start();
Although an anonymous inner class on either the handler or async would be better than making the activity itself Runnable.
Upvotes: 0