【问题标题】:Continuously read buffer stops App连续读取缓冲区停止 App
【发布时间】:2023-03-03 14:21:03
【问题描述】:

我的应用从蓝牙设备接收到永无止境的数据流。 我正在一个 while(true) 循环中读取这个流,并且可以在我的日志中看到读取的数据。 问题是,我的设备不再响应。是否有(希望)简单的方法让应用程序在后台读取流?

谢谢! 克里斯蒂安。

@博尔德: 抱歉,我不太了解 AsynkTask 类。 :( 你能帮我把这段代码放在后台吗? 非常感谢!

                try {
                while (true) 
                {               
                    read = isBT.read(msgBuffer);
                    connected = true;
                    StringBuilder strBuffer = new StringBuilder();
                    for (int i = 0; i<read; i++) 
                    {
                        int b = msgBuffer[i];
                        strBuffer.append(b);
                    }
                    Log.d(TAG,"++++++ Read "+ read + " Bytes: " + strBuffer.toString());
                }
            }
                catch (IOException e) {
                    Log.d(TAG," +++ IOException ++++", e);
                }

【问题讨论】:

    标签: android inputstream android-asynctask


    【解决方案1】:

    这可能会有所帮助http://android-developers.blogspot.com/2009/05/painless-threading.html

    处理程序示例:

    private static final String CONTENT_TAG = "content";
    
    // Call this from datastream thread to post data 
    private void postProgress(String aBufferContent) {
        // Wrapping data in bundle
        final Bundle bundle = new Bundle();
        bundle.putString(CONTENT_TAG, aBufferContent);
    
        // Sending message to handler
        final Message message = mProgressHandler.obtainMessage();
        message.setData(bundle);
        mProgressHandler.sendMessage(message);
    }
    
    // This will be executed in UI thread. Do you GUI update job here
    private final Handler mProgressHandler = new Handler() {
        public void handleMessage(Message msg) {
            final String streamContent = msg.getData().getString(CONTENT_TAG);
            myTextView.setText(streamContent);
        }
    };
    

    【讨论】:

    • 谢谢博尔德。看起来很有趣。我将尝试使用带有方法 doInBackground() 的 AsyncTask 类。这是正确的方法吗?
    • 是的,没错。并使用 Handler 和 Message 类将您的进度发布到 UI 线程。顺便说一句,我认为最好为这项工作生成你自己的带有 Runnable 的线程,因为 AsyncTask 是为小任务设计的,主要不是为那些长时间运行的任务。如果您觉得有帮助,请随时点赞并接受我的回答 =)
    • 谢谢!代码现在在他自己的线程中运行,现在可以工作了:)
    • @boulder:如前所述,线程运行,但我无法更新我的 TextView。我知道它必须通过处理程序来完成(谷歌是我的朋友:))但我无法让它工作。你能用我的代码给我看一个小例子吗?再次感谢:)
    • 用处理程序示例更新了我的答案。
    猜你喜欢
    • 2015-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-15
    • 1970-01-01
    • 1970-01-01
    • 2020-07-13
    相关资源
    最近更新 更多