Skip to content Skip to sidebar Skip to footer

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?

Solution 1:

finalHandlerhandler=newHandler(); 
    finalRunnabler=newRunnable()
    {
        publicvoidrun() 
        {
            callWebservice();
        }
    };

    handler.postDelayed(r, 5000);

Solution 2:

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
        publicvoidrun() {
            CallWebService();
        }

    }, 0, 1000);
}

privatevoidCallWebService()
{
    this.runOnUiThread(fetchData);
}

private Runnable fetchData = new Runnable() {
    publicvoidrun() {
      asyncTask.execute();
    }
};

Solution 3:

You should call asynctask inside the application main thread. Asynctask can't be called in a background thread.

Post a Comment for "Android Async, Handler Or Timer?"