Android: Create a background thread that runs periodically and does UI tasks?

前端 未结 3 1260
遇见更好的自我
遇见更好的自我 2021-01-15 07:03

OK, so I know how to do a backround task, I know how to do a periodic task (using handle postdelayed and runnable), I also know how to do UI task from background thread (via

3条回答
  •  迷失自我
    2021-01-15 07:29

    You could use Async Tasks. These are designed for it :

    http://developer.android.com/reference/android/os/AsyncTask.html

    It allows you to execute a network call in the background, then when you get the result, execute an action on the UI thread

    Declaration :

     private class MyTask extends AsyncTask {
     protected Output doInBackground(Input... inputs) {
           // do something on the network
           return myOutput;// use this to transmit your result
     }
    
     protected void onPostExecute(Output result) {
         // do something on UI thread with the result
     }
    

    }

    If you want to repeat it, just create a runnable to launch it, and after every call, schedule the next one :

    MyTask myTask;
    Handler handler = new Handler();
    
        Runnable myRunnable = new Runnable() {
                @Override
                public void run() {
                    MyTask myTask = new MyTask();
                    myTask.execute(myArg);
                    handler.postDelayed(netRunnable, 60000); // schedule next call
                }
            }
    

    To launch it for the first time :

    handler.postDelayed(myRunnable, 60000);
    

    Or, if you want to launch it immediately :

    handler.post(myRunnable);
    

    Do not forget to cancel the Task when your activity is destroyed :

    myTask.cancel(true);
    

提交回复
热议问题