android应用程序无法读取从可扩展设备发送的特征

ldioqlga  于 2021-08-20  发布在  Java
关注(0)|答案(0)|浏览(178)

**已关闭。**此问题需要调试详细信息。它目前不接受答案。
**想要改进此问题?**更新问题,使其位于堆栈溢出主题上。

昨天关门了。
改进这个问题
我正在创建一个android应用程序,它可以扫描、配对和读取来自任何可移动设备的数据。
我在这里实施了所有这些官方文件:
概述:https://developer.android.com/guide/topics/connectivity/bluetooth/ble-overview
蓝牙权限:https://developer.android.com/guide/topics/connectivity/bluetooth/permissions#java
设置蓝牙:https://developer.android.com/guide/topics/connectivity/bluetooth/setup#java
查找可扩展设备:https://developer.android.com/guide/topics/connectivity/bluetooth/find-ble-devices
连接到gatt服务器:https://developer.android.com/guide/topics/connectivity/bluetooth/connect-gatt-server#java
可传输数据:https://developer.android.com/guide/topics/connectivity/bluetooth/transfer-ble-data#java
但我在将应用程序连接到ble设备后被卡住了。应用程序已成功连接到设备,但应用程序无法读取从设备发送的特征(数据)。
中的应用程序未读取任何特征 HomeActivity.java
因为他被卡住了 broadcastUpdate() 作用于 BluetoothLeService.java :

那么,我的代码怎么了?解决办法是什么?
代码如下:
androidmanifest.xml:

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

    <uses-feature
        android:name="android.hardware.bluetooth_le"
        android:required="true" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.example">
        <activity android:name=".ui.scanandpair.ScanAndPairActivity"/>
        <activity
            android:name=".ui.patient.inputmeasurement.InputMeasurementActivity"
            android:windowSoftInputMode="adjustResize" />
        <activity android:name=".ui.patient.inputnew.InputNewPatientActivity" />
        <activity android:name=".ui.authentication.signin.SignInActivity" />
        <activity android:name=".ui.authentication.signup.SignUpActivity" />
        <activity android:name=".ui.home.HomeActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service
            android:name="com.example.util.BluetoothLeService"
            android:enabled="true" >
        </service>
    </application>

homeactivity.java

public class HomeActivity extends AppCompatActivity implements View.OnClickListener {

    // GENERAL
    ActivityHomeBinding binding;
    String TAG = getClass().getSimpleName();

    // BLE
    BluetoothLeService bluetoothLeService;
    BLEDeviceEntity selectedDevice;
    boolean isConnected = false;
    ArrayList<ArrayList<BluetoothGattCharacteristic>> mGattCharacteristics;

    // KEYS
    String LIST_NAME = "LIST_NAME";
    String LIST_UUID = "LIST_UUID";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityHomeBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        BLESession bleSession = new BLESession(this);
        if(!bleSession.getBLEAddressFromSession().equals("")) {
            selectedDevice = new BLEDeviceEntity(
                    bleSession.getBLEAddressFromSession(),
                    bleSession.getBLENameFromSession());
            startService();
        }

        binding.buttonCariAlat.setOnClickListener(this);
    }

    // ON CLICK LISTENER
    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.buttonCariAlat) {
            moveToScanAndPairActivity();
        }
    }

    private void moveToScanAndPairActivity() {
        Intent intent = new Intent(this, ScanAndPairActivity.class);
        startActivity(intent);
    }

    // SOURCE FOR CONNECT TO A GATT SERVER: https://developer.android.com/guide/topics/connectivity/bluetooth/connect-gatt-server#java

    // SET UP A BOUND DEVICE
    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            bluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
            if (bluetoothLeService != null) {
                if (!bluetoothLeService.initialize()) {
                    Log.d(TAG, "Unable to initialize Bluetooth");
                    finish();
                }
                // perform device connection
                bluetoothLeService.connect(selectedDevice.getAddress());
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            bluetoothLeService = null;
        }
    };

    private void startService() {
        Intent gattServiceIntent = new Intent(this, BluetoothLeService.class);
        bindService(gattServiceIntent, serviceConnection, Context.BIND_AUTO_CREATE);
    }

    // LISTEN FOR UPDATES IN ACTIVITY
    private final BroadcastReceiver gattUpdateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
                isConnected = true;
                Toast.makeText(HomeActivity.this, getString(R.string.terhubung_ke_alat), Toast.LENGTH_SHORT).show();
            } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
                isConnected = false;
                Toast.makeText(HomeActivity.this, getString(R.string.terputus_dari_alat), Toast.LENGTH_SHORT).show();
            } else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
                // Show all the supported services and characteristics on the user interface.
                displayGattServices(bluetoothLeService.getSupportedGattServices());
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();

        registerReceiver(gattUpdateReceiver, makeGattUpdateIntentFilter());
        if (bluetoothLeService != null) {
            final boolean result = bluetoothLeService.connect(selectedDevice.getAddress());
            Log.d(TAG, "Connect request result=" + result);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(gattUpdateReceiver);
    }

    private static IntentFilter makeGattUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
        return intentFilter;
    }

    // READ BLE CHARACTERISTICS
    // Demonstrates how to iterate through the supported GATT
    // Services/Characteristics.
    // In this sample, we populate the data structure that is bound to the
    // ExpandableListView on the UI.
    private void displayGattServices(List<BluetoothGattService> gattServices) {
        Log.d(TAG, "displayGattServices");
        if (gattServices == null) return;
        String uuid = null;
        String unknownServiceString = getResources().
                getString(R.string.service_tidak_diketahui);
        String unknownCharaString = getResources().
                getString(R.string.karakteristik_tidak_diketahui);
        ArrayList<HashMap<String, String>> gattServiceData =
                new ArrayList<HashMap<String, String>>();
        ArrayList<ArrayList<HashMap<String, String>>> gattCharacteristicData
                = new ArrayList<ArrayList<HashMap<String, String>>>();
        mGattCharacteristics =
                new ArrayList<ArrayList<BluetoothGattCharacteristic>>();

        // Loops through available GATT Services.
        for (BluetoothGattService gattService : gattServices) {
            HashMap<String, String> currentServiceData =
                    new HashMap<String, String>();
            uuid = gattService.getUuid().toString();
            currentServiceData.put(
                    LIST_NAME, SampleGattAttributes.
                            lookup(uuid, unknownServiceString));
            currentServiceData.put(LIST_UUID, uuid);
            gattServiceData.add(currentServiceData);

            ArrayList<HashMap<String, String>> gattCharacteristicGroupData =
                    new ArrayList<HashMap<String, String>>();
            List<BluetoothGattCharacteristic> gattCharacteristics =
                    gattService.getCharacteristics();
            ArrayList<BluetoothGattCharacteristic> charas =
                    new ArrayList<BluetoothGattCharacteristic>();

            // Loops through available Characteristics.
            for (BluetoothGattCharacteristic gattCharacteristic :
                    gattCharacteristics) {
                charas.add(gattCharacteristic);
                HashMap<String, String> currentCharaData =
                        new HashMap<String, String>();
                uuid = gattCharacteristic.getUuid().toString();
                currentCharaData.put(
                        LIST_NAME, SampleGattAttributes.lookup(uuid,
                                unknownCharaString));
                currentCharaData.put(LIST_UUID, uuid);
                gattCharacteristicGroupData.add(currentCharaData);
            }

            mGattCharacteristics.add(charas);
            gattCharacteristicData.add(gattCharacteristicGroupData);
        }
    }
}

bluetoothleservice.java

public class BluetoothLeService extends Service {
    // SOURCE FOR CONNECTING TO A GATT SERVER: https://developer.android.com/guide/topics/connectivity/bluetooth/connect-gatt-server#java

    private Binder binder = new LocalBinder();
    public static final String TAG = "BluetoothLeService";
    private BluetoothAdapter bluetoothAdapter;
    private BluetoothGatt bluetoothGatt;
    public final static String ACTION_GATT_CONNECTED =
            "com.example.bluetooth.le.ACTION_GATT_CONNECTED";
    public final static String ACTION_GATT_DISCONNECTED =
            "com.example.bluetooth.le.ACTION_GATT_DISCONNECTED";
    public final static String ACTION_DATA_AVAILABLE =
            "com.example.bluetooth.le.ACTION_DATA_AVAILABLE";

    private static final int STATE_DISCONNECTED = 0;
    private static final int STATE_CONNECTED = 2;
    private int connectionState;

    public final static String ACTION_GATT_SERVICES_DISCOVERED =
            "com.example.bluetooth.le.ACTION_GATT_SERVICES_DISCOVERED";

    public static String EXTRA_DATA = "EXTRA_DATA";

    // SET UP A BOUND DEVICE
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    public class LocalBinder extends Binder {
        public BluetoothLeService getService() {
            return BluetoothLeService.this;
        }
    }

    // SETUP THE BLUETOOTH ADAPTER
    public boolean initialize() {
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (bluetoothAdapter == null) {
            Log.d(TAG, "Unable to obtain a BluetoothAdapter.");
            return false;
        }
        return true;
    }

    // CONNECT TO A DEVICE
    public boolean connect(final String address) {
        if (bluetoothAdapter == null || address == null) {
            Log.d(TAG, "BluetoothAdapter not initialized or unspecified address.");
            return false;
        }

        try {
            final BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address);
            // connect to the GATT server on the device
            bluetoothGatt = device.connectGatt(this, false, bluetoothGattCallback);
            return true;
        } catch (IllegalArgumentException exception) {
            Log.d(TAG, "Device not found with provided address.");
            return false;
        }
        // connect to the GATT server on the device
    }

    // DECLARE GATT CALLBACK
    private final BluetoothGattCallback bluetoothGattCallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            Log.d(TAG, "onConnectionStateChange");
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                // successfully connected to the GATT Server
                connectionState = STATE_CONNECTED;
                broadcastUpdate(ACTION_GATT_CONNECTED);
                // Attempts to discover services after successful connection.
                bluetoothGatt.discoverServices();
            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                // disconnected from the GATT Server
                connectionState = STATE_DISCONNECTED;
                broadcastUpdate(ACTION_GATT_DISCONNECTED);
            }
        }

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            Log.d(TAG, "onServicesDiscovered");
            if (status == BluetoothGatt.GATT_SUCCESS) {
                broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
            } else {
                Log.d(TAG, "onServicesDiscovered received: " + status);
            }
        }

        @Override
        public void onCharacteristicRead(
                BluetoothGatt gatt,
                BluetoothGattCharacteristic characteristic,
                int status
        ) {
            Log.d(TAG, "onCharacteristicRead: " + characteristic.getValue());
            if (status == BluetoothGatt.GATT_SUCCESS) {
                broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
            }
        }

        @Override
        public void onCharacteristicChanged(
                BluetoothGatt gatt,
                BluetoothGattCharacteristic characteristic
        ) {
            Log.d(TAG, "onCharacteristicChanged: " + characteristic.getValue());
            broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
        }
    };

    // BROADCAST UPDATES
    private void broadcastUpdate(final String action, final BluetoothGattCharacteristic characteristic) {
        final Intent intent = new Intent(action);

        Log.d(TAG, "broadcastUpdate with 2 inputs");

        // This is special handling for the Heart Rate Measurement profile. Data
        // parsing is carried out as per profile specifications.
//        if (HEART_RATE_MEASUREMENT.equals(characteristic.getUuid())) {
//            int flag = characteristic.getProperties();
//            int format = -1;
//            if ((flag & 0x01) != 0) {
//                format = BluetoothGattCharacteristic.FORMAT_UINT16;
//                Log.d(TAG, "Heart rate format UINT16.");
//            } else {
//                format = BluetoothGattCharacteristic.FORMAT_UINT8;
//                Log.d(TAG, "Heart rate format UINT8.");
//            }
//            final int heartRate = characteristic.getIntValue(format, 1);
//            Log.d(TAG, String.format("Received heart rate: %d", heartRate));
//            intent.putExtra(EXTRA_DATA, String.valueOf(heartRate));
//        } else {
//            // For all other profiles, writes the data formatted in HEX.
//            final byte[] data = characteristic.getValue();
//            if (data != null && data.length > 0) {
//                final StringBuilder stringBuilder = new StringBuilder(data.length);
//                for(byte byteChar : data)
//                    stringBuilder.append(String.format("%02X ", byteChar));
//                intent.putExtra(EXTRA_DATA, new String(data) + "\n" +
//                        stringBuilder.toString());
//            }
//        }
        Log.d(TAG, "characteristic: " + characteristic.getUuid().toString());

        sendBroadcast(intent);
    }

    private void broadcastUpdate(final String action) {
        final Intent intent = new Intent(action);
        Log.d(TAG, "broadcastUpdate with 1 input, action: " + action);
        sendBroadcast(intent);
    }

    // CLOSE GATT CONNECTION
    @Override
    public boolean onUnbind(Intent intent) {
        close();
        return super.onUnbind(intent);
    }

    private void close() {
        if (bluetoothGatt == null) {
            return;
        }
        bluetoothGatt.close();
        bluetoothGatt = null;
    }

    // SOURCE FOR TRANSFER BLE DATA: https://developer.android.com/guide/topics/connectivity/bluetooth/transfer-ble-data#java

    // DISCOVER SERVICES
    public List<BluetoothGattService> getSupportedGattServices() {
        if (bluetoothGatt == null) return null;
        return bluetoothGatt.getServices();
    }

    public void readCharacteristic(BluetoothGattCharacteristic characteristic) {
        if (bluetoothGatt == null) {
            Log.d(TAG, "BluetoothGatt not initialized");
            return;
        }
        bluetoothGatt.readCharacteristic(characteristic);
    }

    // RECEIVE GATT NOTIFICATION
    public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic,boolean enabled) {
        if (bluetoothGatt == null) {
            Log.d(TAG, "BluetoothGatt not initialized");
            return;
        }
        bluetoothGatt.setCharacteristicNotification(characteristic, enabled);

        // This is specific to Heart Rate Measurement.
        if (HEART_RATE_MEASUREMENT.equals(characteristic.getUuid())) {
            BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString(SampleGattAttributes.CLIENT_CHARACTERISTIC_CONFIG));
            descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
            bluetoothGatt.writeDescriptor(descriptor);
        }
    }
}

scanandpairactivity.java

public class ScanAndPairActivity extends AppCompatActivity {

    // GENERAL
    String TAG = getClass().getSimpleName();
    ActivityScanAndPairBinding binding;

    // BLUETOOTH
    int REQUEST_ENABLE_BT = 1;
    boolean isScanning = false;
    BluetoothAdapter bluetoothAdapter;
    BluetoothLeScanner bluetoothLeScanner;
    ScanAndPairAdapter scanAndPairAdapter;
    List<BLEDeviceEntity> bleDeviceEntityList;
    BLEDeviceEntity selectedDevice;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityScanAndPairBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        android10BluetoothPermission();

        scanAndPairAdapter = new ScanAndPairAdapter(this);
        bleDeviceEntityList = new ArrayList<>();
    }

    // SOURCE FOR BLUETOOTH PERMISSION: https://developer.android.com/guide/topics/connectivity/bluetooth/permissions#java

    // CHECK FOR BLUETOOTH PERMISSION FOR ANDROID 10
    private void android10BluetoothPermission () {
        boolean isLocationPermissionRequired = Build.VERSION.SDK_INT >= Build.VERSION_CODES.N;
        boolean isBGLocationAccessNotGranted = false;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
            isBGLocationAccessNotGranted = ContextCompat.checkSelfPermission(
                    this, Manifest.permission.ACCESS_BACKGROUND_LOCATION) != PackageManager.PERMISSION_GRANTED;
        }
        boolean isLocationAccessNotGranted = ContextCompat.checkSelfPermission(
                this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED;

        if (isLocationPermissionRequired && isBGLocationAccessNotGranted && isLocationAccessNotGranted) {
            requestLocationPermission();
        }
        else {
            setUpBluetooth();
        }
    }

    private void requestLocationPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_FINE_LOCATION)) {
                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
                alertDialogBuilder
                        .setTitle(getString(R.string.izinkan_lokasi))
                        .setMessage(getString(R.string.mohon_izinkan_aplikasi_mengakses_lokasi))
                        .setPositiveButton(getString(R.string.ya), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                makeLocationRequest();
                            }
                        });
                alertDialogBuilder.show();
            } else {
                makeLocationRequest();
            }
        }
    }

    private void makeLocationRequest() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{"android.permission.ACCESS_FINE_LOCATION"}, 101);
        }
    }

    // ON REQUEST PERMISSION RESULT
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch(requestCode) {
            case 101:
                if (grantResults.length != 0 && grantResults[0] == 0) {
                    setUpBluetooth();
                }
                break;
            default:
                Toast.makeText(this, getString(R.string.maaf_izin_lokasi_harus_disetujui), Toast.LENGTH_LONG).show();
        }
    }

    private void setUpBluetooth() {
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        checkBluetooth(bluetoothAdapter);
        enableBluetooth(this, bluetoothAdapter);

        bluetoothLeScanner = bluetoothAdapter.getBluetoothLeScanner();
        scanBLEDevices(bluetoothLeScanner);
    }

    // SOURCE FOR SET UP BLUETOOTH: https://developer.android.com/guide/topics/connectivity/bluetooth/setup#java

    // GET BLUETOOTH ADAPTER
    private void checkBluetooth (BluetoothAdapter bluetoothAdapter) {
        if (bluetoothAdapter == null) {
            Log.d(TAG, "Bluetooth: " + "bluetooth adapter is null");
        }
        else {
            Log.d(TAG, "Bluetooth: " + "bluetooth is adapter not null");
        }
    }

    // ENABLE BLUETOOTH
    private void enableBluetooth (Activity activity, BluetoothAdapter bluetoothAdapter) {
        Log.d(TAG, "Bluetooth: " + "bluetooth adapter is enabled: " + bluetoothAdapter.isEnabled());
        if (!bluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            activity.startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
            Log.d(TAG, "Bluetooth: " + "bluetooth is enabled");
        }
        else {
            Log.d(TAG, "Bluetooth: " + "bluetooth is already enabled");
        }
    }

    // SOURCE FOR FIND BLE DEVICES: https://developer.android.com/guide/topics/connectivity/bluetooth/find-ble-devices#java

    // SCAN BLE DEVICES
    private void scanBLEDevices (BluetoothLeScanner bluetoothLeScanner) {
        showProgressBar();

        int SCAN_DURATION = 5000;

        if(!isScanning) {
            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    isScanning = false;
                    bluetoothLeScanner.stopScan(bleScanCallback);
                    Log.d(TAG, "ScanBLEDevices: " + "stop scanning");
                    populateDataToRecyclerView();
                }
            }, SCAN_DURATION);

            isScanning = true;
            showProgressBar();
            bluetoothLeScanner.startScan(buildScanFilters(), buildScanSettings(), bleScanCallback);
            Log.d(TAG, "ScanBLEDevices: " + "start scanning");
        }
        else {
            isScanning = false;
            bluetoothLeScanner.stopScan(bleScanCallback);
            Log.d(TAG, "ScanBLEDevices: " + "stop scanning");
            populateDataToRecyclerView();
        }
    }

    private void showProgressBar() {
        binding.recylerViewFilm.setVisibility(View.GONE);
        binding.progressBar.setVisibility(View.VISIBLE);
    }

    private void hideProgressBar() {
        binding.recylerViewFilm.setVisibility(View.VISIBLE);
        binding.progressBar.setVisibility(View.GONE);
    }

    private void populateDataToRecyclerView() {
        hideProgressBar();
        scanAndPairAdapter.setBleDeviceEntityList(bleDeviceEntityList);
        scanAndPairAdapter.notifyDataSetChanged();

        binding.recylerViewFilm.setLayoutManager(new LinearLayoutManager(ScanAndPairActivity.this));
        binding.recylerViewFilm.setHasFixedSize(true);
        binding.recylerViewFilm.setAdapter(scanAndPairAdapter);

        scanAndPairAdapter.setOnItemClickCallback(new ScanAndPairAdapter.OnItemClickCallback() {
            @Override
            public void onItemClicked(BLEDeviceEntity bleDeviceEntity) {
                selectedDevice = bleDeviceEntity;
                Toast.makeText(
                        ScanAndPairActivity.this, getString(R.string.mencoba_menghubungkan_dengan) +
                                " " + bleDeviceEntity.getName(), Toast.LENGTH_SHORT).show();
                setBLEDataToSession();
                moveToHomeActivity();
            }
        });
    }

    // BLE SCAN CALLBACK
    private ScanCallback bleScanCallback = new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            super.onScanResult(callbackType, result);
            String deviceAddress = result.getDevice().getAddress();
            String deviceName = result.getDevice().getName();

            Log.d(TAG, "ScanCallback, deviceAddress: " + deviceAddress + ", deviceName: " + deviceName);
            if(bleDeviceEntityList.size() == 0) {
                bleDeviceEntityList.add(new BLEDeviceEntity(deviceAddress, deviceName));
            }
            else {
                for(BLEDeviceEntity bleDeviceEntity : bleDeviceEntityList){
                    if(!bleDeviceEntity.getAddress().equals(deviceAddress)) {
                        bleDeviceEntityList.add(new BLEDeviceEntity(deviceAddress, deviceName));
                    }
                }
            }

            Log.d(TAG, "bleDeviceEntityList: " + bleDeviceEntityList);
        }
    };

    // SOURCE FOR LATEST ANDROID BLE APPLICATION SAMPLE: https://github.com/android/connectivity-samples/tree/main/BluetoothAdvertisementsKotlin

    private static List<ScanFilter> buildScanFilters() {
        List<ScanFilter> scanFilters = new ArrayList<>();

        ScanFilter.Builder builder = new ScanFilter.Builder();
        // Comment out the below line to see all BLE devices around you
        // builder.setServiceUuid(Constants.Service_UUID);
        scanFilters.add(builder.build());
        return scanFilters;
    }

    private static ScanSettings buildScanSettings() {
        ScanSettings.Builder builder = new ScanSettings.Builder();
        builder.setScanMode(ScanSettings.SCAN_MODE_LOW_POWER);
        return builder.build();
    }

    private void moveToHomeActivity() {
        Intent intent = new Intent(this, HomeActivity.class);
        startActivity(intent);
    }

    private void setBLEDataToSession() {
        BLESession bleSession = new BLESession(this);
        bleSession.setBLENameToSession(selectedDevice.getName());
        bleSession.setBLEAddressToSession(selectedDevice.getAddress());
    }
}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题