连续读取缓冲区停止App

时间:2011-04-27 13:06:54

标签: android inputstream android-asynctask

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

谢谢! 基督教。

@boulder: 对不起,我真的不明白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);
                }

1 个答案:

答案 0 :(得分: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);
    }
};