Atanas Vangelov Atanas Vangelov - 1 year ago 49
Java Question

How to call run() that refreshes screen information infinite times until user closes app

So I'm working on an app that monitors different device stats. Basically I want the app to refresh the statistics every second and show it to the user. For example a simple battery monitor

public class MainActivity extends AppCompatActivity implements Runnable{

public void run(){
fillField(R.id.fieldVoltage, battery.getVolt());
}

@Override
protected void onResume(){
super.onResume();
run();
}


this code works fine but if I add the actual refreshing

@Override
protected void onResume(){
super.onResume();
while(true){
run();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}


I can see the logcat refreshing but the screen is empty including all buttons and text. I think its because the onResume function doesn't actually end.

What logic should I use to implement the refreshing?

Answer Source

It's indeed because onResume() never returns. There are two reasons for your problem:

  • while(true)
  • Thread.sleep(1000)

Both you should never do anytime. In your case these block your main thread.

Instead use a main thread Handler to schedule the Runnable delayed.

public class MainActivity extends AppCompatActivity implements Runnable {
    private final Handler handler = new Handler();

    @Override
    protected void onResume(){
        super.onResume();
        run();
    }

    @Override
    protected void onPause(){
        handler.removeCallbacks(this);
        super.onPause();
    }

    public void run(){
        fillField(R.id.fieldVoltage, battery.getVolt());
        handler.postDelayed(this, 1000);
    }

    [....]
}