Al Phaba
Al Phaba

Reputation: 6755

How to refresh a view every few seconds in android?

In my app I am transfering pictures in a background service. For each picture I have database entry in my sqlite db. Now I want to add a info area on my main screen which shows the amount of pictures which needs to be transfered. This area should refresh every 10 seconds, so that a user can see if how many jobs need to be done.

What is the best practice in android to solve such a problem?

Thanks

Upvotes: 0

Views: 7445

Answers (3)

jsimon
jsimon

Reputation: 577

Use an AsyncTask. Work goes in doInBackground(), update the UI during the task with publishProgress(), update the UI at the end of the task with onPostExecute(). The advantage to AsyncTask is that it handles creating and managing the Handlers for you and provides a concise location to build your code.

See my comment here for skeleton code: preventing app from looking hung

Also read over the API: http://developer.android.com/reference/android/os/AsyncTask.html

And a tutorial on AsyncTasks: http://www.vogella.com/articles/AndroidPerformance/article.html#asynctask

Upvotes: 0

Alexander Lucas
Alexander Lucas

Reputation: 22361

Instead of manually updating every 10 seconds, it might be better to have it update every time a task completes. As long as the task isn't occurring on the UI thread, the two won't interfere with eachother. It'll also make the app feel much smoother if a progress bar gradually fills (or a percentage number gradually rises, or whatever) as opposed to one massive change every 10 seconds.

In order to update the UI from a non UI thread, you need to use a Handler. There's a good example of how to use a Handler to communicate from a service to the UI on Android's developer site.

Upvotes: 1

jeet.chanchawat
jeet.chanchawat

Reputation: 2575

you can try to create a 'recursive call' of the method with a delay of 10 seconds

    Handler handler = new Handler();

    handler.postDelayed(new Runnable() {
    @Override
    public void run() {

    //do anything


    }
    }, 10000);

** or better use this below method

Timer t = new Timer();

void timerMethod()
{
t.schedule(new TimerTask() {
public void run() {


Log.d("timer", "timer ");
//do anything


}
}, 10000, 10000);

}

Upvotes: 2

Related Questions