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

时间:2012-06-28 10:20:05

标签: android bluetooth

我想检查使用Android应用程序的设备是否启用了蓝牙。 我使用了.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 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:6)

试试这个。

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

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

答案 2 :(得分:3)

Jared Burrows的回答似乎是正确的,但是我必须在它开始工作之前添加一个添加。我必须检查蓝牙状态。

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

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

答案 3 :(得分:0)

为什么不呢:

...
return mBluetoothAdapter != null && mBluetoothAdapter.isEnabled();
相关问题