No se puede encontrar todos los dispositivos bluetooth android
Estoy intentando exhibir los dispositivos del bluetooth continuamente y demostrarlos en la pantalla pero nunca me demuestra todos los dispositivos en lugar de otro solamente 1 a la vez. No puedo encontrar lo que estoy haciendo mal. Aquí está mi código, puede ser que usted puede encontrar cualquier problema en ella. Gracias
class monitorBluetooth extends monitor { private ListView mLvDevices; private ArrayList<String> mDeviceList = new ArrayList<String>(); public monitorBluetooth(service service) { super(service); bluetooth = BluetoothAdapter.getDefaultAdapter(); this.bReceiver = new BluetoothReceiver(); } public void finalize() throws Throwable { super.finalize(); } public void run() { IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); service.registerReceiver(this.bReceiver, filter); if(service != null) { bluetooth = BluetoothAdapter.getDefaultAdapter(); bluetooth.startDiscovery(); } } class BluetoothReceiver extends BroadcastReceiver { public void onReceive(Context context, Intent intent) { Set<BluetoothDevice> pairedDevices = bluetooth.getBondedDevices(); String action = intent.getAction(); if(BluetoothDevice.ACTION_FOUND.equals(action)) { BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); String uuid = intent.getStringExtra(BluetoothDevice.EXTRA_UUID); int rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI,Short.MIN_VALUE); mDeviceList.add(device.getAddress() + ", " + device.getName()); // get mac address ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, mDeviceList); mLvDevices.setAdapter(adapter); } } } } BluetoothAdapter bluetooth; private BluetoothReceiver bReceiver;
- Android - ¿Cuándo registrar / cancelar la inscripción de los receptores de difusión creados en una actividad?
- BroadcastReceiver onReceive no se llama
- BroadcastReceiver se dispara varias veces (PROVIDERS_CHANGED_ACTION)
- Cómo crear una intención pendiente dentro de una clase BroadcastReceiver?
- Cómo identificar la llamada entrante y la llamada saliente en android
- ¿Cómo identifica * qué * dispositivo bluetooth causa una emisión ACTION_ACL_CONNECTED?
- GCM con el receptor de difusión personalizado
- ACTION_HEADSET_PLUG demora de difusión
- Excepción extraña de "Receptor no registrado"
- ¿Cómo recibir sms en android?
- Android - ¿Cómo utilizar un receptor de radiodifusión local?
- ¿Qué problemas de seguridad puede causar SendBroadcast y qué es un enfoque mejor?
- Cómo obtener la forma de actividad BroadcastReceiver en onReceive
Su código parece funcionar. Escribí a LogCat lo que agregas a mDeviceList y recibí varios dispositivos.
Tal vez es la forma de mostrar los nombres o tal vez no hay más de un dispositivo visible BT alrededor?
EDIT: Código añadido
public class MonitorBluetooth extends Thread{ BluetoothAdapter bluetooth; private BluetoothReceiver bReceiver; private Context mContext; public MonitorBluetooth(Context context){ bluetooth=BluetoothAdapter.getDefaultAdapter(); this.bReceiver=new BluetoothReceiver(); this.mContext=context; } public void finalize() throws Throwable{ super.finalize(); } public void run(){ { IntentFilter filter=new IntentFilter(BluetoothDevice.ACTION_FOUND); mContext.registerReceiver(this.bReceiver,filter); } { IntentFilter filter=new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED); mContext.registerReceiver(this.bReceiver,filter); } { IntentFilter filter=new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); mContext.registerReceiver(this.bReceiver,filter); } bluetooth=BluetoothAdapter.getDefaultAdapter(); bluetooth.startDiscovery(); } class BluetoothReceiver extends BroadcastReceiver{ public void onReceive(Context context,Intent intent){ String action=intent.getAction(); if(BluetoothDevice.ACTION_FOUND.equals(action)){ BluetoothDevice device=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); Log.d("BluetoothReceiver","found "+device.getAddress()+", "+device.getName()); } else if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)){ Log.d("BluetoothReceiver","discovery started"); } else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){ Log.d("BluetoothReceiver","discovery finished"); context.unregisterReceiver(this); } } } }
Con este código recibo todos los dispositivos llamando
MonitorBluetooth monitor=new MonitorBluetooth(this.getApplicationContext()); monitor.start();
De Activity.onCreate (Bundle)
Pruebe algo de este orden:
public void displayDetectedDevices(){ mBluetoothAdapter.startDiscovery(); // Create a BroadcastReceiver for ACTION_FOUND 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)){ BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); String deviceName = device.getName(); String deviceAddress = device.getAddress(); String s = " "; unpairedDevices.add(deviceName + s + deviceAddress +" \n"); unpairedDevicesList = new ArrayList<String>(unpairedDevices); Toast.makeText(getActivity(), unpairedDevicesList.toString(), Toast.LENGTH_LONG).show(); } } }; }
Recuerde en onCreate () declarar lo siguiente:
public void onCreate(Bundle savedInstance){ super.onCreate(savedInstance); unpairedDevicesList = new ArrayList<String>(); unpairedDevices = new HashSet<String>(); }
Recuerde # 2 declarar lo siguiente antes onCreate ():
ArrayList<String> unpairedDevicesList; Set<String> unpairedDevices;
Pensamientos finales:
Utilicé un Set y un arrayList para colocar los dispositivos detectados. Un Set no contiene duplicados. Dependiendo de lo que desee hacer, tener ambos definidos es útil ya que proporcionan diferentes funciones. También aquí es mi página github que contiene más información y una aplicación de trabajo bluetooth completo.
A medida que el conjunto se llena, los dispositivos comenzarán a llenar la pantalla dependiendo de cómo desee que funcione su interfaz de usuario. Usé una lista simple.
Tuve el mismo problema con auriculares Bluetooth. Tenía dos auriculares bluetooth y ambos estaban encendidos, pero no fueron detectados por el blueToothAdapter.startDiscovery()
.
Más tarde me encontré con que, en caso de auriculares bluetooth, es necesario presionar el botón de inicio para activar su modo de emparejamiento para ser detectado por el descubrimiento de Android bluetooth.
Aquí está un ejemplo agradable de descubrir dispositivos bluetooth cercanos de developer.android.com .
- Cuando varios usuarios en android, es el ANDROID_ID único para cada usuario?
- Cómo crear savedInstanceState para la imagen seleccionada dinámicamente en Android?