android Bluetooth蓝牙开发

    xiaoxiao2021-03-25  81

    1,添加蓝牙需要的权限

    <uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

    2.蓝牙的初始化工作

    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (mBluetoothAdapter == null) { Toast.makeText(mApplicationContext, "没有蓝牙设备,请到设置连接蓝牙!", Toast.LENGTH_LONG).show(); } else { if (mBluetoothAdapter.isEnabled()) { mBluetoothControl.init(); } else { Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); context.startActivityForResult(intent, 100); } }

    3.注册相关的广播

    IntentFilter intent = new IntentFilter(); intent.addAction(BluetoothDevice.ACTION_FOUND);//搜索发现设备 intent.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);//搜索发现设备 intent.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);//搜索发现设备 intent.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);//状态改变 intent.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);//行动扫描模式改变了 intent.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);//动作状态发生了变化 activity.registerReceiver(mReciever, intent);

    4,监听广播

    @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); BluetoothDevice device; if (action.equals(BluetoothDevice.ACTION_FOUND)) { device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); if (mBltDeviceCallback != null) { mBltDeviceCallback.onBltFound(device); } } else if (action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)) { device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); switch (device.getBondState()) { case BluetoothDevice.BOND_BONDING://正在配对 LoggerUtils.d("BlueToothTestActivity", "正在配对......"); mBltDeviceCallback.onBltPairing(device); break; case BluetoothDevice.BOND_BONDED://配对结束 LoggerUtils.d("BlueToothTestActivity", "完成配对"); mBltDeviceCallback.onBltPairedComplete(device); break; case BluetoothDevice.BOND_NONE://取消配对/未配对 LoggerUtils.d("BlueToothTestActivity", "取消配对"); mBltDeviceCallback.onBltPairFail(device); default: break; } } }

    5,扫描

    if (!mBluetoothAdapter.isDiscovering()) {//是否正在扫描 mBluetoothAdapter.startDiscovery(); // mBluetoothAdapter.cancelDiscovery(); } 6.检测相关权限(android6.0手动添加)

    public void checkPermission() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // Android M Permission check if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1); } else { mBluetoothAdapter.startDiscovery(); } } else { mBluetoothAdapter.startDiscovery(); } } //权限申请回调 switch (requestCode) { case 1000: if (resultCode == RESULT_OK) { mBluetoothAdapter.startDiscovery(); } break; }

    7,创建服务端的socket

    if (serverSocket == null) { serverSocket = mBluetoothAdapter.listenUsingRfcommWithServiceRecord("com.booyue.blzdemo", DUUID); Log.d(TAG, "run: " + "服务端 serverSocket create"); } mBluetoothSocket = serverSocket.accept(); SerIs = mBluetoothSocket.getInputStream(); serOs = mBluetoothSocket.getOutputStream();

    8,客户端socket进行连接

    if (getBluetoothAdapter().isDiscovering()) //停止搜索 getBluetoothAdapter().cancelDiscovery(); //如果当前socket处于非连接状态则调用连接 //通过和服务器协商的uuid来进行连接 if (mBluetoothSocket != null) { //通过反射得到bltSocket对象,与uuid进行连接得到的结果一样,但这里不提倡用反射的方法 //mBluetoothSocket = (BluetoothSocket) btDev.getClass().getMethod("createRfcommSocket", new Class[]{int.class}).invoke(btDev, 1); Log.d(TAG, "开始连接..."); } else { mBluetoothSocket = btDev.createRfcommSocketToServiceRecord(DUUID); //全局只有一个bluetooth,所以我们可以将这个socket对象保存在appliaction中 if (!mBluetoothSocket.isConnected()) { //你应当确保在调用connect()时设备没有执行搜索设备的操作。 // 如果搜索设备也在同时进行,那么将会显著地降低连接速率,并很大程度上会连接失败。 mBluetoothSocket.connect(); } serOs = mBluetoothSocket.getOutputStream(); SerIs = mBluetoothSocket.getInputStream(); }

    9,创建配对

    public void createBond(BluetoothDevice btDev, Handler handler) { if (btDev.getBondState() == BluetoothDevice.BOND_NONE) { //如果这个设备取消了配对,则尝试配对 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { btDev.createBond(); } } else if (btDev.getBondState() == BluetoothDevice.BOND_BONDED) { //如果这个设备已经配对完成,则尝试连接 mSocketThread.connect(btDev, handler); } }
    转载请注明原文地址: https://ju.6miu.com/read-22933.html

    最新回复(0)