deviceList.add(bluetoothDevice);
list.setAdapter(new MyAdapter(MainActivity.this, deviceList));
}
}
};
此时我们已经通过上述三个api实现了扫描并生成设备列表的过程,那么理所当然,我们要对列表中的设备进行连接,那么我们就需要用到BluetoothDevice中的connectGatt方法,这个方法与对应的设备连接后可以得到一个BluetoothGatt对象
这里说明connectGatt方法包含三个参数
-
Context上下文
-
autoConnect是否自动重连(Boolean)
-
BluetoothGattCallback 回调方法
BluetoothGatt:实现蓝牙的基本功能,可以重新连接蓝牙设备,发现蓝牙设备的 Service。
BluetoothGattCallback :里面有许多方法,对应着各种操作的回调(比如读写操作以及获取服务),我们按照需要实现即可
BluetoothGattService :通过BluetoothGatt可以得到,对应上文提到的Service,通过这个类我们可以得到所需要的characteristic
==================================================================
了解了以上内容以后,我们就做一个简单的安卓应用,连接上测试用的小米手环。
安卓的蓝牙开发必然要用到真机调试,这里就简单的说明一下,如果真机连接不上可以在网上查找对应的解决办法
1.进入手机的(更多设置中)开发者选项(这里以小米为例,进入设置,在我的设备中找到全部参数,连点MIUI版本处看到下方提示进入开发者选项即可),打开USB调试以及USB安装即可
2.打开andorid studio,将数据线连接上手机,就进入了真机调试。
1.在Manifest文件中添加
这里需要添加以上权限,否则会导致闪退
2.如果程序正常运行,但是扫描不到任何的设备,打开手机,进入手机权限管理,给安装的app定位权限设置为允许,同时保证手机中的位置信息是打开的,这步非常重要,旧版本的安卓系统可以略过,本机为andorid 10版本,如果不操作这步将不能看到任何设备
扫描设备主界面
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android=“http://schemas.android.com/apk/res/android”
xmlns:tools=“http://schemas.android.com/tools”
android:layout_width=“match_parent”
android:layout_height=“match_parent”
android:orientation=“vertical”
tools:context=“com.example.blue_test.MainActivity”>>
<Button
android:id=“@+id/Search_device”
android:layout_width=“match_parent”
android:layout_height=“wrap_content”
android:text=“扫描设备”/>
<TextView
android:id=“@+id/Connection_Status”
android:layout_width=“match_parent”
android:layout_height=“wrap_content”
android:text=“连接状态:未连接”
android:gravity=“center”
android:textSize=“20dp”/>
<ListView
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:id=“@+id/list”
/>
实现效果:
扫描设备信息界面
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout
xmlns:android=“http://schemas.android.com/apk/res/android”
xmlns:app=“http://schemas.android.com/apk/r