Android Studio 2 - 6 藍牙

藍牙功能

打開藍牙

private void open() {
        Intent intent = new Intent();
        intent.setAction(BluetoothAdapter.ACTION_REQUEST_ENABLE);//使可用
        intent.setAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);//能夠被掃描
        startActivityForResult(intent, 200);

    }

關閉藍牙

private void close() {
        bluetoothAdapter.disable();//停止使用
    }

搜索附近藍牙

private void search() {
        bluetoothDeviceList_left.clear();
        Toast.makeText(this, "開始搜索", Toast.LENGTH_SHORT).show();
        bluetoothAdapter.startDiscovery();
    }

配對藍牙發送數據

private void show() {
        bluetoothDeviceList_right.clear();
        Toast.makeText(this, "顯示已配對", Toast.LENGTH_SHORT).show();
        Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices();

        bluetoothDeviceList_right.addAll(bondedDevices);
        myBlueAdapter_right.notifyDataSetChanged();
    }

其餘的部分

private void Servicess() {
        Log.i(TAG, "Servicess: ");
        Toast.makeText(this, "開啓服務", Toast.LENGTH_SHORT).show();
        //主線程中不能死循環 否者會卡死
        new Thread(new Runnable() {
            @Override
            public void run() {
                //開啓服務端 接收客戶端的連接
                try {
                    //通過本機藍牙設備得到ServerSocket
                    //參數一 本機藍牙設備的名字 參數二 uuid  listenUsingInsecureRfcommWithServiceRecord
//                    BluetoothServerSocket serverSocket = bluetoothAdapter.listenUsingRfcommWithServiceRecord(bluetoothAdapter.getName(), uuid);
                    BluetoothServerSocket serverSocket = bluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord(bluetoothAdapter.getName(), uuid);
                    Log.i(TAG, "run: 進入線程");
                    while (true){
                        Log.i(TAG, "run: 進入死循環");
                        BluetoothSocket socket = serverSocket.accept();//客戶端

                        Message obtain = Message.obtain();
                        obtain.what = 101;
                        obtain.obj = socket.getRemoteDevice().getName();
                        handler.sendMessage(obtain);

                        new ServiceThread(socket,handler).start();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章