連接 藍牙HC - 05 模塊 讀寫操作

連接 藍牙HC - 05 模塊 進行讀寫操作


1. 開啓藍牙進行連接

    //藍牙
    private BluetoothAdapter bluetoothAdapter;
    private Set<BluetoothDevice> pairedDevices;
    private static UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    
    private OutputStream mmOutStream;
    private InputStream mmInStream;
    private BluetoothSocket mmSocket;
    private byte[] mmBuffer; // mmBuffer store for the stream
 //建立藍牙連接
    public void on() {
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        mmSocket = null;

        if (!bluetoothAdapter.isEnabled()) {
            Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(turnOn, 0);
            Toast.makeText(getApplicationContext(), "Turned on", Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(getApplicationContext(), "Already on", Toast.LENGTH_LONG).show();
        }
    }

2. 建立sockat通道

 
        try {
            String name = "CONNECTED";
            byte[] bytes = name.getBytes();
            mmOutStream.write(bytes);
        } catch (IOException e) {
            Toast.makeText(getApplicationContext(), "Connecting...", Toast.LENGTH_LONG).show();
            connector();
        }
  

connector方法


    /**
     * 初始化文件流 開啓Socket連接
     */
    public void connector() {

        OutputStream tmpOut = null;
        InputStream tmpIn = null;

        // Get list of paired devices

        BluetoothSocket tmp = null;

        String dname;


        pairedDevices = bluetoothAdapter.getBondedDevices();
        BluetoothDevice device = null;
        if (pairedDevices.size() > 0) {
            for (BluetoothDevice bt : pairedDevices) {
                Log.d("TAG name", "已連接:" + bt.getName());
                dname = bt.getName();
                if (dname.equals("HC-05")) {
                    textinfo1.setText("設備名:" + dname);
                    textinfo2.setText("地址:" + bt.getAddress());
                    device = bt;
                    Log.d("TAG", "HC-05設備已讀取到!!!");
                    Toast.makeText(getApplicationContext(), "HC-05設備已讀取到!!!" + device.getName(), Toast.LENGTH_LONG).show();
                } else {
                    Log.d("TAG", "HC-05 設備未讀取到");
                }

            }

            try {
                // MY_UUID is the app's UUID string, also used by the client code.
                tmp = device.createRfcommSocketToServiceRecord(MY_UUID);

            } catch (IOException e) {
                Log.d("TAG", "Socket's listen() method failed", e);
                Toast.makeText(getApplicationContext(), "Error 1 Socket連接失敗", Toast.LENGTH_LONG).show();
            }
            mmSocket = tmp;

            bluetoothAdapter.cancelDiscovery();

            try {
                // Connect to the remote device through the socket. This call blocks
                // until it succeeds or throws an exception.
                mmSocket.connect();

                Log.d("TAG", "Socket connected!!!!!");
                Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_LONG).show();
            } catch (IOException connectException) {

            }

            try {
                tmpIn = mmSocket.getInputStream();
            } catch (IOException e) {
                Log.e(TAG, "Error occurred when creating input stream", e);
            }


            try {
                tmpOut = mmSocket.getOutputStream();
            } catch (IOException e) {
                Log.e(TAG, "Error occurred when creating output stream", e);
                Toast.makeText(getApplicationContext(), "Error 2", Toast.LENGTH_LONG).show();
            }

            mmOutStream = tmpOut;
            mmInStream = tmpIn;


        } else {
            Log.d("TAG", "No devices");
            Toast.makeText(getApplicationContext(), "HC-05 is not pared", Toast.LENGTH_LONG).show();
        }


    }

3. 寫入數據

/**
     * 寫入數據
     *
     * @param v
     */
    public void write(View v) {

        String name =“要發送的數據”; 
        byte[] bytes = name.getBytes();
        Log.e("TAG", "bytes : " + name);
        try {
            mmOutStream.write(bytes);
        } catch (IOException e) {
            e.printStackTrace();
             Toast.makeText(getApplicationContext(), "發送失敗", Toast.LENGTH_LONG).show();
        }

    }

4. 接受數據

/**
     * 接受數據
     */
    Thread th = new Thread(new Runnable() {
        public void run() {


            mmBuffer = new byte[4096];
            int numBytes;

             while (true) {
                try {
                    if (mmInStream.available() > 2) {
                        Log.d("TAG", "數據正常:" + "mmInStream.available()>2 ");
                        // Read from the InputStream.
                        numBytes = mmInStream.read(mmBuffer);

                        final String readMessage = new String(mmBuffer, 0, numBytes);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                textViewInfo.setText(readMessage);
                            }
                        });
                        Log.d("TAG", "readMessage:" + readMessage);
                    } else {
                        SystemClock.sleep(100);
                        Log.d("TAG", "No Data");
                    }

                } catch (IOException e) {
                    Log.d("TAG", "連接中斷,流斷開", e);
                    break;
                }
            }

        }
    });


5. 關閉連接

    public void off(View v) {
        bluetoothAdapter.disable();
        Toast.makeText(getApplicationContext(), "關閉連接", Toast.LENGTH_LONG).show();
    }

PS:藍牙權限自己處理

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章