我是android新手。我想开发一个应用程序,通过编程方式使用蓝牙找到该范围内的设备。如果有人有想法,请给我一些示例代码。
答案 0 :(得分:8)
Find The Devices in the Range by using Bluetooth programmatically.
是的,您可以使用BroadcastReceiver执行此操作,请查看以下代码,它会对您有帮助。
开始搜索
mBluetoothAdapter.startDiscovery();
mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
查找设备
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
mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
}
};
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
答案 1 :(得分:1)
创建类似以下内容的广播接收器并添加设备信息
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
ArrayList<HashMap<String, String> arl = new ArrayList<HashMap<String, String>();
// 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);
// If it's already paired, skip it, because it's been listed already
HashMap<String, String> deviceMap = new HashMap<String, String>();
deviceMap.put(device.getName(), device.getAddress());
arl.add(deviceMap);
// When discovery is finished, change the Activity title
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
setProgressBarIndeterminateVisibility(false);
setTitle(R.string.select_device);
if (mNewDevicesArrayAdapter.getCount() == 0) {
String noDevices = getResources().getText(R.string.none_found).toString();
mNewDevicesArrayAdapter.add(noDevices);
}
}
}
};
答案 2 :(得分:1)
您可能想要使用方法startDiscovery()。
我目前没有示例代码,但您可能需要查看:http://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#startDiscovery%28%29
希望它有所帮助!