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();
    }
发布了20 篇原创文章 · 获赞 4 · 访问量 890

猜你喜欢

转载自blog.csdn.net/v1141261428/article/details/100547858