preface
Bluetooth is also divided into classical Bluetooth, low power Bluetooth and dual-mode Bluetooth. The development of technology really exceeds the cognitive speed of individuals. Not learning means regression. It was originally written about the interaction between low power Bluetooth and smart Bluetooth speakers, but it was written at the end, because bluetooth speakers are not ready yet, there is no guarantee for the results of this paper, so it was changed to Bluetooth chat at last. Bluetooth chat may be suitable for special situations such as flying or high-speed trains with no or poor Internet access. The Demo in this article works fine.
The general process of this paper: Discover Bluetooth -> Pair Bluetooth -> Connect Bluetooth -> data interaction
In this process, we mainly deal with some details and exceptions to better reflect user experience.
Declare permissions
Add the following code in the configuration file androidmanifest.xml of the project to enable the APP to have bluetooth access and discover surrounding Bluetooth access.
// Using Bluetooth requires this permission <uses-permission android:name="android.permission.BLUETOOTH"/> // Use uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/> //Android 6.0 declares one of the following permissions. <uses-permission android:name= <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
Copy the code
Android 6.0 above dynamically apply for permission location permission, otherwise it is prohibited by default, and bluetooth list cannot be obtained.
/** * Android 6.0 Otherwise the scan Bluetooth list is empty */ private void requestPermissions() {if (build.version.sdk_int >= build.version_codes.m) {if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) ! = PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.shouldShowRequestPermissionRationale(this, The Manifest. Permission. ACCESS_COARSE_LOCATION)) {Toast. MakeText (this, "using bluetooth need authorized location information", Toast. LENGTH_LONG). The show (); } / / request permissions ActivityCompat. RequestPermissions (this, new String [] {the Manifest. Permission. ACCESS_COARSE_LOCATION}, REQUEST_ACCESS_COARSE_LOCATION_PERMISSION); } } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == REQUEST_ACCESS_COARSE_LOCATION_PERMISSION) { if (grantResults.length > 0 && grantResults [0] = = PackageManager. PERMISSION_GRANTED) {/ / user authorization} else {finish (); } } super.onRequestPermissionsResult(requestCode, permissions, grantResults); }Copy the code
The user experience of handling authorization is not good. Authorization continues, and disauthorization exits. The authorization logic can be handled separately according to your needs.
Whether the device supports Bluetooth
Not all Android devices support Bluetooth, so check to see if your current device supports Bluetooth before using it.
private void isSupportBluetooth() {
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(bluetoothAdapter == null || ! getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH)) { showNotSupportBluetoothDialog(); Log.e(TAG,"not support bluetooth");
} else {
Log.e(TAG, " support bluetooth"); }}Copy the code
Class BluetoothAdapter represents the bluetooth of the current device, BluetoothAdapter can get all the bluetooth binding through BluetoothAdapter, scan bluetooth, its name and address, through the address can obtain the surrounding Bluetooth devices. BluetoothAdapter objects can be obtained in two ways.
/ / a mBluetoothAdapter = BluetoothAdapter. GetDefaultAdapter (); BluetoothManager manager= (BluetoothManager) getSystemService(context.bluetooth_service); mBluetoothAdapter= manager.getAdapter();Copy the code
Open the bluetooth
Check whether bluetooth is enabled first. If not, prompt the user to open it, or open it directly.
// The user is prompted to enable Bluetooth, and a pop-up box is displayed for the user to choose whether to enable private voidenableBLE() {
if(! bluetoothAdapter.isEnabled()) { Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(intent, REQUEST_BLE_OPEN); } } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data);if (requestCode == 1) {
if(resultCode == RESULT_OK) { scanBle(); }} // Set the code directly to private voidenableBLE() {
if (!bluetoothAdapter.isEnabled()) {
bluetoothAdapter.enable();
}
}
Copy the code
Settings can be found
After bluetooth is enabled, you need to set yourself to be searched by the surrounding Bluetooth so that you can proceed with the next step. Bluetooth can be searched by peripheral devices within 120 seconds by default, and the maximum setting is less than 300 seconds. I heard that setting 0 can be searched permanently.
/** * Set bluetooth to be searchable by other devices */ private voidbeDiscovered() {
if (mBluetoothAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 0);
startActivity(discoverableIntent);
}
}
Copy the code
Collect bluetooth devices around you
Add discovered Bluetooth devices to the collection and display them in the ListView by registering broadcast listeners.
private void registerBluetoothReceiver() {
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(bluetoothReceiver, filter);
}
BroadcastReceiver bluetoothReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(BluetoothDevice.ACTION_FOUND)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
list.add(device);
Log.e(TAG, "discovery:" + device.getName());
bleAdapter.notifyDataSetChanged();
} else if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {
// Toast.makeText(MainActivity.this, "discovery finished", Toast.LENGTH_LONG).show();
btnSearch.setText("Research"); mBluetoothAdapter.cancelDiscovery(); }}};Copy the code
The search results are as follows. You can see that some Bluetooth devices only have Mac addresses, but no names. There is no further processing here. If processing is required, refer to the Bluetooth null processing scheme
Equipment details
After obtaining the Bluetooth list, click the corresponding Bluetooth to enter bluetooth details. A BluetoothDeviced object represents a peripheral Bluetooth device. Through this object, you can obtain the name, binding status, Mac address, UUID and so on of the Bluetooth device.
mDevice.createBond();
Chat box implementation
After matching success, through the BluetoothDevice createRfcommSocketToServiceRecord () method and the bluetooth connection, the connection is successful will be returned BluetoothSocket object, and then get input and output flow, data interaction.
mSocket = device.createRfcommSocketToServiceRecord(UUID.fromString(uuid));
mSocket.connect();
mOutputStream = mSocket.getOutputStream();
mInputStream = mSocket.getInputStream();
Copy the code
The connection process will block the thread, please execute it on the child thread. Uuid and server can be consistent and unique (defined here), through uUID and server binding BluetoothSocket. We synchronize the input and output content to the chat box, then the chat effect is achieved.
BluetoothSocket object server implementation and this similar, specific words can see the source oh.
conclusion
This article briefly describes the bluetooth connection to achieve the chat box process, source code can open GitHub download run, useful star about.
Because of BluetoothSocket closed or abnormal reading and writing, there are some failed to synchronize, each guest officer according to their own needs to deal with. Other time-consuming operations, such as bluetooth connection, do not make progress bar feedback, can be customized according to your own requirements. Demo can be eaten normally.