Skip to content Skip to sidebar Skip to footer

Android: Create A Background Thread That Runs Periodically And Does Ui Tasks?

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 handle

Solution 1:

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 :

privateclassMyTaskextendsAsyncTask<Input, Void, Output> {
 protectedOutputdoInBackground(Input... inputs) {
       // do something on the networkreturn myOutput;// use this to transmit your result
 }

 protectedvoidonPostExecute(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;
Handlerhandler=newHandler();

    RunnablemyRunnable=newRunnable() {
            @Overridepublicvoidrun() {
                MyTaskmyTask=newMyTask();
                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);

Solution 2:

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

Solution 3:

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

Post a Comment for "Android: Create A Background Thread That Runs Periodically And Does Ui Tasks?"