Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/220.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在android中更改新TimerTask操作中的某些内容?_Android - Fatal编程技术网

如何在android中更改新TimerTask操作中的某些内容?

如何在android中更改新TimerTask操作中的某些内容?,android,Android,我对android中的timerTask有一个问题我有这样一个代码: timer = new Timer(); timer.schedule(new TimerTask() { public void run() { countInt = countInt + 1; textview1.setText(countInt); } }, 1000); 每次计时器任务启动时,我的应用程序都会崩溃,因为我正在访问t

我对android中的timerTask有一个问题我有这样一个代码:

timer = new Timer();
timer.schedule(new TimerTask() {
        public void run() {
            countInt = countInt + 1;
            textview1.setText(countInt);
        }
    }, 1000);
每次计时器任务启动时,我的应用程序都会崩溃,因为我正在访问textview,而它在另一个线程中,对吗

如何解决这个问题?

试试这个

 timer = new Timer();
    timer.schedule(new TimerTask() {
            public void run() {
                countInt = countInt + 1;
                yourActivity.this.runOnUiThread(new Runnable()
               public void run(){
                  {textview1.setText(String.valueOf(countInt))});
                }
            }
        }, 1000);

它崩溃是因为您正在处理属于不允许的UI线程的东西。

是的,您是对的,它崩溃是因为“您不是从UI线程访问视图”。要解决这个问题,您可以使用活动发布一个可运行到UI线程

timer = new Timer();
timer.schedule(new TimerTask() {
    public void run() {
        countInt = countInt + 1;
        YourActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                textview1.setText(countInt);
            }
        });
    }
}, 1000);