</pre><p><pre name="code" class="html"><span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">首先是实现的目标,button打开android蓝牙,列出已经配对的设备名与地址,button触发搜索设备,新设备添加到列表。搜索过程用进度组件呈现</span>
1)实现功能需要的ui
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.s042304bluetooth.BluetoothActivity" >
<Button
android:id="@+id/btnOpen"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="open bluetooth" />
<Button
android:id="@+id/btnSearch"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="search bluetooth" />
<TextView
android:id="@+id/tvBluetooth"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30sp" >
</TextView>
</LinearLayout>
2)申请访问权限:
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
3)实现功能的逻辑以及相关知识:
相关api bluetoothadapter bluetoothdevice请查看api手册
3.1)打开蓝牙
法1: 实例化bluetoothadapter对象,有对象的enable完成
法2:创建intent,隐式调用本地BluetoothAdapter.ACTION_REQUEST_ENABLE
3.2)bluetoothadapter获取本地蓝牙数据,已经配对信息,保存在泛型列表中
getbonddevides
3.3)注册广播,这里的功能需要接受BluetoothDevice.ACTION_FOUND/ACTION_DISCOVERY_FINISHED两个信息
创建IntentFilter,过滤响应的intent,这里要注意,android系统的蓝牙响应方式为广播,broadcast的intent隐式响应可以无需再mainifest中添加action,catego。
3.4)响应广播
4)代码实现:
adapter = BluetoothAdapter.getDefaultAdapter();
pairedDevices = adapter.getBondedDevices();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(receiver, filter);
filter = new IntentFilter(adapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(receiver, filter);
@Override
public void onReceive(Context context, Intent intent) {
String actionName = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(actionName)) {
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (device.getBondState() != BluetoothDevice.BOND_BONDED)
tv.append(device.getName() + ":" + device.getAddress()
+ "\n");
} else if (adapter.ACTION_DISCOVERY_FINISHED.equals(actionName)) {
setProgressBarIndeterminateVisibility(false);
setTitle("搜索完成");
adapter.cancelDiscovery();
}