2010-09-27 20 views
82

HI all,Cómo habilitar/deshabilitar bluetooth programáticamente en android

Quiero activar/desactivar 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 tipo de código no está trabajando en el SDK 1.5..How puedo hacer lo mismo en el SDK 1.5.?

+0

¿Cómo es posible que no trabaja? ¿Estás obteniendo un error? Si es así, ¿cuál es el error? –

+0

BluetoothAdapter muestra un error en SDK 1.5 – user458295

Respuesta

126

el código que funcionó para mí ..

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

Para que esto funcione, debe tener la los siguientes permisos:

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

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

+6

si agrega permiso a BLUETOOTH_ADMIN, funciona, pero si no es así, debe usar startActivityForResult (enableBtIntent, 0); para habilitar su bluetooth –

+0

Gracias por su útil respuesta +1. solo quiero agregar para quien no sabe cómo habilitarlo: mBluetoothAdapter.enable() –

5

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

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

Cuando estos se añaden, habilitar y deshabilitar las obras sin defectos con el adaptador Bluetooth predeterminado.

66

Aquí es así un poco más robusto de hacer esto, también el manejo de los valores de retorno de 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 añadir los siguientes permisos en el 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 asíncrona: se devolverá de inmediato, y los clientes deben escuchar ACTION_STATE_CHANGED para recibir notificaciones de los cambios de estado del adaptador subsiguientes. 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, hubo un problema inmediato que impedirá que el adaptador se encienda , como el modo avión, o el adaptador ya está encendido.

ACTUALIZACIÓN:

autorización, así como implementar 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 has been on 
       break; 
      case BluetoothAdapter.STATE_TURNING_ON: 
       // Bluetooth is turning on 
       break; 
      } 
     } 
    } 
}; 

Y cómo registrar/anular el registro del receptor?(En la clase Activity)

@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 el permiso 'BLUETOOTH_ADMIN' funciona, pero si no necesita usar' startActivityForResult (enableBtIntent, 0); 'para habilitar su bluetooth –

+1

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

18

para permitir que el Bluetooth se 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 el La primera función hace que la aplicación solicite permiso al usuario para encender Bluetooth o para denegar. La segunda función hace que la aplicación encienda el Bluetooth directamente.

para desactivar el Bluetooth usar la siguiente función:

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

NOTA/La primera función sólo necesita el siguiente permiso para ser definido en el archivo AndroidManifest.xml:

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

Mientras, el segunda y tercera funciones necesitan los siguientes permisos:

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

Utilicé el siguiente código para desactivar BT cuando mi aplicación se inicia y funciona bien. No estoy seguro de si esta es la forma correcta de implementar esto, ya que google recomienda no usar "bluetooth.disable();" sin 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

Añadir los siguientes permisos en el archivo de manifiesto:

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

Activa el uso del bluetooth esta

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

Desactivar el uso del bluetooth esta

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

probar 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(); 
     } 
    } 

Añadir estos permisos en el manifiesto

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