使用Android应用程序检查蓝牙是否已启用

4

我希望通过一个安卓应用来检查设备的蓝牙是否已开启。 我使用了.isEnabled方法。但出现了错误。通过注释掉一些代码,我发现报错就在.isEnabled这个方法里。请问您能否帮我解决这个问题?

final BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();

submitButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        String status = "Bluetooth";

        if(bluetooth != null) {
            if (bluetooth.isEnabled()) {
                String mydeviceaddress = bluetooth.getAddress();
                String mydevicename = bluetooth.getName();
                status = ("Address "+ mydeviceaddress + " Name" + mydevicename);
                Toast.makeText(getApplicationContext(), "" + status + "", Toast.LENGTH_LONG).show();
            } else {
                status = ("Bluetooth not enabled");
                Toast.makeText(getApplicationContext(), "" + status + "", Toast.LENGTH_LONG).show();
            }
        } else {
            Toast.makeText(getApplicationContext(), "" + status + "", Toast.LENGTH_LONG).show();
        }
    }
}
4个回答

20

这对我来说最有效:

/**
 * Check for Bluetooth.
 *
 * @return true if Bluetooth is available.
 */
public boolean isBluetoothAvailable() {
    final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    return bluetoothAdapter != null 
        && bluetoothAdapter.isEnabled() 
        && bluetoothAdapter.getState() == BluetoothAdapter.STATE_ON;
}

2
只有一个问题,为什么那个方法要接收一个Context对象,明明根本没有使用它呢? - hmartinezd
1
@hmartinezd 很敏锐的眼睛。现在已经修复了。 - Jared Burrows

6

试一下这个。

BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
    // Device does not support Bluetooth
} else {
    if (!bluetoothAdapter.isEnabled()) {
        // Bluetooth is not enabled
    }
}

在你的AndroidManifest.xml文件中添加。
<uses-permission android:name="android.permission.BLUETOOTH" />

@Saku,有哪些错误?请更新您的帖子并放置错误详情。 - Bishan
出现了“强制关闭”。由于模拟器不支持蓝牙,我尝试在实际的平板电脑上运行。因此,我无法提供精确的异常或错误消息。 - Saku
@Saku编写日志文件并跟踪错误消息,这样你就可以看到发生的错误。 - Bishan
如果蓝牙权限仅用于此检测,请勿忘记将其设置为非必需:<uses-feature android:name="android.hardware.bluetooth" android:required="false" />。 - Murphy

3

Jared Burrows的答案似乎是正确的,但在此之前我必须添加一项附加功能才能使其正常工作。我需要检查蓝牙状态。

public static boolean isBluetoothAvailable() {
    final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    return (bluetoothAdapter != null &&
            bluetoothAdapter.isEnabled() &&
            bluetoothAdapter.getState() == BluetoothAdapter.STATE_ON);
}

0
为什么不直接这样写:
...
return mBluetoothAdapter != null && mBluetoothAdapter.isEnabled();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接