2011-04-27 35 views
0

我的应用程序从蓝牙设备接收一个永不停息的数据流。 我在一段时间(真)循环中读取此流,并可以在我的日志中看到读取的数据。 问题是,我的设备没有响应了。有没有(希望)简单的方法让应用程序在后台读取流?连续读缓冲区停止应用程序

谢谢! 基督徒。

@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

可能这将有利于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); 
    } 
}; 
+0

感谢boulder,看起来很有趣,我会用方法doInBackground()来尝试使用AsyncTask类,这是否正确? – 2011-04-27 13:34:01

+0

是的,并且使用Handler和Message类发布到UI线程。顺便说一句,我认为最好是用这个工作产生你自己的带有Runnable的线程,因为AsyncTask是专为小任务设计的,大多数情况下不适合那些长时间运行的人。如果您觉得有帮助,请随时注册并接受我的回答=) – 2011-04-28 09:44:08

+0

谢谢!代码现在运行在他自己的线程中,并且它现在可以工作:) – 2011-04-28 10:59:03