Classic Bluetooth Implementation

This is basically a kind of tutorial which will be useful if you are learning and implementing bluetooth in your android app. In this tutorial I have shared the code for scanning of the Classic Bluetooth devices in range and fetching the paired devices list, moreover I will find some time to write about the implementation of further aspects of classic bluetooth.

Android offers bluetooth API that lets you share your stuff wireless. As per Bluetooth standards it offers you short range (10 m approx.) device connectivity. This API let application to the Bluetooth devices and enable point to point or multipoint wireless feature. Here we are discussing about the Classic Bluetooth that consumes more battery life.

Bluetooth devices with low power requirement Android 4.3 (API level 18) introduces support for Bluetooth Low Energy, I have talked about it in my last blog. We will get to understand about  the API by creating a sample application that lets you share you stuff over bluetooth.

To start with we will first find to check that whether our device support bluetooth or not. For this we need to use Bluetooth Adapter class. Bluetooth Adapter is some sort of entry – point for all bluetooth interaction.

———————————————————-
Fetching Paired Devices using Bluetooth Adapter
———————————————————-

public class MainActivity extends Activity {

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

		 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

		 if(Utility.isAllowDebug()){
			 System.out.println("---------BLUETOOTH ADAPTER--------"+mBluetoothAdapter);
		 }
		 if (mBluetoothAdapter == null) {
			// Device does not support Bluetooth
		 }else{

			//Device Support Bluetooth
		}
	}
}

The above code tells you about the bluetooth availability in your device.

Now what next to do! It’s quite simple if we found bluetooth then turns it on. For turning bluetooth states we have to add an Intent Action (ACTION_REQUEST_ENABLE) that invokes a system call to change the bluetooth state. After doing all this, we will get the result in onActivityResult method. Here we will list all the paired devices, and set it into a list adapter to display devices in a list view

 

private static final int REQUEST_ENABLE_BT = 1;
private ArrayAdapter<String> mArrayAdapter = null;
private ListView mList = null;

@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		mArrayAdapter = new ArrayAdapter<String>(this, R.layout.list_text_content);
		mList = (ListView) findViewById(R.id.list);
		mList.setAdapter(mArrayAdapter);
		-------
		-------
		}else{
				if (!mBluetoothAdapter.isEnabled()) {
				// if bluetooth is not enabled make it enable
				Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
			    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
			}
		}

	}

 @Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		super.onActivityResult(arg0, arg1, arg2);

		if(arg0 == REQUEST_ENABLE_BT){
			if(arg1 == RESULT_OK){

				/**
				 * for fetching list of paired devices
				 */

				Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
				// If there are paired devices
				if (pairedDevices.size() > 0) {
				    // Loop through paired devices
				    for (BluetoothDevice device : pairedDevices) {
						// Add the name and address to an array adapter to show in a ListView
				        mArrayAdapter.add(device.getName() + "\n" + device.getAddress());

				    }
						mArrayAdapter.notifyDataSetChanged();
				}
			}

		}
	}

——————————-
Discovering Devices
——————————-

All this will give you the paired devices list; now let’s have a look over discovering nearby devices and sending them a request to connect, for this you have to make your receiver class that will catch the bluetooth intent on finding any nearby bluetooth device, on Main Activity instantiate your receiver class and register it for BluetoothDevice. ACTION_FOUND intent.

 

@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		-------
		-------

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

	}

	BluetoothDevicesReceiver class

	public class BluetoothDevicesReceiver extends 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);
			// here write code for bluetooth device detail
			}
		}
	}

 

Now create a method in the main activity to store the device information and notify the adapter to change the list with the newly searched device, and invoke that method from the receiver class through instance of main activity.

 

MainActivity

	@Override
		protected void onCreate(Bundle savedInstanceState) {
		-------
		-------
		mBluetoothAdapter.startDiscovery();
		mReceiver = new BluetoothDevicesReceiver();
		mReceiver.setMainActivity(this);
		mReceiver.setmArray(mArrayAdapter)
		IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
		registerReceiver(mReceiver, filter); 

	}
	/**
	*
	*invoke from receiver class on any bluetooth device found
	**/
	public void listOfSearchDevices(ArrayAdapter<String> iArray){

		mArrayAdapter = iArray;
		mArrayAdapter.notifyDataSetChanged();
	}

	BluetoothDevicesReceiver class

	public class BluetoothDevicesReceiver extends BroadcastReceiver {

	private ArrayAdapter<String> mArray = null;
	private MainActivity mActivity = null;

	 public void setMainActivity(MainActivity iActivity){

		this.mActivity = iActivity;
	}

	public void setmArray(ArrayAdapter<String> iArray){
		this.mArray = iArray;
	}
	public BluetoothDevicesReceiver(ArrayAdapter<String> iArray,
			boolean isFromMainActivty) {
	}
	@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);

				mArray.add(device.getName() + "\n" + device.getAddress());
				mActivity.listOfSearchDevices(mArray);

			}
		}
	}

In this way you can implement classic bluetooth in your android app.

Thank you for your time 🙂

Written By: Trayambak Mishra, Software Developer, Mindfire Solutions

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s