Android Studio 经典蓝牙实现

目录

一.具体实现

二.我遇到的问题和解决


蓝牙连接分为经典蓝牙和低功耗蓝牙,此篇为经典蓝牙。Android Studio 官方指导文件对于两种蓝牙连接都有详细的讲解。地址为:蓝牙概览  |  Android 开发者  |  Android Developers (google.cn)

一.具体实现

1.向系统获取蓝牙,并判断设备是否支持蓝牙功能。通过 mBluetoothAdapter 对象实现蓝牙的相关功能。

//对象声明
private BluetoothAdapter mBluetoothAdapter;
//蓝牙获取
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
//判断 mBluetoothAdapter 是否获取成功
if (mBluetoothAdapter == null) {
    Log.e(TAG, "onCreate: 此设备不支持蓝牙");
  }

2.判断设备蓝牙是否打开,没有则请求打开蓝牙。

//判断蓝牙是否打开   true为打开
if (!mBluetoothAdapter.isEnabled()) {
    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
   }

3.查询已配对的设备

此功能会获取所有之前设备配对过且没有删除的设备信息。此功能可以快速查看需要连接的设备是否已经处于了已检测到状态,从而可以直接实现连接。

在此方法中可以看到,我是通过动态添加按钮的方式将已连接过的设备信息进行了输出,并对按钮添加了监听事件,从而实现点击选择指定设备进行连接。

 private void checkpairedDevices() {
        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
        LinearLayout layout2=(LinearLayout) findViewById(R.id.myLinearLayout2);
        if (pairedDevices.size() > 0) {
            // There are paired devices. Get the name and address of each paired device.
            for (BluetoothDevice device : pairedDevices) {
                String deviceName = device.getName();
                String deviceHardwareAddress = device.getAddress(); // MAC address
                //将连接过的设备信息输出
                Log.i("已连接过的设备:", deviceName+"---"+deviceHardwareAddress);
                //以下是根据自己的需要对设备信息进行的处理
                Button button=new Button(this);
                button.setText(deviceName+"_: "+deviceHardwareAddress);
                button.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        //点击进行连接
                        connectThread=new ConnectThread(device);
                        connectThread.run();
                    }
                });
                layout2.addView(button);
            }
        }
    }

4.蓝牙扫描

需要注意,蓝牙扫描之前必须开启GPS才能成功扫描,且蓝牙扫描需要注册广播,应用必须针对 ACTION_FOUND Intent 注册一个 BroadcastReceiver,以便接收每台发现的设备的相关信息。

蓝牙扫描实现:

 private void Bluetoothscan() {
        //发现设备,实现扫描功能
        boolean f = mBluetoothAdapter.startDiscovery();
        if (f == true) {
            Log.i(TAG, "成功进行扫描以发现设备");
        } else {
            Log.i(TAG, "扫描失败");
        }
    }

申请打开GPS,申请打开GPS的方法有很多,此处列举我使用过的两种方法:

方法1:

protected void onCreate(Bundle savedInstanceState) {
        //打开GPS的权限申请
        List<String> permissionList = new ArrayList<>();
        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            permissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
        }
        if (!permissionList.isEmpty()) {
            String[] permissions = permissionList.toArray(new String[permissionList.size()]);
            ActivityCompat.requestPermissions(MainActivity.this, permissions, 1);
        }
    ......
}
       

方法2:

public void GPS() {
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        boolean isEnabled = loca
### 如何在 Android Studio 中使用经典蓝牙 API 实现蓝牙通信 #### 权限声明 为了使应用程序能够访问蓝牙硬件,在 `AndroidManifest.xml` 文件中需声明必要的权限。这包括启用蓝牙以及发现其他蓝牙设备所需的权限。 ```xml <uses-permission android:name="android.permission.BLUETOOTH"/> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/> <!-- 需要定位权限来扫描附近设备 --> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> ``` 这些权限允许应用初始化蓝牙适配器、启动设备可见性和执行设备扫描操作[^1]。 #### 获取 BluetoothAdapter 对象 一旦获得了适当的应用程序级权限,下一步是在代码中获取系统的默认 `BluetoothAdapter` 实例: ```java // 初始化蓝牙适配器 final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); mBluetoothAdapter = bluetoothManager.getAdapter(); if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); } ``` 这段代码展示了如何安全地检查当前是否有可用的蓝牙模块,并请求用户开启它如果尚未激活的话[^3]。 #### 创建服务器套接字监听传入连接 对于希望作为服务器端接收来自客户端的数据流的应用来说,可以利用 `listenUsingRfcommWithServiceRecord()` 方法建立一个等待远程设备发起连接的服务记录: ```java private final UUID MY_UUID = UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66"); public synchronized void onCreate() { super.onCreate(); // ... 其他初始化逻辑 ... try { mServerSocket = mAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID); } catch (IOException e) { } } // 接受新连接的方法 public AcceptThread acceptConnection(){ return new AcceptThread(mServerSocket); } ``` 这里定义了一个唯一的UUID用于标识服务,并设置了接受线程以便处理新的连接尝试。 #### 客户端连接到已知地址的设备 当试图主动与其他特定蓝牙设备建立联系时,则应构建相应的客户端部分: ```java public ConnectThread connectToDevice(String address){ BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address); return new ConnectThread(device,MY_UUID); } class ConnectThread extends Thread { private final BluetoothSocket mmSocket; public ConnectThread(BluetoothDevice device, UUID uuid) { BluetoothSocket tmp = null; try { tmp = device.createRfcommSocketToServiceRecord(uuid); } catch (IOException e) {} mmSocket = tmp; } @Override public void run() { mBluetoothAdapter.cancelDiscovery(); // 取消任何正在进行中的搜索 try { mmSocket.connect(); } catch (IOException connectException) { try { mmSocket.close(); } catch (IOException closeException) {} return; } manageConnectedSocket(mmSocket); // 成功后管理会话 } } ``` 此片段说明了怎样通过给定MAC地址找到目标设备并尝试与其建立RFCOMM通道上的链接[^4]。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值