Android蓝牙扫描/连接/收发数据

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_40391500/article/details/88813349
/**
 * 蓝牙工具类
 */
public class BlueToothUtils {
    private final String TAG = this.getClass().getSimpleName();
    private static BlueToothUtils utils = null;

    private BluetoothAdapter bluetoothAdapter;
    private final UUID SPP_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    private Executor executor;
    //当前链接蓝牙
    private static BluetoothSocket mSocket;

    private ArrayList<BluetoothDevice> deviceList = new ArrayList<>();//扫描到的远程蓝牙设备

    private Handler handler;

    public static BluetoothDevice mDevice = null;

    private boolean enabled = false;//蓝牙是否可用
    private final int SCANTIME = 5*1000;//扫描时间
    private final int requestCode = 2002;//


    public static BlueToothUtils getInstance(){
        if (utils == null){
            synchronized (BlueToothUtils.class){
                if (utils == null){
                    utils = new BlueToothUtils();
                }
            }
        }
        return utils;
    }

    /**
     * 判断是否打开蓝牙
     * 没有就静默打开
     */
    public void isOpen(Handler mHandler){
        handler = mHandler;
        ReceiveUtils.getInstance().setListener(listener);
        BluetoothManager bluetoothManager = (BluetoothManager) MyApplication.context.getSystemService(Context.BLUETOOTH_SERVICE);
        bluetoothAdapter = bluetoothManager.getAdapter(); // null:表示不支持蓝牙
        if (bluetoothAdapter == null){
            return;
        }
        connetGatt();
    }

    /**
     * 链接已配对蓝牙设备
     */
    public void connetGatt(){
        if (bluetoothAdapter != null){
            // true:处于打开状态, false:处于关闭状态
            enabled = bluetoothAdapter.isEnabled();
            if (!enabled){
                MyApplication.activity.startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE),
                        requestCode);
            }else {//获取已配对蓝牙
                Set<BluetoothDevice> devicesSet = bluetoothAdapter.getBondedDevices();
                deviceList.clear();
                for (BluetoothDevice device : devicesSet) {
                    deviceList.add(device);
                    if (handler != null){
                        handler.sendEmptyMessage(BluetoothActivity.SCAN_SUCC);
                    }
//                    LogUtils.log(TAG,"已配对蓝牙" + device.getName());
                    String connetAddress = (String) SPUtils.get(MyApplication.context, SPUtils.BLUETOOTH_ADDRESS, "");
                    if (device.getAddress().equals(connetAddress)){
                        if (bluetoothAdapter.isDiscovering()){
                            scanning(false);
                        }
                        LogUtils.log(TAG,"已配对蓝牙" + device.getName());
                        connet(device);
                    }
                }
            }
        }
    }

    /**
     * 扫描设备
     */
    public void scanning(boolean enable){
        if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()){
            if (handler != null){
                handler.sendEmptyMessage(BluetoothActivity.SCAN_OPEN);
            }
            return;
        }
        if (bluetoothAdapter != null){
            if (enable){
                if (handler != null){
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            bluetoothAdapter.cancelDiscovery();
                            handler.sendEmptyMessage(BluetoothActivity.SCAN_CLOSE);
                            LogUtils.log("BlueToothUtils", "停止扫描设备");
                        }
                    }, SCANTIME);
                }
                deviceList.clear();
                connetGatt();
                // 寻找蓝牙设备,android会将查找到的设备以广播形式发出去
                this.bluetoothAdapter.startDiscovery();
                LogUtils.log("BlueToothUtils", "开始扫描设备");
            }else {
                if (handler != null){
                    handler.removeCallbacksAndMessages(null);
                    handler.sendEmptyMessage(BluetoothActivity.SCAN_CLOSE);
                }
                bluetoothAdapter.cancelDiscovery();
                LogUtils.log("BlueToothUtils", "停止扫描设备");
            }
        }
    }

    /**
     * 注册广播
     */
    public void initIntentFilter() {
        // 设置广播信息过滤
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
        intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        // 注册广播接收器,接收并处理搜索结果
        MyApplication.context.registerReceiver(receiver, intentFilter);

    }

    /**
     * 销毁广播
     */
    public void unregisterReceiver() {
        MyApplication.context.unregisterReceiver(receiver);
    }

    /**
     * 蓝牙广播接收器
     */
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//                LogUtils.log(TAG,"搜索到蓝牙设备名称:" + device.getName());
//                LogUtils.log(TAG,"搜索到蓝牙设备地址:" + device.getAddress());
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                    deviceList.add(device);
                    if (handler != null){
                        handler.sendEmptyMessage(BluetoothActivity.SCAN_SUCC);
                    }
                }
            } else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
                LogUtils.log(TAG,"搜索蓝牙设备中...");

            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                LogUtils.log(TAG,"设备搜索完毕");
                if (handler != null){
                    handler.sendEmptyMessage(BluetoothActivity.SCAN_SUCC);
                }
                // bluetoothAdapter.cancelDiscovery();
            }
            if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
                if (bluetoothAdapter == null) return;
                if (bluetoothAdapter.getState() == BluetoothAdapter.STATE_ON) {
                    LogUtils.log(TAG,"打开蓝牙");
                    enabled = bluetoothAdapter.isEnabled();
                    connetGatt();
                } else if (bluetoothAdapter.getState() == BluetoothAdapter.STATE_OFF) {
                    LogUtils.log(TAG,"关闭蓝牙");
                }
            }
        }

    };

    /**
     * 选择链接蓝牙设备
     */
    public void connet(BluetoothDevice device){
        if (bluetoothAdapter != null && device != null){
            close();
            LogUtils.log(TAG,"开始连接蓝牙--" + device.getName());
            try {
//             final BluetoothSocket socket = dev.createRfcommSocketToServiceRecord(SPP_UUID); //加密传输,Android系统强制配对,弹窗显示配对码
                final BluetoothSocket socket = device.createInsecureRfcommSocketToServiceRecord(SPP_UUID); //明文传输(不安全),无需配对
                executor = Executors.newCachedThreadPool();
                // 开启子线程
                executor.execute(new Runnable() {
                    @Override
                    public void run() {
                        mSocket = socket;
                        mDevice = mSocket.getRemoteDevice();
                        receiveDate(mSocket); //循环读取
                    }
                });
            } catch (Throwable e) {
                close();
            }
        }
    }

    /**
     * 发送数据
     * 
     */
    public void sendData(byte[] by) {
        if (!isConnected(null)){
//            LogUtils.log(TAG, "请先打开蓝牙");
            return;
        }
       if (null != outputStream) {
                outputStream.write(by, 0, by.len);
                LogUtils.log( "SerialPortThread--发送数据");
	    } else {
	         LogUtils.log("SerialPortUtils", "蓝牙通讯失败");
		}
    }

    /**
     * 当前设备与指定设备是否连接
     */
    public boolean isConnected(BluetoothDevice dev) {
        boolean connected = (mSocket != null && mSocket.isConnected());
        if (dev == null)
            return connected;
        return connected && mSocket.getRemoteDevice().equals(dev);
    }

    /**
     * 关闭链接蓝牙设备
     */
    public void cancle(){
        try {
            if (bluetoothAdapter != null){
                bluetoothAdapter.cancelDiscovery();
                bluetoothAdapter.disable();
                bluetoothAdapter = null;
            }
            if (mSocket != null){
                mSocket.close();
            }
            ReceiveUtils.getInstance().close();
//            unregisterReceiver();
            utils = null;
        }catch (Exception e){
            e.printStackTrace();
        }
    }


	public void receiveDate(BluetoothSocket socket){
        try {
            mSocket = socket;
            if (!mSocket.isConnected()){
                mSocket.connect();
            }
            LogUtils.log(TAG, "连接蓝牙成功--" + mSocket.getRemoteDevice().getName());
            outputStream = new DataOutputStream(mSocket.getOutputStream());
            DataInputStream in = new DataInputStream(mSocket.getInputStream());
            int size = 0;
            byte[] buffer;
            isExit = false;
            while (!isExit){
                buffer = new byte[DATA_MAX_LEN];
                if (in != null) {
                    size = in.read(buffer);
                    if (size > 0) {
                        checkData(buffer, size);//处理数据
                    }
                }
                Thread.sleep(10);
            }
        }catch (Exception e){
            LogUtils.log(TAG, "蓝牙连接失败" + e.getMessage());
            close();
            e.printStackTrace();
        }
    }
	 
	 /**
     * 关闭Socket连接
     */
    public void close() {
        try {
            Log.e("-----------", "关闭Socket连接:");
            isExit = true;
            if (mSocket != null){
                mSocket.close();
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_40391500/article/details/88813349