Search code examples
androiddatetextviewrecurrence

Making a Simple Recurring Text Update Continue Indefinitely


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?


Solution

  • 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()