蓝牙,英文叫BlueTooth,是近距离无线通讯的标准,它的命名是有个故事:传说瑞典有个国王特别爱吃蓝莓导致自己的牙齿天天都是蓝色的,在他执政期间这位国王非常善于交际,能说会到,和邻国的搞得关系非常好,这个Bluetooth的发明者觉得蓝牙它的作用就是在近距离沟通周围的设备,跟这个国王很类似,于是起名叫蓝牙。
在大部分的编程工作中,蓝牙这个东西一般是接触不到的,但是作为了解可以快速的看一遍。
蓝牙是主要针对10m范围的短距离通信,两个设备通过蓝牙通讯必须都有蓝牙适配器,蓝牙模块有最重要的两个API:BlueToothAdapter 、 BlueToothDevice;和不是最重要的:
BluetoothSocket 、BluetoothServerSocket。
要使用蓝牙的功能,相关的权限申请有:
<uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> <uses-permission android:name="android.permission.BLUETOOTH_PRIVILEGED" />第一个是使用蓝牙的权限;
第二个是需要扫描设备或者操作蓝牙设置,要申请的权限;
第三个是允许设备不经过用户操作自动配对,但这个权限并不能授权给第三方程序。
首先是打开蓝牙的步骤:1. 获取蓝牙适配器对象;2. 判断是否开启蓝牙;3. 没有开启则发送intent开启并请求返回值;4. 判断返回是否成功开启蓝牙。
在onCreate方法中:
BluetoothAdapter mBlueToothAdapter = BluetoothAdapter.getDefaultAdapter(); if (mBlueToothAdapter == null) { Toast.makeText(this, "no BLUETOOTH device", Toast.LENGTH_SHORT).show(); finish(); } else { // 如果没有开启,开启 if (!mBlueToothAdapter.isEnabled()) { Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(intent, 1); } }然后在:
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == 1) { if (resultCode == RESULT_OK) { Toast.makeText(this,"blue tooth is open",Toast.LENGTH_SHORT).show(); } else if (resultCode == RESULT_CANCELED) { Toast.makeText(this,"blue tooth is canceled",Toast.LENGTH_SHORT).show(); finish(); } } }这样OK
然后我们需要搜索周围的蓝牙设备:
思路是:1. 根据上面,已经获取了蓝牙对象,可以使用 getBoundedDevices() 来获取已绑定设备的列表;2. 搜索周围的设备,startDiscovery(),这个是异步的方法,会搜索12秒;3. 搜到的设备都是通过广播来得到,系统发送ACTION_FOUND(设备找到),获取这个intent,其中包括两个extra fields:EXTRA_DEVICE和EXTRA_CLASS。BluetoothDevice中的EXTRA_DEVICE就是我们搜索到的设备对象。 确认搜索到设备后,我们可以从得到的BluetoothDevice对象中获得设备的名称和地址。
于是:
写接收者:
BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(BluetoothDevice.ACTION_FOUND)) { BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); if (device.getBondState() != BluetoothDevice.BOND_BONDED) { mTv.append(device.getName() + ":" + device.getAddress() + "\n"); } } else if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) { setProgressBarIndeterminateVisibility(false); setTitle("搜索蓝牙设备"); } } };开始搜索并注册广播:
mBlueToothAdapter.startDiscovery(); IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); registerReceiver(receiver, filter);
而且不要忘了,连接设备之前要停止搜索,否则连接会非常慢并容易失败。
然后是建立连接,要通过BlueToothSocket建立,设备与设备之间有UUID作为标识,服务端和客户端的UUID必须是一样的。这里连接不做赘述。