0

我从另一个博客获得了这个蓝牙代码。我能够设置连接并通过蓝牙发送数据。我无法接收。我一直在使用相同的代码一段时间,只是被难住了。我是一个新手,可以使用一些帮助。该应用程序是一个简单的发送 2 个字节并接收 2 个字节。

   void beginListenForData()
        {
            final Handler handler = new Handler(); 
            final byte delimiter = 10; //This is the ASCII code for a newline character
            rcdata.setText("DataRC");           //NEW
            stopWorker = false;
            readBufferPosition = 0;
            readBuffer = new byte[1024];
            workerThread = new Thread(new Runnable()

            {
                public void run()
                {    
                rcdata.setText("DataRC0");          // Test NEW
                   while(!Thread.currentThread().isInterrupted() && !stopWorker)
                   {
                        try 
                        {
                            int bytesAvailable = mmInputStream.available();  

                            if(bytesAvailable > 0)
                            {
                                byte[] packetBytes = new byte[bytesAvailable];
                                mmInputStream.read(packetBytes);
                                rcdata.setText("DataRC1");          // Test NEW
                                for(int i=0;i<bytesAvailable;i++)
                                {

                                    byte b = packetBytes[i];
                                    if(b == delimiter)
                                    {
                                        byte[] encodedBytes = new byte[readBufferPosition];
                                        System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
                                        final String data = new String(encodedBytes, "US-ASCII");
                                        readBufferPosition = 0;

                                        handler.post(new Runnable()
                                        {
                                            public void run()
                                            {
                                                rcdata.setText(data);
                                            }
                                        });
                                    }
                                    else
                                    {
                                        readBuffer[readBufferPosition++] = b;
                                    }
                                }
                            }
                        } 
                        catch (IOException ex) 
                        {
                            stopWorker = true;
                        }
                   }
                }
            });

            workerThread.start();
        }
4

1 回答 1

0

我想你在非 ui 线程上听,我想 rcdata 是编辑或文本视图,你应该使用这个:http: //developer.android.com/reference/android/app/Activity.html#runOnUiThread%28java.lang.Runnable% 29

对于所有 rcdata.setText 调用

于 2013-08-14T15:57:27.267 回答