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

对着背影说爱祢 提交于 2019-12-01 11:22:58
AlbAtNf

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

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);

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!