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<BluetoothDevice>
     */
    public Set<BluetoothDevice> getAlreadyPairedBluetoothDeviceList() {

        Set<BluetoothDevice> devices = null;
        if (adapter != null) {
            devices = adapter.getBondedDevices();
            if (devices.size() > 0) {
                for (Iterator<BluetoothDevice> 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<BluetoothDevice> bluetoothDeviceSet = getAlreadyPairedBluetoothDeviceList();
        final List<BluetoothDevice> bluetoothDeviceList = new ArrayList<BluetoothDevice>(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.加入蓝牙和定位权限

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="com.android.launcher.permission.READ_SETTINGS" />
    <uses-permission android:name="com.android.launcher.permission.WRITE_SETTINGS" />
    <uses-permission android:name="com.google.android.launcher.permission.READ_SETTINGS" />
    <uses-permission android:name="com.google.android.launcher.permission.WRITE_SETTINGS" />
    <uses-permission android:name="com.htc.launcher.permission.READ_SETTINGS" />
    <uses-permission android:name="com.htc.launcher.permission.WRITE_SETTINGS" />

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

在这里插入图片描述
在这里插入图片描述

3.2. 初始化类
在这里插入图片描述
3.3.连接蓝牙
ble.showDialog(); 显示已配对蓝牙列表并连接选中的蓝牙
ble.connect(“address”); 直接传入需要连接的蓝牙MAC地址
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值