Run a loop every second java

int delay = 1000; // delay for 1 sec. int period = 10000; // repeat every 10 sec. Timer timer = new Timer(); timer.scheduleAtFixedRate(new TimerTask() { public void run() { displayData(); // display the data } }, delay, period); 

And other:

 while(needToDisplayData) { displayData(); // display the data Thread.sleep(10000); // sleep for 10 seconds } 

Both of them do not work (application is forcibly closed). What other options can I try?

+7
source share
5 answers

The code crashes because you execute hibernation in the background thread, but the displayed data must be executed in the user interface thread.

You need to run displayData from runOnUiThread (Runnable) or define a handler and send it a message.

eg:

 (new Thread(new Runnable() { @Override public void run() { while (!Thread.interrupted()) try { Thread.sleep(1000); runOnUiThread(new Runnable() // start actions in UI thread { @Override public void run() { displayData(); // this action have to be in UI thread } }); } catch (InterruptedException e) { // ooops } } })).start(); // the while thread will start in BG thread 
+23
source

Use onPostDelayed() to access any of your View or Handler . You save memory without creating a Timer or a new Thread .

 private final Handler mHandler = new Handler(); private final Runnable mUpdateUI = new Runnable() { public void run() { displayData(); mHandler.postDelayed(mUpdateUI, 1000); // 1 second } } }; mHandler.post(mUpdateUI); 
+8
source

Try the following:

 @Override public void run() { TextView tv1 = (TextView) findViewById(R.id.tv); while(true){ showTime(tv1); try { Thread.sleep(1000); }catch (Exception e) { tv1.setText(e.toString()); } } } 

U can also try this

There is another way that you can use to update the user interface at a specific time interval. The above two parameters are correct, but depending on the situation, you can use alternative methods of updating the user interface in a certain period of time.

First declare one global varialbe for the handler to update the user interface control from the stream, for example below

Handler mHandler = new Handler (); Now create one thread and use the while loop to periodically execute the task using the sleep method on the thread.

 new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub while (true) { try { Thread.sleep(10000); mHandler.post(new Runnable() { @Override public void run() { // TODO Auto-generated method stub // Write your code here to update the UI. } }); } catch (Exception e) { // TODO: handle exception } } } }).start(); 
0
source

A few mistakes you made:

  • You should never call Thread.sleep () on the main thread (and you should never block it for a long time). As soon as the main thread is blocked for more than 5 seconds, ANR (application does not respond), and it is forced to close.

  • You should avoid using a timer in android. Try Handler instead. The good thing about the handler is that it is created in the main thread -> it can access Views (unlike Timer, which runs in its own thread, which cannot access Views).

     class MyActivity extends Activity { private static final int DISPLAY_DATA = 1; // this handler will receive a delayed message private Handler mHandler = new Handler() { @Override void handleMessage(Message msg) { if (msg.what == DISPLAY_DATA) displayData(); } }; @Override void onCreate(Bundle b) { //this will post a message to the mHandler, which mHandler will get //after 5 seconds mHandler.postEmptyMessageDelayed(DISPLAY_DATA, 5000); } } 
0
source

I came across this thread when I tried to work around the problem that you cannot hide seconds in DigitalClock widgets for Android. DigitalClock is now deprecated, and TextClock is now the recommended widget. This does not work on older APIs ... So I had to write my 24 hour clock. I don't know if this is a good implementation, but it seems to work (and is updated every second):

  import java.util.Calendar; import android.os.Handler; import android.view.View; import android.widget.TextView; /** * A 24 hour digital clock represented by a TextView * that can be updated each second. Reads the current * wall clock time. */ public class DigitalClock24h { private TextView mClockTextView; // The textview representing the 24h clock private boolean mShouldRun = false; // If the Runnable should keep on running private final Handler mHandler = new Handler(); // This runnable will schedule itself to run at 1 second intervals // if mShouldRun is set true. private final Runnable mUpdateClock = new Runnable() { public void run() { if(mShouldRun) { updateClockDisplay(); // Call the method to actually update the clock mHandler.postDelayed(mUpdateClock, 1000); // 1 second } } }; /** * Creates a 24h Digital Clock given a TextView. * @param clockTextView */ public DigitalClock24h(View clockTextView) { mClockTextView = (TextView) clockTextView; } /** * Start updating the clock every second. * Don't forget to call stopUpdater() when you * don't need to update the clock anymore. */ public void startUpdater() { mShouldRun = true; mHandler.post(mUpdateClock); } /** * Stop updating the clock. */ public void stopUpdater() { mShouldRun = false; } /** * Update the textview associated with this * digital clock. */ private void updateClockDisplay() { Calendar c = Calendar.getInstance(); int hour = c.get(Calendar.HOUR_OF_DAY); // 24 hour int min = c.get(Calendar.MINUTE); String sHour; String sMin; if(hour < 10) { sHour = "0" + hour; } else sHour = "" + hour; if(min < 10) { sMin = "0" + min; } else sMin = "" + min; mClockTextView.setText(sHour + ":" + sMin); } } 

Thanks biegleux for pointing me in the right direction!

0
source

All Articles