2010-10-14 5 views

ответ

-1

Просим проанализировать this class онлайн.

Здесь вы найдете, как обнаружить все подключенные (парные) устройства Bluetooth.

+0

привет Десидерио, и я сказал, что хочу перечислить подключенные (активные) устройства, а не парные/доверенные. – Shatazone

+0

Что касается мониторинга трансляций ACTION_ACL_CONNECTED? – Zelimir

+0

Как загрузить этот класс? Я думаю, это поможет мне в моей проблеме. – Sonhja

1

Ну вот шаги:

  1. Во-первых, вы начинаете намерение обнаружить устройства

    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);

  2. Регистрация широковещательный Reciver для него:

    registerReceiver(mReceiver, filter);

  3. Об определении 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(); 
        } 
    } 
    

и список будет автоматически заполняется на открытии нового устройства.

+0

Отсутствует}; в конце кода. Я не могу сделать редактирование самостоятельно, так как это должно быть изменение с 6 символами, и оно отсутствует. 2. –

0

Система Android не позволяет запрашивать все «подключенные» устройства. Тем не менее, вы можете запросить сопряженные устройства. Вам нужно будет использовать широковещательный приемник для прослушивания событий ACTION_ACL_ {CONNECTED | DISCONNECTED} вместе с событием STATE_BONDED, чтобы обновить состояния вашего приложения, чтобы отслеживать, что в данный момент подключено.

2

По API 14 (Ice Cream), Android имеет некоторые новые методы BluetoothAdapter в том числе:

public int getProfileConnectionState (int profile)

где профиль является одним из HEALTH, HEADSET, A2DP

Проверьте ответ, если это не STATE_DISCONNECTED вы знаете у вас есть живое соединение.

Вот пример кода, который будет работать на любом устройстве 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

Привет, Йоси, у вас есть код для этого? Было бы здорово :) –

+0

Это верно, если я подключаюсь к Bluetooth, даже если я не подключен к чему-либо – JesusS

+0

Симулятор или фактическое устройство? Какое устройство и версия 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); 
    } 
}; 
Смежные вопросы