Android Async, Handler or Timer?

后端 未结 3 707
误落风尘
误落风尘 2021-02-09 03:24

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条回答
  • 2021-02-09 03:51

    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();
        }
    };
    
    0 讨论(0)
  • 2021-02-09 04:00

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

    0 讨论(0)
  • 2021-02-09 04:16
    final Handler handler = new Handler(); 
        final Runnable r = new Runnable()
        {
            public void run() 
            {
                callWebservice();
            }
        };
    
        handler.postDelayed(r, 5000);
    
    0 讨论(0)
提交回复
热议问题