由于某种原因,runOnUiThread被跳过

时间:2013-09-09 09:13:54

标签: android multithreading

我有一个名为DataInputstreamThread的帖子。 DataInputstreamThread从蓝牙设备获取输入。

我想使用runOnUiThread将处理后的数据从输入流添加到文本框。但这并不奏效。每次都会跳过runOnUiThread

代码::

public void getDataFromInputStream() {

    DataInputstreamThread = new Thread(new Runnable() {
        public void run() {


            threadFlag = connectDevice();
            while (threadFlag) {
                try {
                    if (inputStream == null) {
                        inputStream = bluetoothSocket.getInputStream();
                    }

                    bytesAvailable = inputStream.available();
                    if (bytesAvailable > 0) {
                        byte[] packetBytes = new byte[bytesAvailable];
                        inputStream.read(packetBytes);

                        for (int i = 0; i < bytesAvailable; i++) {

                            if (packetBytes[i] != 13) {
                                temp = new String(packetBytes);

                            } else {
                                delimiter = true;
                            }

                        }

                        fin += temp;//I have a breakpoint here, and i know this is executed


                        activity.runOnUiThread(new Runnable() {
                            public void run() {
                             notifyObservers(fin);//I have breakpoint here, and this line is not executed.
                            }
                        });

                        if (delimiter) {

                            fin = "";
                            delimiter = false;
                        }

                    }


                } catch (Exception e) {

                }

            }

            nullify();
        }

    });
    DataInputstreamThread.start();
}

那么为什么 runOnUiThread 没有被执行?

2 个答案:

答案 0 :(得分:3)

这并没有直接回答您提出的问题,但它解释了为什么找不到问题的原因。

这:

catch (Exception e) {

}

正在摧毁你找到这个bug的任何希望。您吞下了异常,因此您没有看到runOnUiThread可能抛出的错误。你只能做猜测。

做一些有用的事情。至少,output the exception stack trace to LogCat。如果之后您仍然无法找到错误,请返回此处并延长您的问题。

答案 1 :(得分:0)

试试这种方式

Handler mHandler = new Handler();

        mHandler.post(new Runnable() {

            @Override
            public void run() {
                 notifyObservers(fin);
            }
        });

而不是

activity.runOnUiThread(new Runnable() {
                            public void run() {
                             notifyObservers(fin);//I have breakpoint here, and this line is not executed.
                            }
                        });