Android -- 蓝牙开发 <一>

来源:互联网 发布:知乎知名大v 编辑:程序博客网 时间:2024/05/16 11:13
关于Android蓝牙的开发
    关于蓝牙,官方文档上面提到可以用来:
          1.扫描其他的蓝牙设备
 2.查询当地的蓝牙适配器,对蓝牙进行配对
 3.建立RFCOMN(串行仿真协议)通道
 4.通过服务发现连接其他设备
 5.和其他设备进行数据传输
 6.管理多个连接
 蓝牙基础:
BlutoothAdapter(蓝牙适配器)  : 所有蓝牙交互的入口点
BluetoothDevice(蓝牙设备) :代表远程蓝牙设备 可以用来连接和查询一些蓝牙设备信息
下来来创建一个蓝牙连接程序
第一步:蓝牙权限(连接蓝牙是需要权限的)
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
第二步:设置蓝牙
获得蓝牙适配器  并且开启蓝牙
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
 //判断设备是否支持蓝牙
if(mBluetoothAdapter == null){
//不支持蓝牙设备
}else{
//支持蓝牙设备
 //如果蓝牙没有开启打开蓝牙
if(!mBluetoothAdapter.isEnabled()){
//通过意图 添加蓝牙适配器动作请求打开
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult();

//暴力打开蓝牙   mBluetoothAdapter.enabled();


}
}
第三步:发现蓝牙设备
通过蓝牙适配器可以搜索到其他远程设备 以及是否配对
查询配对设备
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
//如果存在配对设备
if(pairedDevices.size()>0){
//遍历已经配对的蓝牙设备
for(BlutoothDevice device : pairedDevices){
// 蓝牙名称和蓝牙地址
//device.getName() + "\n" + device.getAddress();
}
}
通过广播接收器来搜索蓝牙设备
  需要注意的是:被搜索的蓝牙要是能够被发现的
因此需要给被搜索的蓝牙设置显示时间
Intent discoverableIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
既然要被搜索的蓝牙已经能搜到了   那么接下来我们就开始搜索吧
//开始搜索蓝牙设备
mBluetoothAdapter.startDiscovery();
//通过广播接收器进行检测
BroadcasrReceiver mReceiver = new BroadcastReceiver(){
public void onReceive(Context context, Intent intent) {
//通过意图得到动作
String action = intent.getAction();
//当动作是蓝牙发现设备的动作时
if(BluetoothDevice.ACTION_FOUND.equals(action)){
//通过意图获得额外的包(额外的蓝牙设备)
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//蓝牙名称和地址
//device.getName() + "\n" + device.getAddress();
}
}
};
还需要注意: 广播接收器是需要注释的:
//创建意图过滤器对象
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
//注册广播
registerReceiver(mReceiver,filter);
0 0
原创粉丝点击