Android为蓝牙技术提供了4个工具类,分别是蓝牙适配器BluetoothAdapter、蓝牙设备BluetoothDevice、蓝牙服务端套接字BluetoothServerSocket和蓝牙客户端套接字BluetoothSocket。
手动搭建蓝牙客户端和服务端完成蓝牙通信:
客户端:
第一步:声明蓝牙获取权限和弱定位权限,在AndroidManifest中加入:
<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"/>
弱定位权限属于危险权限,还需要在Java代码中进行动态获取权限。
第二步:获取到权限后,通过BluetoothAdapter bTAdatper= BluetoothAdapter.getDefaultAdapter();获取蓝牙适配器,不支持蓝牙时会返回null。
第三步:注册广播监听蓝牙获取状态,我们需要三个状态:BluetoothDevice.ACTION_FOUND,每搜索到一个蓝牙设配会发出一个这个广播;
BluetoothAdapter.ACTION_DISCOVERY_STARTED,开始搜索时会发出这个广播;BluetoothAdapter.ACTION_DISCOVERY_FINISHED,搜索完毕时会发出这个广播。
第四步:打开蓝牙,bTAdatper.enable(),(关闭蓝牙,bTAdatper.disable())。设置可被发现的时间:
if(bTAdatper.getScanMode()!=BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE){
Intent intent=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,0);//0为可被发现的时间,0为一直
startActivity(intent);
}
第五步:搜索蓝牙,bTAdatper.startDiscovery()//开始搜索;
bTAdatper.isDiscovering()//正在搜索,返回Boolean值;
bTAdatper.cancelDiscovery()//停止搜索
第六步:获取已配对设备,bTAdatper.getBondedDevices(),已配对多少设备就会返回多少设备。
第七步:连接蓝牙设备,这里我们互连的是蓝牙客户端和服务端,他们之间通信类似于socket,只是客户端使用的是BluetoothSocket,服务端使用的是BluetoothServerSocket,同socket一样,需要地址和端口号,蓝牙的地址就相当于socket中的IP地址,自定义的UUID(全局唯一标识符)就相当于socket的端口。创建客户端蓝牙Socket:
BluetoothSocket bTsocket = device. createRfcommSocketToServiceRecord(BT_UUID)
创建后像socket一样通过connect发起连接,连接成功后再获取输出流就可以往里面写东西传给服务端了,由于蓝牙连接也是耗时操作,所以我们需要把连接操作写到新建的连接线程中去执行。