To discover and pair Bluetooth Devices
the following code will discover the list of paired and the unpaired devices after that u have to implement the Client and server, which takes care of pairing the devices and sending data to the devices, for tat u can make use of the BluetoothChatSample which will give an idea to u.
private Set pairedDevices; public static ArrayList BondedDeviceList; public static ArrayList NewDeviceList; public void makeDiscoverable() < discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300); activity.startActivity(discoverableIntent); >//It will Add the paired device in the BondedDeviceList public void queryPairedDevice()< pairedDevices = mBluetoothAdapter.getBondedDevices(); // If there are paired devices if(pairedDevices==null) < //No Bonded Devices >else < if (pairedDevices.size() >0) < // Loop through paired devices for (BluetoothDevice device : pairedDevices) < BondedDeviceList.add(device); >BondedDeviceList.add("End"); > > > //Broadcast Receiver will find the Available devices and the discovery finished private final BroadcastReceiver mReceiver = new BroadcastReceiver() < @Override public void onReceive(Context context, Intent intent) < String action = intent.getAction(); // When discovery finds a device if (BluetoothDevice.ACTION_FOUND.equals(action.trim())) < // Get the BluetoothDevice object from the Intent BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); // If it's already paired, skip it, because it's been listed already if (device.getBondState() != BluetoothDevice.BOND_BONDED) < NewDeviceList.add(device); >// When discovery is finished, change the Activity title > else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) < if (NewDeviceList.isEmpty() == true) < String noDevices = "No Devices"; NewDeviceList.add(noDevices); >System.out.println("Discovery Finished. "); NewDeviceList.add("End"); > > >; //This is query for the bluetooth devices public void queryDevices() < actionFoundFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND); activity.registerReceiver(mReceiver, actionFoundFilter); // Don't forget to unregister during onDestroy discoveryFinishedFilter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); activity.registerReceiver(mReceiver, discoveryFinishedFilter); // Don't forget to unregister during onDestroy queryPairedDevice(); mBluetoothAdapter.startDiscovery(); >//Unregister the receivers public void unregisterReceiver() < // Make sure we're not doing discovery anymore if (mBluetoothAdapter != null) < mBluetoothAdapter.cancelDiscovery(); >// Unregister broadcast listeners activity.unregisterReceiver(mReceiver); >
Android + Pair devices via bluetooth programmatically
I want to discover bluetooth devices in range, list and pair to them on click. I used following code but its just closing application when I click on device name which I want to pair. I want to know mistake in my code or any other way to do what i need.
package com.marakana; import java.util.Set; import android.app.Activity; 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.os.Bundle; import android.util.Log; import android.view.View; import android.view.Window; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import android.widget.AdapterView.OnItemClickListener; public class BluetoothDemo extends Activity < // Debugging private static final String TAG = "DeviceListActivity"; private static final boolean D = true; // Return Intent extra public static String EXTRA_DEVICE_ADDRESS = "device_address"; // Member fields private BluetoothAdapter mBtAdapter; private ArrayAdaptermPairedDevicesArrayAdapter; private ArrayAdapter mNewDevicesArrayAdapter; @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); // Setup the window requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.device_list); // Set result CANCELED incase the user backs out setResult(Activity.RESULT_CANCELED); // Initialize the button to perform device discovery Button scanButton = (Button) findViewById(R.id.button_scan); scanButton.setOnClickListener(new OnClickListener() < public void onClick(View v) < doDiscovery(); v.setVisibility(View.GONE); >>); // Initialize array adapters. One for already paired devices and // one for newly discovered devices mPairedDevicesArrayAdapter = new ArrayAdapter(this, R.layout.device_name); mNewDevicesArrayAdapter = new ArrayAdapter(this, R.layout.device_name); // Find and set up the ListView for paired devices ListView pairedListView = (ListView) findViewById(R.id.paired_devices); pairedListView.setAdapter(mPairedDevicesArrayAdapter); pairedListView.setOnItemClickListener(mDeviceClickListener); // Find and set up the ListView for newly discovered devices ListView newDevicesListView = (ListView) findViewById(R.id.new_devices); newDevicesListView.setAdapter(mNewDevicesArrayAdapter); newDevicesListView.setOnItemClickListener(mDeviceClickListener); // Register for broadcasts when a device is discovered IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); this.registerReceiver(mReceiver, filter); // Register for broadcasts when discovery has finished filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); this.registerReceiver(mReceiver, filter); // Get the local Bluetooth adapter mBtAdapter = BluetoothAdapter.getDefaultAdapter(); // Get a set of currently paired devices Set pairedDevices = mBtAdapter.getBondedDevices(); // If there are paired devices, add each one to the ArrayAdapter if (pairedDevices.size() > 0) < findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE); for (BluetoothDevice device : pairedDevices) < mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress()); >> else < String noDevices = getResources().getText(R.string.none_paired).toString(); mPairedDevicesArrayAdapter.add(noDevices); >> @Override protected void onDestroy() < super.onDestroy(); // Make sure we're not doing discovery anymore if (mBtAdapter != null) < mBtAdapter.cancelDiscovery(); >// Unregister broadcast listeners this.unregisterReceiver(mReceiver); > /** * Start device discover with the BluetoothAdapter */ private void doDiscovery() < if (D) Log.d(TAG, "doDiscovery()"); // Indicate scanning in the title setProgressBarIndeterminateVisibility(true); setTitle(R.string.scanning); // Turn on sub-title for new devices findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE); // If we're already discovering, stop it if (mBtAdapter.isDiscovering()) < mBtAdapter.cancelDiscovery(); >// Request discover from BluetoothAdapter mBtAdapter.startDiscovery(); > // The on-click listener for all devices in the ListViews private OnItemClickListener mDeviceClickListener = new OnItemClickListener() < public void onItemClick(AdapterViewav, View v, int arg2, long arg3) < // Cancel discovery because it's costly and we're about to connect mBtAdapter.cancelDiscovery(); // Get the device MAC address, which is the last 17 chars in the View String info = ((TextView) v).getText().toString(); String address = info.substring(info.length() - 17); // Create the result Intent and include the MAC address Intent intent = new Intent(); intent.putExtra(EXTRA_DEVICE_ADDRESS, address); // Set result and finish this Activity setResult(Activity.RESULT_OK, intent); finish(); >>; // The BroadcastReceiver that listens for discovered devices and // changes the title when discovery is finished private final BroadcastReceiver mReceiver = new BroadcastReceiver() < @Override 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); // If it's already paired, skip it, because it's been listed already if (device.getBondState() != BluetoothDevice.BOND_BONDED) < mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress()); >// When discovery is finished, change the Activity title > else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) < setProgressBarIndeterminateVisibility(false); setTitle(R.string.select_device); if (mNewDevicesArrayAdapter.getCount() == 0) < String noDevices = getResources().getText(R.string.none_found).toString(); mNewDevicesArrayAdapter.add(noDevices); >> > >; >
How to get the bluetooth devices as a list?
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 pairedDevices = mBluetoothAdapter.getBondedDevices(); ArrayList listview = new ArrayList(Arrays.asList(pairedDevices.toString())); setListAdapter(new ArrayAdapter(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.
6 Answers 6
You should change your code as below:
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));
yea. Thanks. only need to add that i changed List
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
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.
Find list of Nearby Bluetooth Devices:
Find Screenshot for the same.
MainActivity.java:
public class MainActivity extends ActionBarActivity < private ListView listView; private ArrayListmDeviceList = 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:
Manifest file:
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:
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?
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?
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); ArrayAdapterbtArrayAdapter = 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