我看了很多例子,一切似乎都是正确的。我有两个权限,检查它们是否被激活。我看过Stackoverflow上的无数帖子。我知道这是一个非常小的东西,我总是喜欢。我确保我搜索的所有设备都可见。我甚至用系统蓝牙进行了双重检查,发现它只是找到了。我究竟做错了什么。这是我的代码。
public class Bluetooth_ListView extends ListActivity
{
private BluetoothAdapter mBluetoothAdapter;
private ArrayList<Bluetooth> arrayOfFoundBTDevices;
private BroadcastReceiver mReceiver;
@TargetApi(Build.VERSION_CODES.M)
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// Quick permission check
int permissionCheck = this.checkSelfPermission("Manifest.permission.ACCESS_FINE_LOCATION");
permissionCheck += this.checkSelfPermission("Manifest.permission.ACCESS_COARSE_LOCATION");
if (permissionCheck != 0) {
this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1001);
}
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
mBluetoothAdapter.startDiscovery();
displayListOfFoundDevices();
}
private void displayListOfFoundDevices()
{
arrayOfFoundBTDevices = new ArrayList<Bluetooth>();
// Create a BroadcastReceiver for ACTION_FOUND
mReceiver = new BroadcastReceiver()
{
@Override
public void onReceive(Context context, Intent intent)
{
Log.v("discover_me", "Bluetooth receiving");
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);
int rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI,Short.MIN_VALUE);
// Create the device object and add it to the arrayList of devices
Bluetooth bluetoothObject = new Bluetooth();
bluetoothObject.setBluetooth_name(device.getName());
bluetoothObject.setBluetooth_address(device.getAddress());
bluetoothObject.setBluetooth_state(device.getBondState());
bluetoothObject.setBluetooth_type(device.getType());
bluetoothObject.setBluetooth_uuids(device.getUuids());
bluetoothObject.setBluetooth_rssi(rssi);
arrayOfFoundBTDevices.add(bluetoothObject);
Bluetooth_Adapter adapter = new Bluetooth_Adapter(getApplicationContext(), arrayOfFoundBTDevices);
setListAdapter(adapter);
}
}
};
// Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
}
@Override
protected void onPause()
{
super.onPause();
mBluetoothAdapter.cancelDiscovery();
}
@Override
protected void onDestroy()
{
super.onDestroy();
unregisterReceiver(mReceiver);
mBluetoothAdapter.cancelDiscovery();
}
}
任何建议都很棒。无论如何,阵列总是空白的。此外,onReceive中的Log.v永远不会被调用。