Bluetooth development learning record

Recently, I encountered the business of using Bluetooth to transmit data in the project. I recorded it with a learning attitude, personal understanding, and welcome to leave a message if there are errors or additions. Enough talk, let's get down to business

1. What is Bluetooth
Bluetooth is one of the most widely used wireless communication protocols
Mainly for short-distance device communication (10 meters)
Commonly used to connect headphones, mice and mobile communication devices, etc.

2. Discover surrounding Bluetooth devices
BluetoothAdapter: represents the local Bluetooth adapter
BluetoothDevice: Represents a remote Bluetooth device
 
Scan for paired Bluetooth devices:
1. Declare Bluetooth permissions in AndroidManifest.xml

Permissions must be noted here. After android6.0, in order to better protect the data security of users, all places that need to access hardware unique identifiers need to apply for location permissions, that is, they need to apply for location permissions.
  

<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission-sdk-23 android:name="android.permission.ACCESS_COARSE_LOCATION"/>

Bluetooth permissions are normal-level permissions, you only need to apply for them in Manifest, but location permissions are dangerous-level permissions. In addition to applying in Manifest, you also need to apply dynamically in the code, and track the user's confirmation of permissions result! ! (Without authorization, you will definitely not be able to use the complete function, but it does not seem to affect us to turn on Bluetooth, and the device search function of Bluetooth cannot be used)

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);
    }
}

Judge the user's authorization result in the authorization result callback function:

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    boolean grantedLocation = true;
    switch (requestCode) {
        case PERMISSION_REQUEST_COARSE_LOCATION:
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                grantedLocation = false;
            }
            if(!grantedLocation){
                Toast.makeText(this,"Permission error !!!",Toast.LENGTH_SHORT).show();
                finish();
            }

            break;
    }
    
}

 

2. Get the BluetoothAdapter object

3. Determine whether there is a Bluetooth device in the current device

4. Determine whether the Bluetooth device in the current device has been turned on

 // Initialize the bluetooth device
    private void init() {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        // Check if the device supports bluetooth devices
        if (mBluetoothAdapter == null) {
            Log.d(TAG, "Device does not support Bluetooth");
            // Bluetooth is not supported, exit.
            return;
        }
        // If the user's device does not have Bluetooth enabled, a dialog box for enabling the Bluetooth device will pop up, allowing the user to enable Bluetooth.
        if (!mBluetoothAdapter.isEnabled()) {
            Log.d(TAG, "Ask the user to turn on bluetooth");
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
            // Next, judge in the onActivityResult callback
        }
    }

3. Modify the visibility of native bluetooth devices

// optional method, not required
    // This method enables its own Bluetooth device to be scanned by other Bluetooth devices,
    // Note the time threshold.  0 - 3600 seconds.
    // The usual setting time is 120 seconds.
    private void enable_discovery() {
        Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);

        // The range of the second parameter can be set from 0 to 3600 seconds, and can be found within this time interval (window period).
        // Any value outside this range will be automatically set to 120 seconds.
        discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 3600);

        startActivity(discoverableIntent);
    }

4. Scan for available Bluetooth devices around

// Start bluetooth discovery...
    private void discovery() {
        if (mBluetoothAdapter == null) {
            init();
        }

        mBluetoothAdapter.startDiscovery();
    }




 // Register a broadcast receiver.
        // receive bluetooth discovery
        IntentFilter filterFound = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(mReceiver, filterFound);

        IntentFilter filterStart = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        registerReceiver(mReceiver, filterStart);

        IntentFilter filterFinish = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        registerReceiver(mReceiver, filterFinish);







 // Broadcast reception discovers bluetooth devices
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
                ToastUtils.showMessage(mContext,"start scanning...");
                Log.d(TAG, "start scanning...");
            }

            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                Log.d(TAG, "scan result.");
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (device != null) {
                    // Adapter added to ListView.
                    if(!TextUtils.isEmpty(device.getName())){
                        mAdapter.add(device.getName() + "\n" + device.getAddress());
                        mAdapter.notifyDataSetChanged();
                    }
                    devices.add(device);
                }
            }

            if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                Log.d(TAG, "end of scan.");
                ToastUtils.showMessage(mContext,"end of scan.");
            }
        }
    };



 @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mReceiver);
    }

At this point, the function of starting Bluetooth and searching the surrounding Bluetooth list has been realized. As for the function of connecting Bluetooth to transmit data, in order not to mislead you, I will record it after the research is successful and it is used.

Tags: Android bluetooth

Posted by danman252 on Thu, 28 Apr 2022 23:40:57 +0300