Android 蓝牙2.0工具类

1.加入工具类

/**
 * @anthor GrainRain
 * @funcation 蓝牙2.0工具类
 * @date 2020/7/20
 */
public class BluetoothUtils {

    private BluetoothAdapter adapter;
    private BluetoothSocket bluetoothSocket = null;
    private static final UUID bluetoothUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    private OutputStream outputStream = null;
    private InputStream inputStream = null;

    private Context context;
    private boolean isConnection = false;
    private MessageCallback callback;

    public BluetoothUtils(Context mContext, MessageCallback mCallback) {
        context = mContext;
        openBluetooth();
        registerBoradcastReceiver();
        callback = mCallback;

        if (adapter == null) {
            adapter = BluetoothAdapter.getDefaultAdapter();
        }
    }

    /**
     * 连接蓝牙
     **/
    @SuppressLint("StaticFieldLeak")
    public void connect(final String address) {

        new AsyncTask() {
            @Override
            protected String doInBackground(Object[] params) {

                try {
                    BluetoothDevice device = adapter.getRemoteDevice(address);
                    bluetoothSocket = device.createRfcommSocketToServiceRecord(bluetoothUUID);
                    adapter.cancelDiscovery();

                    bluetoothSocket.connect();
                    outputStream = bluetoothSocket.getOutputStream();
                    inputStream = bluetoothSocket.getInputStream();

                    while (true) {
                        byte[] data = new byte[500];
                        int count = inputStream.read(data);

                        int[] data_int = new int[data.length];
                        for (int i = 0; i < data.length; i++) {
                            data_int[i] = (byte) (data[i] & 0xff);
                        }

                        if(callback != null) {
                            callback.bluttoothMessage(data_int);
                        }
                    }
                } catch (Exception e) {
                    L.e(e);
                }
                return null;
            }

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
            }

            @Override
            protected void onPostExecute(Object o) {
                super.onPostExecute(o);
            }
        }.execute();
    }

    /**
     * 获取已配对的蓝牙列表
     *
     * @return Set
     */
    public Set getAlreadyPairedBluetoothDeviceList() {

        Set devices = null;
        if (adapter != null) {
            devices = adapter.getBondedDevices();
            if (devices.size() > 0) {
                for (Iterator it = devices.iterator(); it.hasNext(); ) {
                    BluetoothDevice device = (BluetoothDevice) it.next();
                    L.e(device.getName() + " " + device.getAddress());
                }
            } else {
                L.e("没有已配对的蓝牙设备");
            }
        }
        return devices;
    }

    /**
     * 发送数据
     *
     * @param message
     */
    public void sendMessage(String message) {
        sendMessage(message.getBytes());
    }

    /**
     * 发送数据
     *
     * @param message
     */
    public void sendMessage(byte[] message) {
        try {
            outputStream.write(message);
            outputStream = bluetoothSocket.getOutputStream();
            inputStream = bluetoothSocket.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 打开蓝牙
     */
    public void openBluetooth() {
        if (adapter != null) {
            if (!adapter.isEnabled()) {
                Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                context.startActivity(intent);
            }
        }
    }

    /**
     * 显示蓝牙列表对话框
     */
    public void showDialog() {

        final Set bluetoothDeviceSet = getAlreadyPairedBluetoothDeviceList();
        final List bluetoothDeviceList = new ArrayList(bluetoothDeviceSet);
        final String[] items = new String[bluetoothDeviceSet.size()];

        for (int i = 0; i < bluetoothDeviceList.size(); i++) {
            items[i] = bluetoothDeviceList.get(i).getName() + " " + bluetoothDeviceList.get(i).getAddress();
        }

        AlertDialog.Builder listDialog = new AlertDialog.Builder(context);
        listDialog.setTitle("已配对蓝牙列表");
        listDialog.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                connect(bluetoothDeviceList.get(which).getAddress());
                toast.show(bluetoothDeviceList.get(which).getName() + " " + bluetoothDeviceList.get(which).getAddress());
            }
        });
        listDialog.show();
    }

    /**
     * 判断蓝牙是否连接
     */
    public boolean isConnection() {
//        int a2dp = adapter.getProfileConnectionState(BluetoothProfile.A2DP);
//        int headset = adapter.getProfileConnectionState(BluetoothProfile.HEADSET);
//        int health = adapter.getProfileConnectionState(BluetoothProfile.HEALTH);
//        return adapter != null && (a2dp == BluetoothAdapter.STATE_CONNECTED ||
//                headset == BluetoothAdapter.STATE_CONNECTED ||
//                health == BluetoothAdapter.STATE_CONNECTED);
        return isConnection;
    }

    //注册监听蓝牙连接状态
    private void registerBoradcastReceiver() {
        IntentFilter stateChangeFilter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
        IntentFilter connectedFilter = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED);
        IntentFilter disConnectedFilter = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED);
        context.registerReceiver(stateChangeReceiver, stateChangeFilter);
        context.registerReceiver(stateChangeReceiver, connectedFilter);
        context.registerReceiver(stateChangeReceiver, disConnectedFilter);
    }

    //蓝牙状态回调
    private BroadcastReceiver stateChangeReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(BluetoothDevice.ACTION_ACL_CONNECTED)) {
                toast.show("蓝牙已连接");
                isConnection = true;
            } else if (action.equals(BluetoothDevice.ACTION_ACL_DISCONNECTED)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                String name = device.getName();
                toast.show("蓝牙已断开");
                isConnection = false;
            }
        }
    };

    public interface MessageCallback {
        void bluttoothMessage(int[] data);
    }
}

2.加入蓝牙和定位权限

    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    

3.使用
3.1.继承和实现蓝牙信息回调接口
implements BluetoothUtils.MessageCallback

Android 蓝牙2.0工具类_第1张图片
Android 蓝牙2.0工具类_第2张图片

3.2. 初始化类
Android 蓝牙2.0工具类_第3张图片
3.3.连接蓝牙
ble.showDialog(); 显示已配对蓝牙列表并连接选中的蓝牙
ble.connect(“address”); 直接传入需要连接的蓝牙MAC地址
Android 蓝牙2.0工具类_第4张图片

你可能感兴趣的:(Android,android,蓝牙)