Android connection Bluetooth process (complete code at the end)
- Declare permissions
1) Declare permissions in the AndroidManifest manifest file (Note: Searching for Bluetooth requires location permission!!) <uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" /> <uses-permission android:name="android.permission.BLUETOOTH_SCAN" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> 2) Apply for runtime permissions if (ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED ) {<!-- --> ActivityCompat.requestPermissions(this, new String[]{<!-- --> Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.BLUETOOTH_SCAN, Manifest.permission.BLUETOOTH_CONNECT}, 0); } // Process the results of the permission request in the onRequestPermissionsResult method @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {<!-- --> super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == 0) {<!-- --> if (grantResults.length > 0 & amp; & amp; grantResults[0] == PackageManager.PERMISSION_GRANTED) {<!-- --> // The user has granted Bluetooth connection permission and performs operations related to Bluetooth connection. // Get the pairing list for (BluetoothDevice bondedDevice : bluetoothAdapter.getBondedDevices()) {<!-- --> deviceListAdapter.add(bondedDevice.getName() + "\ " + bondedDevice.getAddress()); } } else {<!-- --> // The user has denied the Bluetooth connection permission. You may need to display a prompt message or provide an explanation. Toast.makeText(this, "Please grant Bluetooth permissions", Toast.LENGTH_LONG).show(); } } }
- Get a Bluetooth adapter
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (bluetoothAdapter == null) {<!-- --> Toast.makeText(MainActivity.this, "This device does not support Bluetooth!", Toast.LENGTH_SHORT).show(); }
- Activate Bluetooth
//Start Bluetooth if (!bluetoothAdapter.isEnabled()) {<!-- --> Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, 1); }
- Create a Bluetooth display list
deviceListView = findViewById(R.id.deviceListView); deviceListAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1); deviceListView.setAdapter(deviceListAdapter);
- Register a Bluetooth broadcast receiver (for receiving results of Bluetooth searches)
//Register Bluetooth broadcast receiver IntentFilter filter = new IntentFilter(); filter.addAction(BluetoothDevice.ACTION_FOUND); filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED); filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED); registerReceiver(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); deviceListAdapter.add(device.getName() + "\ " + device.getAddress()); } } }, filter);
- Search bluetooth
if (bluetoothAdapter.isDiscovering()) {<!-- --> bluetoothAdapter.cancelDiscovery(); } deviceListAdapter.clear(); bluetoothAdapter.startDiscovery();
- Connect Bluetooth (executed in asynchronous code)
// Connect to Bluetooth deviceListView.setOnItemClickListener((parent, view, position, id) -> {<!-- --> String deviceInfo = (String) parent.getItemAtPosition(position); String deviceAddress = deviceInfo.substring(deviceInfo.length() - 17); BluetoothDevice myDevice = bluetoothAdapter.getRemoteDevice(deviceAddress); new Thread(new Runnable() {<!-- --> @Override public void run() {<!-- --> try {<!-- --> Looper.prepare(); if (mySocket != null) {<!-- --> Toast.makeText(MainActivity.this, "Disconnect connected Bluetooth", Toast.LENGTH_SHORT).show(); mySocket.close(); } mySocket = myDevice.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB")); // uuid is universal mySocket.connect(); myOutStream = mySocket.getOutputStream(); myInStream = mySocket.getInputStream(); Toast.makeText(MainActivity.this, "Bluetooth connected:" + myDevice.getName(), Toast.LENGTH_SHORT).show(); } catch (Exception e2) {<!-- --> Toast.makeText(MainActivity.this, "Bluetooth connection failed" + e2.getMessage(), Toast.LENGTH_SHORT).show(); myInStream = null; myOutStream = null; mySocket = null; } Looper.loop(); } }).start(); });
Key API
// Get Bluetooth adapter BluetoothAdapter.getDefaultAdapter(); // Whether Bluetooth is enabled bluetoothAdapter.isEnabled(); // Turn on Bluetooth Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, 1); // Is Bluetooth searching? bluetoothAdapter.isDiscovering(); //Search for Bluetooth bluetoothAdapter.startDiscovery(); // Stop searching for Bluetooth bluetoothAdapter.cancelDiscovery(); // Get Bluetooth device bluetoothAdapter.getRemoteDevice(); // Get Bluetooth socket BluetoothSocket mySocket = myDevice.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB")); // Connect Bluetooth mySocket.connect(); // Get the input stream and output stream myOutStream = mySocket.getOutputStream(); myInStream = mySocket.getInputStream();
Complete code
MainActivity
package com.example.bluetoothdemo; import android.Manifest; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.os.Bundle; import android.os.Looper; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import java.io.InputStream; import java.io.OutputStream; import java.util.UUID; public class MainActivity extends AppCompatActivity {<!-- --> private BluetoothAdapter bluetoothAdapter; // Bluetooth private ArrayAdapter<String> deviceListAdapter; private ListView deviceListView; private static BluetoothSocket mySocket = null; private static OutputStream myOutStream = null; private static InputStream myInStream = null; // runtime permissions public static final String[] PERMISSIONS = new String[]{<!-- --> Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.BLUETOOTH_SCAN, Manifest.permission.BLUETOOTH_CONNECT, }; @Override protected void onCreate(Bundle savedInstanceState) {<!-- --> super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Check Bluetooth scanning permissions if (ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {<!-- --> ActivityCompat.requestPermissions(this, new String[]{<!-- --> Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.BLUETOOTH_SCAN, Manifest.permission.BLUETOOTH_CONNECT}, 0); } // Get Bluetooth bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (bluetoothAdapter == null) {<!-- --> Toast.makeText(MainActivity.this, "This device does not support Bluetooth!", Toast.LENGTH_SHORT).show(); return; } //Set Bluetooth list deviceListView = findViewById(R.id.deviceListView); deviceListAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1); deviceListView.setAdapter(deviceListAdapter); // Start Bluetooth if (!bluetoothAdapter.isEnabled()) {<!-- --> Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, 1); } //Register Bluetooth broadcast receiver IntentFilter filter = new IntentFilter(); filter.addAction(BluetoothDevice.ACTION_FOUND); filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED); filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED); registerReceiver(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); deviceListAdapter.add(device.getName() + "\ " + device.getAddress()); } } }, filter); Button startScanBluetooth = findViewById(R.id.start_scan_bluetooth); // Search for Bluetooth Button stopScanBluetooth = findViewById(R.id.stop_scan_bluetooth); // Stop searching for Bluetooth startScanBluetooth.setOnClickListener(new View.OnClickListener() {<!-- --> @Override public void onClick(View view) {<!-- --> if (bluetoothAdapter.isDiscovering()) {<!-- --> bluetoothAdapter.cancelDiscovery(); } deviceListAdapter.clear(); bluetoothAdapter.startDiscovery(); } }); stopScanBluetooth.setOnClickListener(new View.OnClickListener() {<!-- --> @Override public void onClick(View view) {<!-- --> bluetoothAdapter.cancelDiscovery(); } }); // Connect Bluetooth deviceListView.setOnItemClickListener((parent, view, position, id) -> {<!-- --> String deviceInfo = (String) parent.getItemAtPosition(position); String deviceAddress = deviceInfo.substring(deviceInfo.length() - 17); BluetoothDevice myDevice = bluetoothAdapter.getRemoteDevice(deviceAddress); new Thread(new Runnable() {<!-- --> @Override public void run() {<!-- --> try {<!-- --> Looper.prepare(); if (mySocket != null) {<!-- --> Toast.makeText(MainActivity.this, "Disconnect connected Bluetooth", Toast.LENGTH_SHORT).show(); mySocket.close(); } mySocket = myDevice.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB")); // uuid is universal mySocket.connect(); myOutStream = mySocket.getOutputStream(); myInStream = mySocket.getInputStream(); Toast.makeText(MainActivity.this, "Bluetooth connected:" + myDevice.getName(), Toast.LENGTH_SHORT).show(); } catch (Exception e2) {<!-- --> Toast.makeText(MainActivity.this, "Bluetooth connection failed" + e2.getMessage(), Toast.LENGTH_SHORT).show(); myInStream = null; myOutStream = null; mySocket = null; } Looper.loop(); } }).start(); }); } // Process the results of the permission request in the onRequestPermissionsResult method @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {<!-- --> super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == 0) {<!-- --> if (grantResults.length > 0 & amp; & amp; grantResults[0] == PackageManager.PERMISSION_GRANTED) {<!-- --> // The user has granted Bluetooth connection permission and performs operations related to Bluetooth connection. //Paired list for (BluetoothDevice bondedDevice : bluetoothAdapter.getBondedDevices()) {<!-- --> deviceListAdapter.add(bondedDevice.getName() + "\ " + bondedDevice.getAddress()); } } else {<!-- --> // The user has denied the Bluetooth connection permission. You may need to display a prompt message or provide an explanation. Toast.makeText(this, "Please grant Bluetooth permissions", Toast.LENGTH_LONG).show(); } } } }
activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout 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=".MainActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <Button android:id="@ + id/start_scan_bluetooth" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Search Bluetooth" /> <Button android:id="@ + id/stop_scan_bluetooth" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Stop searching for Bluetooth" /> <ListView android:id="@ + id/deviceListView" android:layout_marginTop="30dp" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout> </androidx.constraintlayout.widget.ConstraintLayout>