private BroadcastReceiver searchDevices = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Bundle b = intent.getExtras();
Object[] lstName = b.keySet().toArray();
// 显示所有收到的消息及其细节
for (int i = 0; i < lstName.length; i++) {
String keyName = lstName[i].toString();
Log.e(keyName, String.valueOf(b.get(keyName)));
}
// 搜索设备时,取得设备的MAC地址
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (device.getBondState() == BluetoothDevice.BOND_NONE) {
String str = "未配对|" + device.getName() + "|" + device.getAddress();
lstDevices.add(str); // 获取设备名称和mac地址
adtDevices.notifyDataSetChanged();
}
}
}
};
class ItemClickEvent implements AdapterView.OnItemClickListener {
@Override
public void onItemClick(AdapterView> arg0, View arg1, int arg2,
long arg3) {
btAdapt.cancelDiscovery();
String str = lstDevices.get(arg2);
String[] values = str.split("\\|");
String address=values[2];
btDevice = btAdapt.getRemoteDevice(address);
try {
if(values[0].equals("未配对"))
{
Toast.makeText(testReflect.this, "由未配对转为已配对", 500).show();
ClsUtils.createBond(btDevice.getClass(), btDevice);
}
else if(values[0].equals("已配对"))
{
Toast.makeText(testReflect.this, "由已配对转为未配对", 500).show();
ClsUtils.removeBond(btDevice.getClass(), btDevice);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* 按键处理
* @author GV
*
*/
class ClickEvent implements View.OnClickListener {
@Override
public void onClick(View v) {
if (v == btnSearch) {//搜索附近的蓝牙设备
lstDevices.clear();
Object[] lstDevice = btAdapt.getBondedDevices().toArray();
for (int i = 0; i < lstDevice.length; i++) {
BluetoothDevice device=(BluetoothDevice)lstDevice[i];
String str = "已配对|" + device.getName() + "|" + device.getAddress();
lstDevices.add(str); // 获取设备名称和mac地址
adtDevices.notifyDataSetChanged();
}
// 开始搜索
setTitle("本机蓝牙地址:" + btAdapt.getAddress());
btAdapt.startDiscovery();
}
else if(v==btnShow){//显示BluetoothDevice的所有方法和常量,包括隐藏API
ClsUtils.printAllInform(btDevice.getClass());
}
}
}
}