Android Programming
In order for Bluetooth devices to transfer data between each other:
- First, they must form a channel of communication using a pairing process. One device, a discoverable device, makes itself available for incoming connection requests. Another device finds the discoverable device using a service discovery process. After the discoverable device accepts the pairing request, the two devices complete a bonding process where they exchange security keys. The devices cache these keys for later use.
- After the pairing and bonding processes are complete, the two devices exchange information.
- When the session is complete, the device that initiated the pairing request releases the channel that had linked it to the discoverable device. The two devices remain bonded, however, so they can reconnect automatically during a future session as long as they’re in range of each other and neither device has removed the bond.
Android Permissions
You need to declare these permissions in the » AndroidManifest.xml «:
- android.permission.BLUETOOTH : for performing Bluetooth communication, such as requesting a connection, accepting a connection, and transferring data.
- android.permission.BLUETOOTH_ADMIN : for discovering local Bluetooth devices.
- android.permission.ACCESS_COARSE_LOCATION or android.permission.ACCESS_FINE_LOCATION : for gathering information about the location of the user. This information may come from the user’s own device, or Bluetooth beacons in use at locations such as shops.
Android Bluetooth By Examples
Example 1
Start «Android Studio» ⇒ Start a new Andriod Studio Project ⇒ In «Create Android Project» dialog, enter «Hello Bluetooth» in «Application Name» and «example.com» in «Company Domain». Set your «Project Location». Uncheck «Include C++ Support» ⇒ In «Select the form factors and minimum SDK», check «Phone and Tablet» and choose «API 15» ⇒ In «Add an Activity to Mobile», select «Empty Activity» ⇒ In «Creates a new empty activity», enter «MainActivity» to «Activity Name» and «activity_main» to «Layout name» ⇒ Finish.
Setting up Bluetooth
First, get a BluetoothAdapter via static method BluetoothAdapter.getDefaultAdapter() . It returns the device’s Bluetooth adapter; or null if the device does not support Bluetooth.
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (bluetoothAdapter == null) < // Device doesn't support Bluetooth Toast.makeText(this, "error: bluetooth not supported", Toast.LENGTH_LONG).show(); >
private static final int REQUEST_ENABLE_BT = 1; . if (!bluetoothAdapter.isEnabled()) < Intent enableBluetoothIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBluetoothIntent, REQUEST_ENABLE_BT); >// Called Back when the started activity returns a result public void onActivityResult(int requestCode, int resultCode, Intent result) < if (requestCode == REQUEST_ENABLE_BT) < // Match the request code if (resultCode == RESULT_OK) < Toast.makeText(this, "Bluetooth Turned on", Toast.LENGTH_LONG).show(); >else < // RESULT_CANCELED Toast.makeText(this, "error: turning on bluetooth", Toast.LENGTH_LONG).show(); > > >
- The isEnabled() returns false if Bluetooth is disabled.
- To enable Bluetooth, call startActivityForResult() with an intent BluetoothAdapter.ACTION_REQUEST_ENABLE . This call issues a request to enable Bluetooth through the system settings without stopping your application. A dialog appears to request user permission to enable Bluetooth.
- The REQUEST_ENABLE_BT is a constant that must be greater than 0. The system passes this request code back to onActivityResult() ; and result code of RESULT_OK or RESULT_CANCELLED .
- You can invoke disable() to disable bluetooth.
Finding Devices
Using the BluetoothAdapter , you can find remote Bluetooth devices either through device dicovery or by querying the list of paired devices.
Device discovery searches Bluetooth-enabled devices and requests some information. A Bluetooth device responds to a discovery request only if it is currently accepting information requests by being discoverable. It responds to the discovery request by sending back information such as device’s name, its class and its MAC address. The discovering device can then choose to initiate a connection to the discovered device.
Once a connection is established, a pairing request is presented to the user. When a device is paired, the basic information about that device (such as device name, class and MAC address) is saved, and connection can be initiated later without performing discovery.
Before performing device discovery, we shall query the set of paired devices to see if the desired device is already known, via getBondedDevices() . For example,
Set pairedDevices = mBluetoothAdapter.getBondedDevices(); if (pairedDevices.size() > 0) < // There are paired devices. Get the name and address of each paired device. for (BluetoothDevice device : pairedDevices) < String deviceName = device.getName(); // device name String deviceHardwareAddress = device.getAddress(); // MAC address > >
Latest version tested: Android 7.1 (Nougat) 8 (Oreo), Android Studio 3.0.1
Last modified: March, 2018
connecting paired devices in Bluetooth using android studio
I have created an app to display paired devices successfully but not able to connect to it. I tried a lot but i’m getting «app has been stopped working». Please advise on issues in my code to connect to paired devices:
public class MainActivity extends AppCompatActivity < public static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); BluetoothAdapter bt; ArrayAdapterlistAdapter; Set devicesArray; ListView listview; Button connectbutton; Handler mHandler = new Handler() < @Override public void handleMessage(Message msg) < // TODO Auto-generated method stub super.handleMessage(msg); Toast.makeText(getApplicationContext(), "CONNECT", Toast.LENGTH_SHORT).show(); >>; @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); if(bt==null)< Toast.makeText(getApplicationContext(), "no bluetooth on device",Toast.LENGTH_SHORT).show(); finish(); >else < if(!bt.isEnabled())< Intent intent=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(intent,1); >> listview.setOnItemClickListener(new AdapterView.OnItemClickListener() < @Override public void onItemClick(AdapterViewparent, View arg1, int arg2, long arg3) < Toast.makeText(getApplicationContext(), (CharSequence) parent.getItemAtPosition(arg2), Toast.LENGTH_SHORT).show(); if(bt.isDiscovering()) < bt.cancelDiscovery(); >BluetoothDevice selectedDevice = (BluetoothDevice) parent.getItemAtPosition(arg2); > >); > public void onButtonClick(View v) < getpaireddevices(); >public void onButtonClick2(View v) < startdiscovery(); >private void getpaireddevices() < devicesArray = bt.getBondedDevices(); if (devicesArray.size() >0) < for (BluetoothDevice device : devicesArray) listAdapter.add(device.getName()); >> private void startdiscovery() < bt.cancelDiscovery(); bt.startDiscovery(); >private void init() < listview = (ListView)findViewById(R.id.listView); connectbutton = (Button)findViewById(R.id.button); listAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,0); listview.setAdapter(listAdapter); bt= BluetoothAdapter.getDefaultAdapter(); > @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) < super.onActivityResult(requestCode, resultCode, data); if(resultCode == RESULT_CANCELED) < Toast.makeText(getApplicationContext(), "bluetooth must be turned on to continue",Toast.LENGTH_SHORT).show(); finish(); >>