1

I wanted to run a async task in every 1 second and update the screen in every 1 second.
How can it be done?

For a simple example I want to show current time in every 1 second.
I creates a async task and it can calculate the current time update the UI once.
How can the task run infinitely?

Vishnudev K
  • 2,874
  • 3
  • 27
  • 42

4 Answers4

2

Asynch task is not designed to be run repeatedly. its a one off thing. You fire it, handle the stuff and forget it. For repeated work try:

  • Schedued threadpool executor
  • Timertask
  • Alarm manager

either will do the job for you.

Nazgul
  • 1,892
  • 1
  • 11
  • 15
2

Do code like this way:

public class MainActivity extends Activity {

TextView mClock;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mClock = (TextView) findViewById(R.id.your_textview_id);
}

private Handler mHandler = new Handler();
private Runnable timerTask = new Runnable() {
    @Override
    public void run() {
        Calendar now = Calendar.getInstance();
        mClock.setText(String.format("%02d:%02d:%02d",
                now.get(Calendar.HOUR),
                now.get(Calendar.MINUTE),
                now.get(Calendar.SECOND)) );
        mHandler.postDelayed(timerTask,1000);
    }
};

@Override
public void onResume() {
    super.onResume();
    mHandler.post(timerTask);
}

@Override
public void onPause() {
    super.onPause();
    mHandler.removeCallbacks(timerTask);
}
}
ridoy
  • 6,274
  • 2
  • 29
  • 60
0

You can use Timer and TimerTask.

  1. http://developer.android.com/reference/java/util/Timer.html
  2. http://developer.android.com/reference/java/util/TimerTask.html

Documentation suggest using ScheduledThreadPoolExecutor, but Timer is so simple that it's still worth consideration.

ezaquarii
  • 1,914
  • 13
  • 15
  • thanks for the replay http://stackoverflow.com/questions/8098806/where-do-i-create-and-use-scheduledthreadpoolexecutor-timertask-or-handler solved the issue – Vishnudev K May 07 '14 at 20:08
-1

All of these answers are wrong. If you want something to happen on another thread, regularly, use a freaking Thread. Put a while loop at the top and make it sleep until the next time you want it to run.

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127
  • Author wants to update GUI every 1 second, so that "something" must happen in GUI thread. – ezaquarii May 07 '14 at 21:21
  • Author used that as an example. He initially said AsyncTask, which means he wants to do something in another thread. If that isn't what he wants, he should clarify. If, for example, he wants to hit a website and post the result, he has to use a thread or AsyncTask (and AsyncTask is the wrong solution here), and then post the UI change back to the UI thread via handler. Agreed that if he doesn't need it on another thread then a thread isn't the right solution. – Gabe Sechan May 07 '14 at 21:26