2010-10-14 30 views

Respuesta

-1

Analice this class en línea.

Aquí encontrará cómo descubrir todos los dispositivos Bluetooth conectados (emparejados).

+0

Hola Desiderio, bueno, como dije, quiero enumerar los dispositivos conectados (activos), no los emparejados/confiables. – Shatazone

+0

¿Qué sucede con la supervisión de transmisiones ACTION_ACL_CONNECTED? – Zelimir

+0

¿Cómo puedo descargar esa clase? Creo que me ayudará con mi problema. – Sonhja

1

Bueno, aquí están los pasos:

  1. En primer lugar, se inicia la intención de descubrir dispositivos

    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);

  2. El registro de un reciver emisión para ello:

    registerReceiver(mReceiver, filter);

  3. Sobre la definición de mReceiver:

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() { 
        public void onReceive(Context context, Intent intent) { 
        String action = intent.getAction(); 
        // When discovery finds a device 
        if (BluetoothDevice.ACTION_FOUND.equals(action)) { 
         // Get the BluetoothDevice object from the Intent 
         BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 
         // Add the name and address to an array adapter to show in a ListView 
         arrayadapter.add(device.getName())//arrayadapter is of type ArrayAdapter<String> 
         lv.setAdapter(arrayadapter); //lv is the list view 
         arrayadapter.notifyDataSetChanged(); 
        } 
    } 
    

y la lista se rellena automáticamente en el nuevo descubrimiento de dispositivos.

+0

Falta un}; al final del código. No puedo editarlo solo, ya que tiene que ser un cambio de 6 caracteres, y solo falta 2. –

0

El sistema Android no permite consultar todos los dispositivos conectados "actualmente". Sin embargo, puede consultar para dispositivos emparejados. Tendrá que usar un receptor de difusión para escuchar eventos ACTION_ACL_ {CONNECTED | DISCONNECTED} junto con el evento STATE_BONDED para actualizar sus estados de aplicación y rastrear lo que está actualmente conectado.

2

A partir del API 14 (helado), Android tiene un algunos nuevos métodos BluetoothAdapter incluyendo:

public int getProfileConnectionState (int profile)

donde el perfil es uno de HEALTH, HEADSET, A2DP

Comprobación de respuesta, si no es STATE_DISCONNECTED sabes tienes una conexión en vivo

Aquí es ejemplo de código que funcione en cualquier dispositivo API:

BluetoothAdapter mAdapter; 

/** 
* Check if a headset type device is currently connected. 
* 
* Always returns false prior to API 14 
* 
* @return true if connected 
*/ 
public boolean isVoiceConnected() { 
    boolean retval = false; 
    try { 
     Method method = mAdapter.getClass().getMethod("getProfileConnectionState", int.class); 
     // retval = mAdapter.getProfileConnectionState(android.bluetooth.BluetoothProfile.HEADSET) != android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; 
     retval = (Integer)method.invoke(mAdapter, 1) != 0; 
    } catch (Exception exc) { 
     // nothing to do 
    } 
    return retval; 
} 
+0

Hola, Yossi, ¿tienes algún código para esto? Sería genial :) –

+0

Eso me está volviendo cierto siempre si tengo Bluetooth activado, incluso si no estoy conectado a nada – JesusS

+0

¿Simulador o dispositivo real? ¿Qué dispositivo y versión de Android? – Yossi

0
public void checkConnected() 
{ 
    // true == headset connected && connected headset is support hands free 
    int state = BluetoothAdapter.getDefaultAdapter().getProfileConnectionState(BluetoothProfile.HEADSET); 
    if (state != BluetoothProfile.STATE_CONNECTED) 
    return; 

    try 
    { 
    BluetoothAdapter.getDefaultAdapter().getProfileProxy(_context, serviceListener, BluetoothProfile.HEADSET); 
    } 
    catch (Exception e) 
    { 
    e.printStackTrace(); 
    } 
} 

private ServiceListener serviceListener = new ServiceListener() 
{ 
    @Override 
    public void onServiceDisconnected(int profile) 
    { 

    } 

    @Override 
    public void onServiceConnected(int profile, BluetoothProfile proxy) 
    { 
    for (BluetoothDevice device : proxy.getConnectedDevices()) 
    { 
     Log.i("onServiceConnected", "|" + device.getName() + " | " + device.getAddress() + " | " + proxy.getConnectionState(device) + "(connected = " 
      + BluetoothProfile.STATE_CONNECTED + ")"); 
    } 

    BluetoothAdapter.getDefaultAdapter().closeProfileProxy(profile, proxy); 
    } 
}; 
Cuestiones relacionadas