我正在尝试在Android和蓝牙模块之间建立连接。我按照http://developer.android.com/guide/topics/connectivity/bluetooth.html的说明操作
在“发现”之后,我将找到的设备放入一个ListView,它有一个注册的OnItemClickListener
。
我现在的问题是,我需要点击条目中的BluetoothDevice
才能在下一步建立连接。我所拥有的只是ListView中的位置ID和Set<BluetoothDevice>
。但我不知道如何从集合中提取特定的BluetoothDevice
。
到目前为止,这是我的代码。 谢谢!
ProgressBar spinWheel;
ListView devList;
BluetoothAdapter btAdapter;
ArrayAdapter<String> lvAdapter;
BroadcastReceiver mReceiver;
Set<BluetoothDevice> pairedDevices;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.searchlist);
spinWheel = (ProgressBar)findViewById(R.id.progressBar1);
btAdapter = BluetoothAdapter.getDefaultAdapter();
devList = (ListView)findViewById(R.id.devicelist);
lvAdapter = new ArrayAdapter<String>(getApplicationContext(),
R.layout.simplerow, R.id.simpleRow);
devList.setAdapter(lvAdapter);
devList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parentView, View childView, int position,
long id) {
//establish Connection, need the clicked BluetoothDevice
}
});
//gepaarte Geräte in die ListView
pairedDevices = btAdapter.getBondedDevices();
//If there are paired devices
if (pairedDevices.size() > 0) {
// Loop through paired devices
for (BluetoothDevice device : pairedDevices) {
// Add the name and address to an array adapter to show in a ListView
lvAdapter.add(device.getName() + "\n"+ "#"+ device.getAddress());
}
}
// Create a BroadcastReceiver for ACTION_FOUND
mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// Add the name and address to an array adapter to show in a ListView
lvAdapter.add(device.getName() + "\n" + device.getAddress());
pairedDevices.add(device);
}
}
};
// Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy
btAdapter.startDiscovery();
}
@Override
public void onDestroy(){
super.onDestroy();
unregisterReceiver(mReceiver);
}
}
答案 0 :(得分:1)
我自己解决了这个问题,但我想发布它来帮助别人。 我使用了函数BluetoothAdapter.getRemoteDevice(String adress)。 当插入String中的地址从ListView中插入时,拆分为“#”。
public void onItemClick(AdapterView<?> parentView, View childView, int position,
long id) {
String[] separated = lvAdapter.getItem(position).split("#");
if(btAdapter.checkBluetoothAddress(separated[1])==true){
devtoconnect = btAdapter.getRemoteDevice(separated[1]);
}
}
});
尽管如此,感谢您对其他问题的帮助!