scheduleAtFixedRate 使整个应用程序崩溃

scheduleAtFixedRate crash whole app

我正在编写生成随机数并在 android 屏幕上(一个接一个)显示它们的应用程序。这是 activity java 片段。

public class Scada extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_scada);
    Timer timer1= new Timer();
    timer1.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            TextView myTextView = (TextView) findViewById(R.id.Flow1);
            random flow1=new random();
            myTextView.setText("Flow: " + flow1.random() + " m" + Html.fromHtml("<sup><small>" + "3" + "</small></sup>"));
        }
    },0,9000);

这里是随机的class(不过我觉得还行)

public class random {

    public int random (){
    Random gen1 = new Random();
    int flow1 = gen1.nextInt(100);
    return  flow1;}
}

当我尝试使用 Timer 应用时 crashed.What 是什么原因?提前谢谢你。

计时器在后台线程上运行,您不能在后台线程上更改 UI。如果您的目标只是每 9 秒更改一次 TextView 的内容,则可以使用 Handler。例如

final Runnable r = new Runnable() {
        public void run() {
            TextView myTextView = (TextView) findViewById(R.id.Flow1);
            random flow1=new random();
            myTextView.setText("Flow: " + flow1.random() + " m" + Html.fromHtml("<sup><small>" + "3" + "</small></sup>"));
            myTextView.postDelayed(this, 9000);
        }
    };

在 onCreate 中,同样的事情:

TextView myTextView = (TextView) findViewById(R.id.Flow1);
myTextView.postDelayed(r, 9000);