Vishnudev K
Vishnudev K

Reputation: 2934

Run async task periodically in android

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?

Upvotes: 1

Views: 1234

Answers (4)

Gabe Sechan
Gabe Sechan

Reputation: 93726

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.

Upvotes: -1

ridoy
ridoy

Reputation: 6342

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

Upvotes: 2

Nazgul
Nazgul

Reputation: 1902

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.

Upvotes: 2

ezaquarii
ezaquarii

Reputation: 1916

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.

Upvotes: 0

Related Questions