安卓蓝牙开启

2023-11-29

我正在开发一个蓝牙聊天应用程序。问题是,当我启用蓝牙时,应用程序启用蓝牙但会导致强制关闭。下次我启动相同的应用程序(启用蓝牙)时,它运行顺利!我已经搜索过,只得到一些信息,说当我启动启用蓝牙的意图时,代码会继续执行,而不等待意图的结果

        public void run() {

        // 1. Check if Bluetooth is Enabled
        if (!blue.isEnabled()) {
            Intent enable_Bluetooth = new Intent(
                    BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enable_Bluetooth, 1);

        }

        // 2. Start Bluetooth Server
        try {
            Server = blue.listenUsingRfcommWithServiceRecord("dhiraj",
                    MY_UUID);

first:

在应用程序清单文件中声明蓝牙权限。 例如:

<manifest ... >
<uses-permission android:name="android.permission.BLUETOOTH" />
...
</manifest>

设置蓝牙:

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
// Device does not support Bluetooth
}

启用蓝牙:

if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}

查找设备:

Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.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
    mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
}

发现设备:

// Create a BroadcastReceiver for ACTION_FOUND
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override 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
        mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
    }
}
};
// Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy

启用发现

Intent discoverableIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

安卓蓝牙开启 的相关文章

随机推荐