Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android® Apps
GitHub logo Twitter logo OReilly Book Cover Art

Implementing Bluetooth Device Discovery

Published? true
FormatLanguage: WikiFormat

Problem:

You want to display a list of Bluetooth devices in the vicinity.

Solution:

Simple steps

  1. Create XML file to display the list
  2. Create a class file to load list
  3. Edit manifest file

It's that simple.

Discussion:

1 Create XML file to display the list

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

2 Create a class file to load list


      //IntentFilter will match the action specified
      IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
      //broadcast reciever for any matching filter
      this.registerReceiver(mReciever, filter);
    
      //attach the adapter
      ListView newDevicesListView = (ListView)findViewById(R.id.new_devices);
      newDevicesListView.setAdapter(mNewDevicesArrayAdapter);
    
      
      filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
     this.registerReceiver(mReciever, filter);
     
//Create a reciever for the Intent
private final BroadcastReceiver mReciever = new BroadcastReceiver() {
		
		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			
			String action = intent.getAction();
			
			if(BluetoothDevice.ACTION_FOUND.equals(action)){
				BluetoothDevice btDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
				
				if(btDevice.getBondState() != BluetoothDevice.BOND_BONDED){
					mNewDevicesArrayAdapter.add(btDevice.getName()+"\n"+btDevice.getAddress());
				}
			}
			else
				if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
					setProgressBarIndeterminateVisibility(false);
					setTitle(R.string.select_device);
					if(mNewDevicesArrayAdapter.getCount() == 0){
						String noDevice = getResources().getText(R.string.none_paired).toString();
						mNewDevicesArrayAdapter.add(noDevice);
					}
				}
			
		}
	};

3 Edit manifest file

...

Download:

The source code for this project can be downloaded from http://projects.darwinsys.com/BluetoothDemo-src.zip.