1

I have a very function function inside the activity that takes a static date in the past, formats it to a relative string using DateUtils.getRelativeDateTimeString (so it becomes something like "3 minutes ago" and sets it to a TextView. However, I want this TextView to keep updated so long as the activity stays open.

How do I make a continuous task that will either run continuously (infinite loop) or run within short intervals - like every second. How to accomplish this without getting into background services and such?

Dzhuneyt
  • 8,437
  • 14
  • 64
  • 118
  • Use AsyncTask, and do the conversion in `doInBackground` and publish it to `onProgressUpdate`. – Wenhui Oct 07 '12 at 21:17

2 Answers2

1

Here is an example using AsyncTask

private class BackgroundCoversionTask extends AsyncTask< String, String, Void >{

    @Override
    protected Void doInBackground( String... params ) {

        while( !isCancelled() ){
            try {
                Thread.sleep( 1000 );
            } catch ( InterruptedException e ) {
                break;
            }

            //DateUtils.getRelativeDateTimeString( MainActivity.this, time, minResolution, transitionResolution, flags )
            // Do something right here
            publishProgress( Long.toString( System.currentTimeMillis() ) );

        }

        return null;
    }

    @Override
    protected void onProgressUpdate( String... values ) {
        super.onProgressUpdate( values );

        mTextView.setText( values[0] );
    }

}

Then if you want to cancel the task, call cancel()

Wenhui
  • 648
  • 4
  • 13
0

Just run it on a separate thread.

Thread thread = new Thread()
{
    @Override
    public void run() {
        try {
            while(true) {
                sleep(1000);
                //Do your date update here
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
};

thread.start();

See: How to run a Runnable thread in Android?

With threads please make sure that when the app is paused or resumed you appropriately pause or resume your thread. Also it is a good idea to end them yourself at the end of the activity lifecycle for the sake of handling any data you might want

Community
  • 1
  • 1
AC Arcana
  • 366
  • 2
  • 10