Saltar al contenido

¿Cómo obtener los dispositivos bluetooth como una lista?

Hola usuario de nuestro sitio, hallamos la respuesta a lo que necesitas, continúa leyendo y la obtendrás a continuación.

Solución:

Debe cambiar su código de la siguiente manera:

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set pairedDevices = mBluetoothAdapter.getBondedDevices();

List s = new ArrayList();
for(BluetoothDevice bt : pairedDevices)
   s.add(bt.getName());

setListAdapter(new ArrayAdapter(this, R.layout.list, s));

Encontrar lista de Bluetooth cercano Dispositivos:

Encuentra captura de pantalla para el mismo.

ingrese la descripción de la imagen aquí

MainActivity.java:

public class MainActivity extends ActionBarActivity {

    private ListView listView;
    private ArrayList mDeviceList = new ArrayList();
    private BluetoothAdapter mBluetoothAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        listView = (ListView) findViewById(R.id.listView);

        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        mBluetoothAdapter.startDiscovery();

        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(mReceiver, filter);

    


    @Override
    protected void onDestroy() 
        unregisterReceiver(mReceiver);
        super.onDestroy();
    

    private final BroadcastReceiver mReceiver = new 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);
                mDeviceList.add(device.getName() + "n" + device.getAddress());
                Log.i("BT", device.getName() + "n" + device.getAddress());
                listView.setAdapter(new ArrayAdapter(context,
                        android.R.layout.simple_list_item_1, mDeviceList));
            
        
    ;

activity_main.xml:



    


Manifiesto expediente:




    

    
    

    
        
            
                

                
            
        
    


Nota:

Asegúrese de pedir permiso de ubicación a su usuario y activar el GPS.

Razón: A partir de Android 6.0, necesita permiso de ubicación para el descubrimiento de Bluetooth.

Más referencia:

  1. https://developer.android.com/guide/topics/connectivity/bluetooth
  2. https://getlief.zendesk.com/hc/en-us/articles/360007600233-Why-does-Android-require-Location-Permissions-for-Bluetooth-

Hecho

Probé el siguiente código,

main.xml





ListPairedDevicesActivity.java

import java.util.Set;

import android.app.ListActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothClass;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class ListPairedDevicesActivity extends ListActivity 

 @Override
 protected void onCreate(Bundle savedInstanceState) 
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);

  ArrayAdapter btArrayAdapter 
    = new ArrayAdapter(this,
             android.R.layout.simple_list_item_1);

  BluetoothAdapter bluetoothAdapter 
   = BluetoothAdapter.getDefaultAdapter();
  Set pairedDevices 
   = bluetoothAdapter.getBondedDevices();

  if (pairedDevices.size() > 0) 
      for (BluetoothDevice device : pairedDevices) 
       String deviceBTName = device.getName();
       String deviceBTMajorClass 
        = getBTMajorDeviceClass(device
          .getBluetoothClass()
          .getMajorDeviceClass());
       btArrayAdapter.add(deviceBTName + "n" 
         + deviceBTMajorClass);
      
  
  setListAdapter(btArrayAdapter);

 

 private String getBTMajorDeviceClass(int major)
  switch(major) 
  case BluetoothClass.Device.Major.AUDIO_VIDEO:
   return "AUDIO_VIDEO";
  case BluetoothClass.Device.Major.COMPUTER:
   return "COMPUTER";
  case BluetoothClass.Device.Major.HEALTH:
   return "HEALTH";
  case BluetoothClass.Device.Major.IMAGING:
   return "IMAGING"; 
  case BluetoothClass.Device.Major.MISC:
   return "MISC";
  case BluetoothClass.Device.Major.NETWORKING:
   return "NETWORKING"; 
  case BluetoothClass.Device.Major.PERIPHERAL:
   return "PERIPHERAL";
  case BluetoothClass.Device.Major.PHONE:
   return "PHONE";
  case BluetoothClass.Device.Major.TOY:
   return "TOY";
  case BluetoothClass.Device.Major.UNCATEGORIZED:
   return "UNCATEGORIZED";
  case BluetoothClass.Device.Major.WEARABLE:
   return "AUDIO_VIDEO";
  default: return "unknown!";
  
 

 @Override
 protected void onListItemClick(ListView l, View v, int position, long id) 
  // TODO Auto-generated method stub
  super.onListItemClick(l, v, position, id);

     Intent intent = new Intent();
     setResult(RESULT_OK, intent);
     finish();
 


AndroidBluetooth.java

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class AndroidBluetooth extends Activity 

 private static final int REQUEST_ENABLE_BT = 1;
 private static final int REQUEST_PAIRED_DEVICE = 2;

    /** Called when the activity is first created. */
 Button btnListPairedDevices;
 TextView stateBluetooth;
 BluetoothAdapter bluetoothAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        btnListPairedDevices = (Button)findViewById(R.id.listpaireddevices);

        stateBluetooth = (TextView)findViewById(R.id.bluetoothstate);
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        CheckBlueToothState();

        btnListPairedDevices.setOnClickListener(btnListPairedDevicesOnClickListener);
    

    private void CheckBlueToothState()
     if (bluetoothAdapter == null)
         stateBluetooth.setText("Bluetooth NOT support");
        else
         if (bluetoothAdapter.isEnabled())
          if(bluetoothAdapter.isDiscovering())
           stateBluetooth.setText("Bluetooth is currently in device discovery process.");
          else
           stateBluetooth.setText("Bluetooth is Enabled.");
           btnListPairedDevices.setEnabled(true);
          
         else
          stateBluetooth.setText("Bluetooth is NOT Enabled!");
          Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
             startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
         
        
    

    private Button.OnClickListener btnListPairedDevicesOnClickListener
    = new Button.OnClickListener()

  @Override
  public void onClick(View arg0) 
   // TODO Auto-generated method stub
   Intent intent = new Intent();
   intent.setClass(AndroidBluetooth.this, ListPairedDevicesActivity.class);
   startActivityForResult(intent, REQUEST_PAIRED_DEVICE); 
  ;

 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) 
  // TODO Auto-generated method stub
  if(requestCode == REQUEST_ENABLE_BT)
   CheckBlueToothState();
  if (requestCode == REQUEST_PAIRED_DEVICE)
   if(resultCode == RESULT_OK)

   
   
    

AndroidManifest.xml



    
    

    
        
            
                
                
            
        
  
    

Reseñas y puntuaciones del artículo

Tienes la opción de reafirmar nuestra misión escribiendo un comentario y valorándolo te lo agradecemos.

¡Haz clic para puntuar esta entrada!
(Votos: 2 Promedio: 5)



Utiliza Nuestro Buscador

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *