关于蓝牙,我们首先要了解什么是蓝牙?
蓝牙
蓝牙是一种近距离的无线传输技术,由爱立信公司在1994年创立,现在由Bluetooth SIG管理和制订。蓝牙用于在不同设备之间建立连接,采用短波长通讯,ISM频段在2.4-2.485GHz。
在使用范围方面,其实根据CLASS级别的不同,现在的蓝牙理论上已经可以达到100米,而蓝牙5.0更达到243.84米,但考虑到电力消耗和受环境因素影响,一般常见的移动设备上蓝牙传输范围仍在10米左右。
Android 平台包含蓝牙网络堆栈支持,此支持能让设备以无线方式与其他蓝牙设备交换数据。应用框架提供通过 Android Bluetooth API 访问蓝牙功能的权限。这些 API 允许应用以无线方式连接到其他蓝牙设备,从而实现点到点和多点无线功能。
设置蓝牙
-
获取
if (!bluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); }
-
启用蓝牙。
if (!bluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); }
查找设备
Set pairedDevices = bluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) { for (BluetoothDevice device : pairedDevices) {
String deviceName = device.getName();
String deviceHardwareAddress = device.getAddress(); } }
发现设备
@Override protected void onCreate(Bundle savedInstanceState) {
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(receiver, filter); }
private final BroadcastReceiver receiver = 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);
String deviceName = device.getName();
String deviceHardwareAddress = device.getAddress(); } } };
@Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(receiver); }
连接设备
private class AcceptThread extends Thread {
private final BluetoothServerSocket mmServerSocket;
public AcceptThread() { BluetoothServerSocket tmp = null;
try { tmp = bluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
} catch (IOException e) {
Log.e(TAG, "Socket's listen() method failed", e);
}
mmServerSocket = tmp;
}
public void run() {
BluetoothSocket socket = null; while (true) {
try {
socket = mmServerSocket.accept();
} catch (IOException e) {
Log.e(TAG, "Socket's accept() method failed", e);
break; }
if (socket != null) {
manageMyConnectedSocket(socket);
mmServerSocket.close();
break; } } }
public void cancel() {
try {
mmServerSocket.close();
} catch (IOException e) {
Log.e(TAG, "Could not close the connect socket", e); } } }
最后就是进行真机测试,将蓝牙之间连接通信 ,然后查看。