How to get the bluetooth devices as a list?
Asked Answered
D

7

34

I am trying to get my bonded bluetooth devices but I can get it as a long string instead of list.

This is my code:

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
ArrayList<String> listview = 
new ArrayList<String>(Arrays.asList(pairedDevices.toString()));
setListAdapter(new ArrayAdapter<String>(this, R.layout.list, listview));

I am getting something like this: [00:23:7F:1c, f0:09:f1:b4:b0]. And its all in one line. How can I change it to be in a list and not all in one line?

Also, how can I get the friendly names of the devices and not these numbers?

Thanks!!!

Dichotomy answered 29/5, 2012 at 8:16 Comment(1)
Did you implemented that when click on item of the list connects to the paired device automatically?Stood
G
52

You should change your code as below:

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();

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

setListAdapter(new ArrayAdapter<String>(this, R.layout.list, s));
Geanine answered 29/5, 2012 at 8:24 Comment(4)
yea!!! Thanks!!! only need to add that i changed List<String> s = new ArrayList<String>(); to ArrayList<String> s = new ArrayList<String>(); it works great now.Dichotomy
have the same error after your update. did the same change i did before and it works now. this was the error it gave me befor my fix: The type List is not generic; it cannot be parameterized with arguments <String>Dichotomy
@Geanine Is that possible when click on item of that list connect to the device?Stood
The implementation for list item click listener totally depends on you. You may definitely extend AdapterView.OnItemClickListener to make Bluetooth connection to the device shown in list. Use listView.setOnItemClickListener to provide your custom click listener.Geanine
T
51

Find list of Nearby Bluetooth Devices:

Find Screenshot for the same.

enter image description here

MainActivity.java:

public class MainActivity extends ActionBarActivity {

    private ListView listView;
    private ArrayList<String> mDeviceList = new ArrayList<String>();
    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<String>(context,
                        android.R.layout.simple_list_item_1, mDeviceList));
            }
        }
    };

activity_main.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.bluetoothdemo.MainActivity" >

    <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/listView"/>

</RelativeLayout>

Manifest file:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.bluetoothdemo"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Note:

Please make sure that you ask Location permission to your user and turn GPS On.

Reason: From Android 6.0 you need Location permission for Bluetooth Discovery.

More reference:

  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-

Done

Translocation answered 8/7, 2015 at 12:44 Comment(12)
@DavidBalas, Glad to help you.Translocation
Does it connect to a paired device clicked?Stood
@Skizo, no, it would not.Translocation
Do you know how can I connect it with a click? I mean if I have a list with all of my paired devices do you know how to connect it with 1 click?Stood
I am trying this code.It is provide all paired devices. How can I get ReadyToPair device?Is there any way to achieve this thing?Ellipsoid
Is there a reason why the same device appears more than once in the list?Hickman
you need to add 2 more permissions <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />Drudge
@SruitA.Suk You don't need both of these permissions. You can ask any one of these. If you want to work on approximate location then you should go for 'ACCESS_COARSE_LOCATION' else 'ACCESS_FINE_LOCATION'.Beechnut
@HirenPatel This worked for me but I have one question. I have one device which is scanned using bluetoothAdapter.startDiscovery() but not with scanner.startScan(callBack) method. What could be the reason?Beechnut
can uh tell me whats this 0C:60:70 and soo on below every devices is this mac address of other devices if yes how can i access our own mac address of bluetooth ??Hammered
@Hammered To get your own Bluetooth MAC address use the below code. private static final String SECURE_SETTINGS_BLUETOOTH_ADDRESS = "bluetooth_address"; String macAddress = Settings.Secure.getString(getContentResolver(), SECURE_SETTINGS_BLUETOOTH_ADDRESS);Calm
BroadcastReceiver's onReceive is not triggered any ideas why?Ellga
B
10

I tried the below code,

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    />
<TextView 
    android:id="@+id/bluetoothstate" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    />
<Button
    android:id="@+id/listpaireddevices" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"
    android:text="List Paired Devices" 
    android:enabled="false"
    /> 
<TextView
    android:id="@+id/bluetoothstate" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    />

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<String> btArrayAdapter 
    = new ArrayAdapter<String>(this,
             android.R.layout.simple_list_item_1);

  BluetoothAdapter bluetoothAdapter 
   = BluetoothAdapter.getDefaultAdapter();
  Set<BluetoothDevice> 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

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.test.AndroidBluetooth"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="7" />
    <uses-permission android:name="android.permission.BLUETOOTH"></uses-permission>

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".AndroidBluetooth"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
  <activity android:name=".ListPairedDevicesActivity" 
      android:label="AndroidBluetooth: List of Paired Devices"/>
    </application>
</manifest>
Banna answered 29/5, 2012 at 8:25 Comment(1)
Does it connect to the paired device with a click?Stood
B
4
package com.sekurtrack.myapplication;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Set;

public class MainActivity extends AppCompatActivity {
    ListView listView;
    private BluetoothAdapter BA;
    private ArrayList<String> mDeviceList = new ArrayList<String>();
    private Set<BluetoothDevice> pairedDevices;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView=(ListView)findViewById(R.id.devicesList);



        BA = BluetoothAdapter.getDefaultAdapter();
        BA.startDiscovery();
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(mReceiver, filter);

       /* BA = BluetoothAdapter.getDefaultAdapter();
        pairedDevices = BA.getBondedDevices();
        ArrayList list = new ArrayList();
        for(BluetoothDevice bt : pairedDevices) list.add(bt.getName());
        Toast.makeText(getApplicationContext(), "Showing Paired Devices",Toast.LENGTH_SHORT).show();
        final ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, list);
        listView.setAdapter(adapter);*/

    }


    @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("BT1", device.getName() + "\n" + device.getAddress());
                listView.setAdapter(new ArrayAdapter<String>(context,
                        android.R.layout.simple_list_item_1, mDeviceList));
            }
        }
    };
}
Bor answered 9/4, 2018 at 13:29 Comment(1)
While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value.Bossuet
D
2

In this code you just need to call this in your button click.

private void list_paired_Devices() {
        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
        ArrayList<String> devices = new ArrayList<>();
        for (BluetoothDevice bt : pairedDevices) {
            devices.add(bt.getName() + "\n" + bt.getAddress());
        }
        ArrayAdapter arrayAdapter = new ArrayAdapter(bluetooth.this, android.R.layout.simple_list_item_1, devices);
        emp.setAdapter(arrayAdapter);
    }
Darrow answered 3/4, 2017 at 14:56 Comment(0)
M
0

Here is an easy way to do it in Kotlin:

BluetoothActivity.kt

import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.os.Bundle
import android.view.View
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity


class BluetoothActivity : AppCompatActivity() {

private var mBTArrayAdapter: ArrayAdapter<String>? = null
private var mBTAdapter: BluetoothAdapter? = null
private var mPairedDevices: Set<BluetoothDevice>? = null

private var mListPairedDevicesBtn: Button? = null

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_bluetooth)

    mBTArrayAdapter = ArrayAdapter(this, android.R.layout.simple_list_item_1)
    mBTAdapter = BluetoothAdapter.getDefaultAdapter()

    mListPairedDevicesBtn = findViewById<View>(R.id.paired_btn) as Button

    mListPairedDevicesBtn!!.setOnClickListener { listPairedDevices() }

}

private fun listPairedDevices() {
    mBTArrayAdapter?.clear()
    mPairedDevices = mBTAdapter?.bondedDevices
    if (mBTAdapter?.isEnabled == true) {
        for (device in mPairedDevices!!) mBTArrayAdapter?.add(device.name + "\n" + device.address)
    } else Toast.makeText(applicationContext,
        "Please Switch On The Bluetooth First",
        Toast.LENGTH_SHORT).show()
}

}

The list view:

<Button
        android:id="@+id/paired_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Paired Devices"
        android:layout_marginTop="5dp"
        android:textSize="16sp"/>

Please tell me if it works for you!

Matronize answered 16/12, 2021 at 8:22 Comment(0)
R
0

Here is how I did it inside a fragment ...

    val bluetoothManager = this.activity?.getSystemService(AppCompatActivity.BLUETOOTH_SERVICE) as BluetoothManager
    val bluetoothAdapter = bluetoothManager.adapter
    val pairedButton = view.findViewById<Button>(R.id.pairedButton)

pairedButton.setOnClickListener {

        if (bluetoothAdapter?.isEnabled == true) {

           if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {

                    if (ContextCompat.checkSelfPermission(
                            (activity as MainActivity),
                            Manifest.permission.BLUETOOTH_CONNECT
                        ) == PackageManager.PERMISSION_GRANTED
                    ) {
                        Log.d(tag,"checkSelfPermission()")
                    }

                    } else {

                        // TODO("VERSION.SDK_INT < S")
                    }

                val pairedDevices: Set<BluetoothDevice>? = bluetoothAdapter.bondedDevices
                val pairedList = view.findViewById<TextView>(R.id.pairedDevTextView)
                pairedList.text = null
                pairedDevices?.forEach { device ->
                    // use 'name' or 'alias' (for edited name) 
                    val deviceName = device.alias
                    val deviceHardwareAddress = device.address // MAC address
                    pairedList.append("\nDevice: $deviceName\nMAC: $deviceHardwareAddress\n")
                }

        } else {

            Toast.makeText(context,"Bluetooth Not Enabled", Toast.LENGTH_SHORT).show()

        }

}
Rattray answered 31/8, 2023 at 13:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.