首先...... HappyNew Year !!!!我开始学习Android编程,实际上我正在尝试开发一些代码。主要的想法是搜索配对蓝牙设备,并列出所有BT设备附近...稍后我会尝试连接两台设备但不时:P
我的问题应该很简单,因为我用配对的方法填充我的ListView但是使用这段代码我无法填写我发现的那个...但我不知道我做错了什么导致Toast。 MakeText显示这个BT设备但不在ListView ....任何人都可以帮助我???非常感谢
//显示ANDROID VERSION Context context = getApplicationContext();
//Setting up for JELLY_BEAN_MR1 and above
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {
BluetoothManager bluetoothManager = (BluetoothManager)context.getSystemService(Context.BLUETOOTH_SERVICE);
if (bluetoothManager != null)
{
mBluetoothAdapter = bluetoothManager .getAdapter();
}
} else {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
}
//Enable
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
}
//Discover my BT
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
//Paired Devices
pairedDevices = mBluetoothAdapter.getBondedDevices();
final ArrayList<String> listBT = new ArrayList<String>();
ListView lv =(ListView)findViewById(R.id.listDevicesFound);
for(BluetoothDevice bt : pairedDevices)
listBT.add(bt.getName());
//Starting Search
final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)){
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
listBT.add(device.getName()); //Something happens but not adding to ListView
Toast.makeText(getApplicationContext(), device.getName(),
Toast.LENGTH_SHORT).show();
}
}
};
registerReceiver(mReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
mBluetoothAdapter.startDiscovery();
//Show ListView
lv.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , listBT));
答案 0 :(得分:1)
为您的适配器创建一个类变量(在您的类中上面):
private ArrayAdapter<String> mDeviceListAdapter;
克隆特适配器并将其设置为列表:
//Show ListView
mDeviceListAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , listBT);
lv.setAdapter(mDeviceListAdapter);
当您有新项目时更新适配器数据:
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)){
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
listBT.add(device.getName());
if(mDeviceListAdapter!=null){
mDeviceListAdapter.add(device.getName());
mDeviceListAdapter.notifyDataSetChanged();
}
Toast.makeText(getApplicationContext(), device.getName(),
Toast.LENGTH_SHORT).show();
}
}