Implementation of Bluetooth app Code by android

  • 2021-09-11 21:09:35
  • OfStack

In this paper, we share the specific code of android to realize Bluetooth app for your reference. The specific contents are as follows


private BluetoothGatt bluetoothGatt;
private BluetoothGattService gattService;
private BluetoothGattCharacteristic gattCharacteristic;
private BluetoothManager bluetoothManager;
private BluetoothAdapter bluetoothAdapter;
private List<BluetoothDevice> devices = new ArrayList<>();

private UUID serviceUUID;  // Different equipment   Different uuid
private UUID characteristicUUID;   // Different equipment   Different uuid
private final UUID service4UUID= UUID.fromString("0000fff0-0000-1000-8000-00805f9b34fb");  
private final UUID charAUUID = UUID.fromString("0000fffa-0000-1000-8000-00805f9b34fb");

private LightReceiver lightReceiver;
private ScanReceiver scanReceiver;
private ListView listView;
private TextView tvrefresh;
private String lightAction;

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  Log.i("tag", "MainActivity  onCreate()");
  //
  listView = (ListView) findViewById(R.id.lv_bluetooth);
  tvrefresh = (TextView) findViewById(R.id.tv_refresh_bluetooth);
  tvrefresh.setOnClickListener(this);
  openBluetooth();
  registeLigthReceiver();
  registeScanReceiver();

}

@Override
protected void onStart() {
  super.onStart();
  Log.i("tag", "MainActivity  onStart()");
  bluetoothScan();
}

// Return 
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
  Log.i("tag", "MainActivity  onKeyUp()");
  this.finish();
  return super.onKeyUp(keyCode, event);
}

// Rescan Bluetooth 
@Override
public void onClick(View view) {
  switch (view.getId()) {
    case R.id.tv_refresh_bluetooth:
      // Bluetooth scanning 
      bluetoothScan();
      break;
    default:
      break;
  }
}

// Turn on local Bluetooth 
private void openBluetooth() {
  Log.i("tag", "openLocalBluetooth()");
  // Check whether your phone supports Bluetooth 4.0
  if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
    Toast.makeText(this, " Phone does not support Bluetooth 4.0", Toast.LENGTH_SHORT).show();
    finish();
  }
  // Call the way of system service and request to turn on Bluetooth 
  bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
  bluetoothAdapter = bluetoothManager.getAdapter();
  // Turn on Bluetooth 
  if (!bluetoothAdapter.isEnabled()) {
    bluetoothAdapter.enable();
  }
}

// Start Bluetooth scanning    Scan to 1 Add 1 A 
private void bluetoothScan() {
  Log.i("tag", "bluetoothScan()");
  if (bluetoothAdapter == null) {
    openBluetooth();
  }
  if (!bluetoothAdapter.isDiscovering()) {
    bluetoothAdapter.startDiscovery();  // Callback 
  } else {
    Toast.makeText(this, " Scanning ..", Toast.LENGTH_SHORT).show();
  }
}

// Update the data in the Bluetooth list 
private void updateUi() {
  Log.i("tag", "updateUi()");
  if (devices != null && devices.size() > 0) {
    BlueAdapter adapter = new BlueAdapter(this, devices);
    listView.setAdapter(adapter);
    adapter.notifyDataSetChanged();
  } else {
    Toast.makeText(this, " There is no Bluetooth nearby ", Toast.LENGTH_SHORT).show();
  }
}

// Acquire gatt  Corresponding service
private BluetoothGattService getGattService(BluetoothGatt gatt, UUID serviceUUID) {
  List<BluetoothGattService> gattServices = gatt.getServices();
  for (BluetoothGattService gattService : gattServices) {
    if (gattService.getUuid().equals(serviceUUID)) {
      return gattService;
    }
  }
  return null;
}

// Acquire service Corresponding characteristic
private BluetoothGattCharacteristic getGattCharacteristic(BluetoothGattService gattService, UUID characteristicUUID) {
  List<BluetoothGattCharacteristic> gattCharacteristics = gattService.getCharacteristics();
  for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
    if (gattCharacteristic.getUuid().equals(characteristicUUID)) {
      return gattCharacteristic;
    }
  }
  return null;
}

// Register Bluetooth Scan Monitor 
private void registeScanReceiver() {
  Log.i("tag", "registeScanReceiver()");
  scanReceiver = new ScanReceiver();
  IntentFilter filter = new IntentFilter();
  filter.addAction(BluetoothDevice.ACTION_FOUND);
  filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
  registerReceiver(scanReceiver, filter);
}

// Define Bluetooth Scan Listening Class   Add device  ,   Update interface 
class ScanReceiver extends BroadcastReceiver {

  @Override
  public void onReceive(Context context, Intent intent) {
    Log.i("tag", " BluetoothReceiver / ScanReceiver onReceive()  action=" + intent.getAction());
    String scanAction = intent.getAction();
    if (scanAction.equals(BluetoothDevice.ACTION_FOUND)) {
      BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
      if (!devices.contains(device)) {
        devices.add(device);
        if (CacheUtils.getBlueDeviceString(MainActivity1.this, device.getAddress()).equals("")) {
          CacheUtils.putBlueDeviceString(MainActivity1.this, device.getAddress(), device.getName());
        }
        updateUi();
      }
    } else if (scanAction.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {
      if (devices == null || devices.size() == 0) {
        Toast.makeText(MainActivity1.this, " No Bluetooth devices were found nearby ", Toast.LENGTH_SHORT).show();
      }
    }
  }
}

// Register light monitoring 
private void registeLigthReceiver() {
  Log.i("tag", "registeReceiver()");
  lightReceiver = new LightReceiver();
  IntentFilter filter = new IntentFilter();
  filter.addAction("openLight");
  filter.addAction("closeLight");
  registerReceiver(lightReceiver, filter);
}

// Define a light monitor class 
class LightReceiver extends BroadcastReceiver {

  @Override
  public void onReceive(Context context, Intent intent) {

    Log.i("tag", " BluetoothReceiver  /LightReceiver onReceive()  action=" + intent.getAction());
    //
    String address = intent.getStringExtra("bluetoothAddress");  // From adapter Data obtained 
    lightAction = intent.getAction();
    // if()    Different equipment    Different serviceUUID , different characteristicUUID  Determine for yourself 
    serviceUUID=service4UUID;
    characteristicUUID=charAUUID;

    if (bluetoothAdapter == null) {
      openBluetooth();
    }
    BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address);  
    MyBluetoothGattCallback gattCallback = new MyBluetoothGattCallback();
    bluetoothGatt = device.connectGatt(MainActivity1.this, false, gattCallback);  // Callback 

  }
}

// Bluetooth connection / Communication callback 
class MyBluetoothGattCallback extends android.bluetooth.BluetoothGattCallback {
  @Override
  public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    super.onConnectionStateChange(gatt, status, newState);
    Log.i("tag", "MyBluetoothGattCallback  onConnectionStateChange()  newState=" + newState);
    if (newState == BluetoothProfile.STATE_CONNECTED) {
      gatt.discoverServices();       // Connection succeeded, search service started, 1 You must call this method, or you will not get the service 
      Log.i("tag", "MyBluetoothGattCallback  STATE_CONNECTED  ");
    } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
      Log.i("tag", "MyBluetoothGattCallback  STATE_DISCONNECTED");
    }
  }

  @Override
  public void onServicesDiscovered(BluetoothGatt gatt, int status) {
    super.onServicesDiscovered(gatt, status);
    Log.i("tag", "MyBluetoothGattCallback  onServicesDiscovered() status=" + status);

    if (lightAction.equals("openLight") || lightAction.equals("closeLight")) {  // Avoid   Constantly updated 
      if (gattService == null || gattCharacteristic == null || !serviceUUID.equals(service4UUID) || !characteristicUUID.equals(charAUUID)) {
        gattService = getGattService(gatt, serviceUUID);
        if (gattService != null) {
          gattCharacteristic = getGattCharacteristic(gattService, characteristicUUID);
          if (gattCharacteristic != null) {
            gatt.setCharacteristicNotification(gattCharacteristic, true);
            gatt.connect();
          }
        }
      }
      if (lightAction.equals("openLight")) {
        gattCharacteristic.setValue("openLight"); // Set it yourself here   Data required by Bluetooth module 
        gatt.writeCharacteristic(gattCharacteristic);
      } else if (lightAction.equals("closeLight")) {
        gattCharacteristic.setValue("closeLight"); // Set it yourself here   Data required by Bluetooth module 
        gatt.writeCharacteristic(gattCharacteristic);
      }
      lightAction = "";
      gatt.readRemoteRssi();
    }
  }
}

@Override
protected void onDestroy() {
  super.onDestroy();
  Log.i("tag", "onDestroy()");
  if (bluetoothAdapter != null) {
    bluetoothAdapter.disable();
    bluetoothAdapter = null;
  }
  if (bluetoothGatt != null) {
    bluetoothGatt.disconnect();
    bluetoothGatt.close();
    bluetoothGatt = null;
  }

  if (lightReceiver != null) {
    unregisterReceiver(lightReceiver);
    lightReceiver = null;
  }
  if (scanReceiver != null) {
    unregisterReceiver(scanReceiver);
    scanReceiver = null;
  }
}

Related articles: