I have an Activity that must constantly get the result either from web or from MP3 stream data (ID3 tag) and display them on its TextViews.
So the parsing can be implemented in Service that plays the stream or in AsyncTask, that parses the file. It must be on timer and load the data only when the Activity became visible.
The parsing by itself can be realized, but what's the way to constantly run this task and update Activity UI?
I've seen some links, tried some own codes, but it worked only for 1 launch. The example for multiple call of AsyncTask from this site didn't work (crash).
Please give a stable simple working example of timered call of AsyncTask with constantly UI update or timered call of Service method with UI update.
As I understand, the timer must be called in UI thread in onCreate and onResume?
Thanks.
UPDATED CODE: (here is the working version of timer that updates UI, need to be tested with AsyncTask work)
doUpdate(); // in the UI onCreate
TimerTask updateTask;
final Handler handler = new Handler();
Timer timer = new Timer();
public void doUpdate(){
updateTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
Random r = new Random();
int nm=r.nextInt(100-1) + 1;
updatePlaylist(String.valueOf(nm)); //here we update the TextView
// BUT CALLING:
// new PlayList(PlayerActivity.this).execute(this);
// doesn't work! It's an AsyncTask.
}
});
}};
timer.schedule(updateTask, 0, 2000);
}
So maybe new AsyncTask object code line is wrong?
class PlayList extends AsyncTask<Activity, Void, String> {
private PlayerActivity act;
public PlayList(Activity activity) {
this.act = (PlayerActivity) activity;
}
protected String doInBackground(Activity... activities) {
String result;
Random r = new Random();
int num=r.nextInt(100-1) + 1;
result=String.valueOf(num);
//result=act.mp3Service.getPlaylist(); // will work later
return result;
}
protected void onPostExecute(String result) {
act.updatePlaylist(result);
}
}