在Android应用中无法通过蓝牙找到发言人

时间:2019-08-05 18:17:27

标签: android bluetooth

我正在尝试制作一个简单的应用程序,该应用程序通过蓝牙扫描设备并与它们连接以进行学习。我有一个Creative MUVO 1c扬声器,它通过蓝牙无线连接,但是我的startDiscovery()方法找不到任何东西。我根据Android开发者网站上的蓝牙概述进行了所有操作,但不知道出了什么问题。这是我的代码:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button scanDevicesButton;
BluetoothAdapter bluetoothAdapter;
final int REQUEST_ENABLE_BT = 1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    scanDevicesButton = findViewById(R.id.scan_devices);
    scanDevicesButton.setOnClickListener(this);
    bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (!bluetoothAdapter.isEnabled()) {
        Intent enableBTIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBTIntent, REQUEST_ENABLE_BT);
    }

    // Checking paired devices
    Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
    if (pairedDevices.size() > 0) {
        for (BluetoothDevice device : pairedDevices) {
            String deviceName = device.getName();
            String deviceAddress = device.getAddress();
            Log.d("Paired devices: ", deviceName + " " + deviceAddress);
        }
    }

    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    registerReceiver(receiver, filter);

}

private final BroadcastReceiver receiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            Toast.makeText(getBaseContext(), "Devicefound", Toast.LENGTH_SHORT).show();
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            String deviceName = device.getName();
            String deviceHardwareAddress = device.getAddress();
            Log.d("Founddevices: ", deviceName + " " + deviceHardwareAddress);
        }
    }
};

@Override
protected void onDestroy() {
    super.onDestroy();
    unregisterReceiver(receiver);
}

@Override
public void onClick(View v) {
    int id = v.getId();
    if (id == R.id.scan_devices) {
        Toast.makeText(getBaseContext(), "Scan", Toast.LENGTH_SHORT).show();
        boolean isDiscovering = bluetoothAdapter.startDiscovery();
        Log.d("Discovering: ", " " + isDiscovering);
    }
}

}

如果有人指出我犯了一个错误,我将不胜感激。

0 个答案:

没有答案