Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if bluetooth is enabled using an Android application

I want to check if bluetooth is enabled in a device using an Android application. I used the .isEnabled method. But there is an error. I found out (by commenting lines) that the error is in .isEnabled method. Can you pls help me to figure this out?

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();
        }
    }
}
like image 282
Saku Avatar asked Nov 28 '22 11:11

Saku


2 Answers

This has worked best for me:

/**
 * 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;
}
like image 196
Jared Burrows Avatar answered Dec 16 '22 07:12

Jared Burrows


Try this.

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

in your AndroidManifest.xml File add

<uses-permission android:name="android.permission.BLUETOOTH" />
like image 23
Bishan Avatar answered Dec 16 '22 07:12

Bishan