【问题标题】:Bluetooth Connection and Receive/Display Data on Screen蓝牙连接和接收/在屏幕上显示数据
【发布时间】:2014-02-05 06:42:43
【问题描述】:

我正在尝试将我的安卓手机连接到与声纳传感器相连的电路上的Bluetooth 芯片。传感器/电路被编程为接受连接并以消息的形式连续显示数据。我的代码允许我连接,但它不会在屏幕上显示数据。帮忙?

您可以在下面找到我的 java 代码。

public class ConnectThread extends Activity {
    static BluetoothSocket mmSocket;
    static BluetoothSocket mmSocket2;
    static BluetoothDevice mmDevice;
    static BluetoothDevice mmDevice2;
    static InputStream mmInputStream;
    static OutputStream mmOutputStream;
    static BluetoothAdapter mBluetoothAdapter;
    static BluetoothAdapter mBluetoothAdapter2;
    TextView myLabel;
    TextView Display;
    static volatile boolean stopWorker;
    static Thread workerThread;
    static byte[] readBuffer;
    static int readBufferPosition;

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_connect_thread);

    Button button = (Button)this.findViewById(R.id.button1);
    myLabel = (TextView)findViewById(R.id.textView1);
    Display = (TextView)findViewById(R.id.Display);
    button.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Toast.makeText(ConnectThread.this, "Connection in progress", Toast.LENGTH_SHORT).show();
            myLabel.setText("Connection in progress");
            try 
            {
                 findBT();
                 openBT();

            }
            catch (IOException ex) { }
           }        
         });}



        void findBT() 
        {


            mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            if(mBluetoothAdapter == null)
            {
                myLabel.setText("No bluetooth adapter available");
            }

            if(!mBluetoothAdapter.isEnabled())
            {
                Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBluetooth, 0);
            }

            Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
            if(pairedDevices.size() > 0)
            {
                for(BluetoothDevice device1 : pairedDevices)
                {
                    if(device1.getName().equals("HC-05")) 
                    {
                        mmDevice = device1;
                        myLabel.setText("Bluetooth Device Found");
                        break;
                    }
                }

                if(pairedDevices.size()==0){myLabel.setText("Please Pair devices");}
            }




        }
        public int openBT() throws IOException
        {
            UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); //Standard SerialPortService ID
            mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);        
            mmSocket.connect();
            mmOutputStream = mmSocket.getOutputStream();
            mmInputStream = mmSocket.getInputStream();


            return 1;
        }

        void ListenForData()
        {
            final Handler handler = new Handler(); 
            final byte delimiter = 10; //This is the ASCII code for a newline character

            stopWorker = false;
            readBufferPosition = 0;
            readBuffer = new byte[1024];
            workerThread = new Thread(new Runnable()
            {
                public void run()
                {                
                   while(!Thread.currentThread().isInterrupted() && !stopWorker)
                   {
                        try 
                        {
                            int bytesAvailable = mmInputStream.available();                        
                            if(bytesAvailable > 0)
                            {
                                byte[] packetBytes = new byte[bytesAvailable];
                                mmInputStream.read(packetBytes);
                                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()
                                            {
                                                Display.setText(data);

                                            }
                                        });
                                    }
                                    else
                                    {
                                        readBuffer[readBufferPosition++] = b;
                                    }
                                }
                            }
                        } 
                        catch (IOException ex) 
                        {
                            stopWorker = true;
                        }
                   }
                }
            });

            workerThread.start();
        }



        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action))
            { myLabel.setText("CONNECTED");}
        }
        void closeBT() throws IOException
    {
        stopWorker = true;
        mmOutputStream.close();
        mmInputStream.close();
        mmSocket.close();
        myLabel.setText("Bluetooth Closed");
    }
        }

【问题讨论】:

    标签: android bluetooth


    【解决方案1】:

    使用如下处理程序传递您的消息:

    public static final int MESSAGE_PROGRESS = 1;
    public static final String TOAST = "toast";
    
    
    Message msg = mHandler.obtainMessage(ConnectThread.MESSAGE_PROGRESS);
    Bundle bundle = new Bundle();
    bundle.putString(ConnectThread.TOAST, progressMessage);
    msg.setData(bundle);
    mHandler.sendMessage(msg);
    

    并在处理程序的帮助下设置文本,例如:

    String data;
    private final Handler mHandler = new Handler() {
    void handleMessage(Message msg) {
    switch (msg.what) {
        case MESSAGE_TOAST:
         if(data = msg.getData().getString(TOAST)) {
            Display.setText(data);
            }
        }
    };
    

    【讨论】:

    • 我在我的代码中应该把上面的代码放在哪里?在哪些方法下?该代码中的任何变量也需要我填写吗?
    • 将第一个 sendMessage(msg) 代码放在您从 inputStream 读取字节的位置。并将处理程序放入您的 Activity 以接收这些消息意味着将第二个代码放在 Activity 的末尾而不是任何方法中..
    • 我应该将 BluetoothMain 更改为什么?
    • 仍然不确定如何添加这些更改并让我的代码编译?
    猜你喜欢
    • 2011-11-09
    • 1970-01-01
    • 1970-01-01
    • 2011-08-19
    • 2023-02-23
    • 1970-01-01
    • 1970-01-01
    • 2015-08-03
    • 1970-01-01
    相关资源
    最近更新 更多