Android中的蓝牙

蓝牙
蓝牙主要针对短距离设备通信(10米以内)
android.bluetooth包中
1.BluetoothAdapter:代表本地的蓝牙适配器
2.BluetoothDevice:代表一个远程的Bluetooth设备


1.
在AndroidManifest.xml声明蓝牙权限:
<uses-permission android:name="android.permission.BLUETOOTH"/>

2.一般过程
(1)获得BluetoothAdapter对象;
(2)判断当前设备是否拥有蓝牙设备;
(3)判断当前设备中的蓝牙设备是否已经打开;

(4)得到所有已经配对的蓝牙设备对象;

//获得本地适配器对象
			BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
			//是否有蓝牙设备
			if (adapter != null) {
				System.out.println("get a bluetooth!");
				//打开蓝牙设备
				if (!adapter.isEnabled()) {
					Intent intent = new Intent(
							BluetoothAdapter.ACTION_REQUEST_ENABLE);
					startActivity(intent);
				}
				Set<BluetoothDevice> devices = adapter.getBondedDevices();
				//获得已绑定的设备
				if(devices.size()>0){
					for (BluetoothDevice bluetoothDevice : devices) {
						System.out.println(bluetoothDevice.getName()+"	"+bluetoothDevice.getAddress());
					}
				}
				else{
					System.out.println("no bonded device");
				}
			

			}
			else{
				System.out.println("no bluetooth device");
			}


可见性设置

Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
			discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
			startActivity(discoverableIntent);
持续时间不能超过300秒,超过的一律将变成300s

开始扫描

adapter.startDiscovery();



Android蓝牙的基本操作包括以下几个方面: 1. 获取蓝牙适配器 在使用蓝牙功能之前,需要先获取蓝牙适配器。可以通过调用`BluetoothAdapter.getDefaultAdapter()`方法获取默认的蓝牙适配器,如下所示: ``` BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); ``` 2. 搜索设备 获取蓝牙适配器之后,可以进行设备搜索。可以通过调用`bluetoothAdapter.startDiscovery()`方法启动设备搜索,也可以通过调用`bluetoothAdapter.cancelDiscovery()`方法取消设备搜索。搜索设备需要时间,可以通过注册广播接收器来接收搜索结果。 ``` bluetoothAdapter.startDiscovery(); // 取消搜索 bluetoothAdapter.cancelDiscovery(); ``` 3. 连接设备 搜索到设备之后,需要连接设备。可以通过调用`BluetoothDevice.createRfcommSocketToServiceRecord()`方法创建一个用于通信的Socket对象。连接设备需要时间,可以通过异步线程来连接设备。 ``` BluetoothSocket socket = device.createRfcommSocketToServiceRecord(MY_UUID); socket.connect(); ``` 4. 数据传输 连接设备之后,可以进行数据传输。可以通过获取BluetoothSocket对象的InputStream和OutputStream对象进行数据的读写操作。 ``` InputStream inputStream = socket.getInputStream(); OutputStream outputStream = socket.getOutputStream(); ``` 5. 监听蓝牙状态 在使用蓝牙功能时,需要监听蓝牙的状态。可以通过注册广播接收器来接收蓝牙状态的变化。 ``` <receiver android:name=".BluetoothStateReceiver"> <intent-filter> <action android:name="android.bluetooth.adapter.action.STATE_CHANGED" /> </intent-filter> </receiver> ``` 以上就是Android蓝牙的基本操作。开发者可以根据自己的需求进行调整和改进。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值