权限
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
初始化
defaultAdapter = BluetoothAdapter.getDefaultAdapter();
defaultAdapter.enable();
搜索已配对设备
Set<BluetoothDevice> bondedDevices = defaultAdapter.getBondedDevices();
for (BluetoothDevice bluetoothDevice : bondedDevices) {
if (!deviceList.contains(bluetoothDevice))
//添加到集合中
deviceList.add(bluetoothDevice);
}
搜索未配对设备
- 在一开始注册发现蓝牙的广播
- 注册广播 ,有两个action,一个是发现蓝牙,一个是蓝牙状态改变的广播
receiver = new MyBluetoothReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
registerReceiver(receiver, filter);
class MyBluetoothReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
BluetoothDevice bluetoothDevice = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (action.equals(BluetoothDevice.ACTION_FOUND)) {
if (!deviceList.contains(bluetoothDevice)) {
deviceList.add(bluetoothDevice);
}
setAdapter();
} else if (action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)) {
int bondState = bluetoothDevice.getBondState();
switch (bondState) {
case BluetoothDevice.BOND_NONE:
Toast.makeText(MainActivity.this, "配对失败", 0).show();
break;
case BluetoothDevice.BOND_BONDING:
Toast.makeText(MainActivity.this, "正在配对", 0).show();
break;
case BluetoothDevice.BOND_BONDED:
Toast.makeText(MainActivity.this, "配对成功", 0).show();
deviceList.remove(bluetoothDevice);
deviceList.add(0, bluetoothDevice);
setAdapter();
break;
default:
break;
}
}
}
}
new Thread() {
public void run() {
if (defaultAdapter.isDiscovering()) {
defaultAdapter.cancelDiscovery();
}
defaultAdapter.startDiscovery();
};
}.start();
设置数据适配器
// 如果适配器为空,创建,设置适配器
if (myBluetoothAdapter == null) {
myBluetoothAdapter = new MyBluetoothAdapter(this, deviceList);
listView.setAdapter(myBluetoothAdapter);
} else {
// 刷新适配器
myBluetoothAdapter.notifyDataSetChanged();
}
对未配对设备进行配对
try {
// 获取点击的条目
BluetoothDevice bluetoothDevice = deviceList.get(position);
// 未配对,就去配对
if (bluetoothDevice.getBondState() == BluetoothDevice.BOND_NONE) {
String address = bluetoothDevice.getAddress();
// 获取远程设备
BluetoothDevice remoteDevice = defaultAdapter
.getRemoteDevice(address);
// 配对操作
// 先获取字节码文件对象
Class<BluetoothDevice> clz = BluetoothDevice.class;
// 获取方法,这个方法是隐藏的,调不到,随时用反射
Method method = clz.getMethod("createBond", null);
// 执行配对该方法
method.invoke(remoteDevice, null);
// 如果当前条目的状态,是已经配好对的,就开始聊天
}
对配对设备准备开始聊天操作
else if (bluetoothDevice.getBondState() == BluetoothDevice.BOND_BONDED) {
// 跳转界面,开始聊天
Intent intent = new Intent(MainActivity.this,MyChatActivity.class);
intent.putExtra("address", bluetoothDevice.getAddress());
startActivity(intent);
}
代码见
http://download.youkuaiyun.com/detail/zhiyuan0932/9498223