Update UI Asynchronously in Android

后端 未结 2 1935
遇见更好的自我
遇见更好的自我 2021-01-27 00:15

I have a webservice call which is called every 10 seconds and should update a TextView with the webservice reply(or atleast show a toast message every 10 seconds)

But th

2条回答
  •  北海茫月
    2021-01-27 01:16

    Here is an example of an AsyncTask

    public class TalkToServer extends AsyncTask {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }
    
    @Override
    protected void onProgressUpdate(String... values) {
        super.onProgressUpdate(values);
    
    }
    
    @Override
    protected String doInBackground(String... params) {
    //do your work here
        return something;
    }
    
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
           // do something with data here-display it or send to mainactivity
    }
    

    Then you can access by calling

    TalksToServer varName = new TalkToServer(); //pass parameters if you need to the constructor
    varName.execute();
    

    Async Docs Progress Dialog Example

    You don't want to do network stuff or call sleep on the UI thread. If it is an inner class then you will have access to your member variables of the outer class. Otherwise, create a contructor in the AsyncTask class to pass context if you want to update from onPostExecute or other methods besids doInBackground().

提交回复
热议问题