Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Async, Handler or Timer?

Every 5 seconds, I want to call my webservice and get text (not images), then display it in my ImageAdapter. What would be the best way to accomplish this?

like image 216
Raptrex Avatar asked Jul 21 '11 21:07

Raptrex


2 Answers

final Handler handler = new Handler(); 
    final Runnable r = new Runnable()
    {
        public void run() 
        {
            callWebservice();
        }
    };

    handler.postDelayed(r, 5000);
like image 135
srinivas Nidadavolu Avatar answered Nov 04 '22 11:11

srinivas Nidadavolu


It depends if you want to use a different thread or not. Do you want the user to be able to interact with the application on the UI Thread while the images are downloading? If so, then I would definitely use an AsyncTask with a small ProgressBar (style="@android:style/Widget.ProgressBar.Small")

If you don't care about threading then what @inazaruk said.

Edit: the truth is most modern apps that retrieve data from a web service will use an AsyncTask with a discreet little loader in the corner just to let the user know it's updating.

Edit 2: here's an example of using a TimerTask to run something every 5 seconds. The key is the runOnUiThread(). There may be better ways to tie all the elements together but this accurately portrays all the pieces.

myTimer = new Timer();
    myTimer.schedule(new TimerTask() {
        @Override
        public void run() {
            CallWebService();
        }

    }, 0, 1000);
}

private void CallWebService()
{
    this.runOnUiThread(fetchData);
}

private Runnable fetchData = new Runnable() {
    public void run() {
      asyncTask.execute();
    }
};
like image 28
citizen conn Avatar answered Nov 04 '22 12:11

citizen conn