Android 2.2: How to update text images automatically using a timer?

I have some text elements in my application that I want to update automatically every 5 seconds. I have a method for updating them, but how to make a timer that starts the method every 5 seconds? Thanks!

+4
source share
3 answers

Provide another solution

Handler h=new Handler(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setContentView(R.layout.main); h.post(new Runnable(){ @Override public void run() { // call your function h.postDelayed(this,5000); } }); 
+4
source

Look at the CountDownTimer extension, it has an onFinish () method that you can overwrite to refresh the TextView and restart the timer if you want to repeat it. You can also bind to onTick () if you want to update only a finite number of times.

+4
source

I tried the Handler solution myself, especially after reading this article on the resource pages: http://developer.android.com/resources/articles/timed-ui-updates.html . But I wanted to be able to start and stop the timer in the same way as a stopwatch, and after the timer resumes, the Handler solution starts updating much less often - on the emulator every five seconds. In the end, I found a review on a blog that suggested a solution with an inner class extending AsyncTask. You can use the publishProgress () - onProgressUpdate () function in AsyncTask. From onProgressUpdate (), you can make changes β€œdirectly” to the user interface stream, for example. myTextView.setText (...). This publishes the results much more often. Here's a super simple implementation of this inner class:

 private class UpdateTimerLabel extends AsyncTask<Integer, Integer, Integer> { @Override protected Integer doInBackground(Integer... arg0) { while (true) { try { Thread.sleep(1000); publishProgress(arg0); Log.d(tag, "AsyncTask tries to publish"); } catch (InterruptedException e) { e.printStackTrace(); }if (1 == 0) break; // Silly but necessary I think } return null; } protected void onProgressUpdate(Integer... progress) { updateTimerTextView(); // Call to method in UI } } 
-1
source

Source: https://habr.com/ru/post/1333745/


All Articles