Android线程似乎不起作用

时间:2018-03-30 21:50:50

标签: java android android-studio

在我现在正在使用的调谐器应用程序中,我想实现一个指示器,显示是否播放了正确的音高。为此,我已经实现了指示器的颜色仅在我按住音高至少2秒时才会改变。

    public void thr(final double v1, final double v2) {
    new Thread() {
        @Override
        public void run() {
            super.run();
            int i = 0;
            while (pitchInHz >= v1 && pitchInHz < v2) {
                if(i == 20){    //2 Sekunden
                    imageView.setBackgroundColor(getResources().getColor(holo_green_light));
                }else {
                    imageView.setBackgroundColor(getResources().getColor(darker_gray));
                    try {
                        sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    i++;
                }
            }
            running = false;
        }
    }.start();

每当我的应用程序尝试使用该线程时,该应用程序就会崩溃。 一些想法为什么会这样?

        if(pitchInHz >= 72.41 && pitchInHz < 92.41) {
        //e
        noteText.setText("e"); //this is working
        if(!running) {
            thr(72.41, 92.41);
            running = true;
        }

1 个答案:

答案 0 :(得分:0)

我想它是因为你试图从主线程以外的其他线程访问一个视图,你不能这样做。

尝试像这样运行:

public void thr(final double v1, final double v2) {
new Thread() {
    @Override
    public void run() {
        super.run();
        int i = 0;
        while (pitchInHz >= v1 && pitchInHz < v2) {
            if(i == 20){    //2 Sekunden
                runOnUiThread(new Runnable() {
                    @override
                    public void run() {
                        imageView.setBackgroundColor(getResources().getColor(holo_green_light));
                    }
                })

            }else {
                runOnUiThread(new Runnable() {
                    @override
                    public void run() {
                        imageView.setBackgroundColor(getResources().getColor(darker_gray));
                    }
                })
                try {
                    sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                i++;
            }
        }
        running = false;
    }
}.start();