Android Async, Handler or Timer?

2019-03-19 09:39发布

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?

3条回答
手持菜刀,她持情操
2楼-- · 2019-03-19 10:34
final Handler handler = new Handler(); 
    final Runnable r = new Runnable()
    {
        public void run() 
        {
            callWebservice();
        }
    };

    handler.postDelayed(r, 5000);
查看更多
可以哭但决不认输i
3楼-- · 2019-03-19 10:38

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

查看更多
Root(大扎)
4楼-- · 2019-03-19 10:39

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();
    }
};
查看更多
登录 后发表回答