Cómo habilitar / deshabilitar bluetooth mediante programación en Android


104

Quiero habilitar / deshabilitar bluetooth a través del programa. tengo el siguiente código.

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

Pero este código no funciona en SDK 1.5. ¿Cómo puedo hacer que funcione?


¿Cómo no funciona? ¿Estás obteniendo un error? Si es así, ¿cuál es el error?
— Adam Driscoll

1
BluetoothAdapter muestra un error en SDK 1.5
— user458295

Respuestas:



164

este código funcionó para mí ..

//Disable bluetooth
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();    
if (mBluetoothAdapter.isEnabled()) {
    mBluetoothAdapter.disable(); 
} 

Para que esto funcione, debe tener los siguientes permisos:

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

realmente funciona para mí también. Método simple para desconectar el bluetooth en dispositivos Android. muchas gracias amigo.
— Amit Thaper

7
si agrega el permiso BLUETOOTH_ADMIN, funciona, pero si no, necesita usar startActivityForResult (enableBtIntent, 0); para habilitar su bluetooth
— Majid Golshadi

1
Gracias por tu útil respuesta +1. solo quiero agregar para quienes no saben cómo habilitarlo: mBluetoothAdapter.enable ()
— Chris Sim

97

Aquí hay una forma un poco más sólida de hacer esto, también manejando los valores de retorno de los enable()\disable()métodos:

public static boolean setBluetooth(boolean enable) {
    BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    boolean isEnabled = bluetoothAdapter.isEnabled();
    if (enable && !isEnabled) {
        return bluetoothAdapter.enable(); 
    }
    else if(!enable && isEnabled) {
        return bluetoothAdapter.disable();
    }
    // No need to change bluetooth state
    return true;
}

Y agregue los siguientes permisos en su archivo de manifiesto:

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

Pero recuerde estos puntos importantes:

Esta es una llamada asincrónica: regresará inmediatamente y los clientes deben escuchar a ACTION_STATE_CHANGED para recibir notificaciones de los cambios de estado del adaptador posteriores. Si esta llamada devuelve verdadero, entonces el estado del adaptador pasará inmediatamente de STATE_OFF a STATE_TURNING_ON, y algún tiempo después pasará a STATE_OFF o STATE_ON. Si esta llamada devuelve falso, entonces hubo un problema inmediato que evitará que el adaptador se encienda, como el modo Avión, o el adaptador ya está encendido.

ACTUALIZAR:

Ok, entonces, ¿cómo implementar el oyente bluetooth ?:

private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();

        if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
            final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
                                                 BluetoothAdapter.ERROR);
            switch (state) {
            case BluetoothAdapter.STATE_OFF:
                // Bluetooth has been turned off;
                break;
            case BluetoothAdapter.STATE_TURNING_OFF:
                // Bluetooth is turning off;
                break;
            case BluetoothAdapter.STATE_ON:
                // Bluetooth is on
                break;
            case BluetoothAdapter.STATE_TURNING_ON:
                // Bluetooth is turning on
                break;
            }
        }
    }
};

¿Y cómo registrar / anular el registro del receptor? (En tu Activityclase)

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // ...

    // Register for broadcasts on BluetoothAdapter state change
    IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
    registerReceiver(mReceiver, filter);
}

@Override
public void onStop() {
    super.onStop();

     // ...

    // Unregister broadcast listeners
    unregisterReceiver(mReceiver);
}

1
si agrega BLUETOOTH_ADMINpermiso, funciona, pero si no, debe usarlo startActivityForResult(enableBtIntent, 0);para habilitar su bluetooth
— Majid Golshadi

1
la información resaltada se cita de los documentos de BluetoothAdapter, específicamente para el método enable ().
— Kevin Lee

oye, los doctores dicen que Bluetooth should never be enabled without direct user consent. If you want to turn on Bluetooth in order to create a wireless connection, you should use the ACTION_REQUEST_ENABLE Intent, which will raise a dialog that requests user permission to turn on Bluetooth. The enable() method is provided only for applications that include a user interface for changing system settings, such as a "power manager" app.¿Qué significa? Por ej. Hice una pequeña aplicación a partir de tu código y funcionó. Pero si quiero subir a Play Store, ¿no funcionará?
— Hilal

@Hilal funcionará. Pero los usuarios deben dar su consentimiento antes de la instalación. Verán un diálogo como este: pewinternet.org/2015/11/10/…
— Caner

23

Para habilitar el Bluetooth, puede utilizar cualquiera de las siguientes funciones:

 public void enableBT(View view){
    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (!mBluetoothAdapter.isEnabled()){
        Intent intentBtEnabled = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 
        // The REQUEST_ENABLE_BT constant passed to startActivityForResult() is a locally defined integer (which must be greater than 0), that the system passes back to you in your onActivityResult() 
        // implementation as the requestCode parameter. 
        int REQUEST_ENABLE_BT = 1;
        startActivityForResult(intentBtEnabled, REQUEST_ENABLE_BT);
        }
  }

La segunda función es:

public void enableBT(View view){
    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (!mBluetoothAdapter.isEnabled()){
        mBluetoothAdapter.enable();
    }
}

La diferencia es que la primera función hace que la aplicación solicite al usuario un permiso para encender el Bluetooth o para denegarlo. La segunda función hace que la aplicación encienda el Bluetooth directamente.

Para deshabilitar el Bluetooth use la siguiente función:

public void disableBT(View view){
    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (mBluetoothAdapter.isEnabled()){
        mBluetoothAdapter.disable();
    }
}

NOTA / La primera función solo necesita el siguiente permiso para definirse en el archivo AndroidManifest.xml:

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

Mientras que, la segunda y tercera funciones necesitan los siguientes permisos:

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

Creo que el parámetro (Ver vista) no es necesario
— CitrusO2

6

La solución de prijin funcionó perfectamente para mí. Es justo mencionar que se necesitan dos permisos adicionales:

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

Cuando se agregan, habilitar y deshabilitar funciona perfectamente con el adaptador bluetooth predeterminado.


4

Utilicé el siguiente código para desactivar BT cuando mi aplicación se inicia y funciona bien. No estoy seguro si esta es la forma correcta de implementar esto, ya que Google recomienda no usar "bluetooth.disable ();" sin una acción explícita del usuario para desactivar Bluetooth.

    BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
    bluetooth.disable();

Solo utilicé el siguiente permiso.

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

2

Agrega los siguientes permisos a tu archivo de manifiesto:

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

Habilita bluetooth usa esto

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();    
if (!mBluetoothAdapter.isEnabled()) {
    mBluetoothAdapter.enable(); 
}else{Toast.makeText(getApplicationContext(), "Bluetooth Al-Ready Enable", Toast.LENGTH_LONG).show();}

Desactivar bluetooth usar esto

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();    
if (mBluetoothAdapter.isEnabled()) {
    mBluetoothAdapter.disable(); 
}

0

prueba esto:

//this method to check bluetooth is enable or not: true if enable, false is not enable
public static boolean isBluetoothEnabled()
    {
        BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (!mBluetoothAdapter.isEnabled()) {
            // Bluetooth is not enable :)
            return false;
        }
        else{
            return true;
        }

    }

//method to enable bluetooth
    public static void enableBluetooth(){
        BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (!mBluetoothAdapter.isEnabled()) {
            mBluetoothAdapter.enable();
        }
    }

//method to disable bluetooth
    public static void disableBluetooth(){
        BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter.isEnabled()) {
            mBluetoothAdapter.disable();
        }
    }

Agrega estos permisos en el manifiesto

<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
Al usar nuestro sitio, usted reconoce que ha leído y comprende nuestra Política de Cookies y Política de Privacidad.
Licensed under cc by-sa 3.0 with attribution required.