Cómo mostrar el estado de la conexión bluetooth en android

Estoy desarrollando una aplicación. Necesito mostrar el estado de si el dispositivo está conectado o no a otro dispositivo emparejado. Puedo mostrar el mensaje de brindis, pero no puedo mostrar si el bluetooth está conectado a otro dispositivo o no en la vista de lista.

¿Puedes por favor mirar mi código añadido una vez y ayudarme en el problema ..

mi DeviceListActivity.class

mListView = (ListView) findViewById(R.id.lv_paired); BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices(); mDeviceList = new ArrayList<BluetoothDevice>(); mDeviceList.addAll(pairedDevices); mAdapter = new DeviceListAdapter(this); mAdapter.setData(mDeviceList); mAdapter.setListener(new OnConnectButtonClickListener() { public void onConnectButtonClick(int position) { BluetoothDevice device = mDeviceList.get(position); ConnectDevice(device); } }); mListView.setAdapter(mAdapter); registerReceiver(mConnectReceiver, new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED)); registerReceiver(mConnectReceiver, new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED)); } private void ConnectDevice(BluetoothDevice device) { try { // SERIAL_UUID = device.getUuids()[0].getUuid(); // msocket = device.createInsecureRfcommSocketToServiceRecord(SERIAL_UUID); Method method = device.getClass().getMethod("createRfcommSocket", new Class[] { int.class }); msocket = (BluetoothSocket) method.invoke(device, 2); msocket.connect(); } catch (Exception ex) { ex.printStackTrace(); try { msocket.close(); } catch (IOException closeEx) { closeEx.printStackTrace(); } return; } } private final BroadcastReceiver mConnectReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) { showToast("BlueTooth is Connected"); } else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) { showToast("BlueTooth DisConnected"); } mAdapter.notifyDataSetChanged(); } }; @Override public void onDestroy() { unregisterReceiver(mConnectReceiver); super.onDestroy(); } 

Mi clase DeviceListAdapter

 public class DeviceListAdapter extends BaseAdapter { private LayoutInflater mInflater; private List<BluetoothDevice> mData; private OnConnectButtonClickListener connectListener; public DeviceListAdapter(Context context) { mInflater = LayoutInflater.from(context); } public void setData(List<BluetoothDevice> data) { mData = data; } public void setListener(OnConnectButtonClickListener listener) { connectListener = listener; } public int getCount() { return (mData == null) ? 0 : mData.size(); } public Object getItem(int position) { return null; } public long getItemId(int position) { return position; } public View getView(final int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { convertView = mInflater.inflate(R.layout.list_item_device, parent, false); holder = new ViewHolder(); holder.nameTv = (TextView) convertView.findViewById(R.id.tv_name); holder.addressTv = (TextView) convertView.findViewById(R.id.tv_address); holder.connectBtn = (Button) convertView.findViewById(R.id.btn_connect); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } BluetoothDevice device = mData.get(position); holder.nameTv.setText(device.getName()); holder.addressTv.setText(device.getAddress()); holder.connectBtn.setText("connect"); holder.connectBtn.setText("connected"); holder.connectBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (connectListener != null) { connectListener.onConnectButtonClick(position); } } }); return convertView; } static class ViewHolder { TextView nameTv; TextView addressTv; Button connectBtn; } public interface OnConnectButtonClickListener { public abstract void onConnectButtonClick(int position); } 

Ahora, utilizando el receptor de registro, cuando haga clic en conectar necesito actualizar el estado del elemento de lista como conectado.

Cualquier ayuda en este problema puede salvar mi día. Gracias por adelantado.

Creo que vas a necesitar cambiar el modo en que guardas tus datos. BluetoothDevice te permitirá comprobar tu estado de vinculación con getBondState() , pero si getBondState() un vistazo a los documentos, eso no necesariamente ayudará:

Estar enlazado (emparejado) con un dispositivo remoto no significa necesariamente que el dispositivo esté actualmente conectado. Simplemente significa que el procedimiento pendiente se completó en algún momento anterior, y la clave de enlace todavía se almacena localmente, listo para usar en la siguiente conexión.

Es posible que desee crear un contenedor simple alrededor de su BluetoothDevice que pueda establecer el estado de la conexión.

 class BluetoohInfo { BluetoothDevice device; boolean connected; BluetoothInfo(BluetoothDevice device, boolean connected) { this.device = device; this.connected = connected; } public boolean isConnected() { return connected; } // getters and setters of your choosing } 

Ahora, en lugar de mostrar un Toast dentro de su BroadcastReceiver , simplemente establezca la propiedad conectada de BluetoothInfo a true .

A continuación, make mDeviceList una lista de BluetoothInfo , de modo que respalden su ListView , en lugar de sólo una lista en bruto de BluetoothDevice :

 mDeviceList = new ArrayList<BluetoothInfo>(); 

Dentro de getView() de su adaptador de lista, haga una comprobación para su propiedad conectada.

 if (bluetoothInfo.isConnected()) { holder.connectBtn.setText("connected"); } else { holder.connectBtn.setText("connect"); } 

Al hacer esto, el notifyDataSetChanged() dentro de su receptor debe hacer que estos cambios sean efectivos.

  • Android Estimote sdk no es capaz de escanear otros beacons que los estimote
  • Android: perfil de baja energía del GATT de Bluetooth
  • Android: Mostrar Notificación en la Vigilancia Cuando Cualquier Llamada o Notificación de la Red Social de móvil (mediante Bluetooth)
  • Pre-emparejamiento de dispositivos bluetooth
  • Android 4.3 Bluetooth Baja energía inestable
  • ¿Cómo detectar cuándo un dispositivo BLE ya no está en el rango?
  • ¿Cómo puedo activar la nueva función Bluetooth A2DP Sink introducida en Lollipop?
  • Detección del dispositivo bluetooth sin conectarse a él en Android
  • Problemas con Android Bluetooth LE Notificaciones
  • Uso de Bluetooth en el emulador de Android
  • Activar el perfil manos libres Bluetooth Bluetooth
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.