ScheduledThreadPoolExecutor does not work on Android. Why?

Viewed 49

I am quite newbie with android development and I am trying to figure out why this does not work. I run this idea on Eclipse and it works fine. But I cant make it work on any of my devices. The app shows the value at start but it dont refresh the value anymore.

public class MainActivity extends AppCompatActivity {

    private TextView txtCrono;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        this.txtCrono = (TextView) findViewById(R.id.txtTiempo); //activity_main TextView

        ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1);


        exec.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                txtCrono.setText(String.valueOf(System.currentTimeMillis()));
            }
        }, 0, 100, TimeUnit.MILLISECONDS);

    }
}
1 Answers

Try to use runOnUIThread:

exec.scheduleAtFixedRate(new Runnable() {
    @Override
    public void run() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                txtCrono.setText(String.valueOf(System.currentTimeMillis()));
            }
        });
    }
}, 0, 100, TimeUnit.MILLISECONDS);

Basically, you must access a View from the main UI thread. (I don't know why your code doesn't cause an error and the first runnable is successfully setText. Maybe only the first runnable is executed on the main UI thread.)

Related