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

前端 未结 3 550
悲哀的现实
悲哀的现实 2021-01-15 07:20

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:41

    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<Input, Void, Output> {
     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);
    
    0 讨论(0)
  • 2021-01-15 07:44

    Maybe you are better of, creating a seperate (Intent)Service and calling it periodically with postDelayed. Create a BroadcastReceiver in your Activity and handle UI changes there.

    Another hint for handling UI changes from other threads: It is not possible. Therefore you need to call runOnUiThread. Here is how to use it

    0 讨论(0)
  • 2021-01-15 07:47

    If activities are frequently switching, why not reversing the responsibilities. You might create a service which executes a periodic network task.

    Then, - either your activities periodically call this service to get the value. - or you use a listener system : you create an interface that your activities must implement in order to get notified from the task completion

    0 讨论(0)
提交回复
热议问题