1

I want save BluetoothGatt objects to manage BLE connections in my android app. Currently i am using a static android class to save those variables. But someTimes application vanishes those static variables.

public class ConnectedDevicesService {
    private static ConcurrentHashMap<String, BluetoothGatt> bleDeviceHashMap = new ConcurrentHashMap<>();
    public static  void  addBleDevice(String macAddress, BluetoothGatt device) {
        bleDeviceHashMap.put(macAddress, device);
        setBleDeviceMutableLiveData(bleDeviceHashMap);
    }
    public static  void setBleDeviceMutableLiveData(ConcurrentHashMap<String, BluetoothGatt> 
        bleDeviceMutableLiveDataNew) {
         bleDeviceMutableLiveData.setValue(bleDeviceMutableLiveDataNew);
    }
    public static HashMap<String, BluetoothGatt> getServerMachinesHashMap() {
        return serverMachinesHashMap;
    }
}

Then i have tried to save bleDeviceHashMap into shared preferences in android.

 public synchronized void addDeviceDataToSharedPrefs(ConcurrentHashMap<String, BluetoothGatt> bleDeviceHashMap){
        mPrefs = getSharedPreferences("com.app", MODE_PRIVATE);
        SharedPreferences.Editor prefsEditor = mPrefs.edit();
        Gson gson = new Gson();
        String bleDeviceHashMapJson = gson.toJson(bleDeviceHashMap);
        prefsEditor.putString("deviceMap", bleDeviceHashMapJson);
        prefsEditor.apply();
    }

but Gson can not serialize this map object. Is there a way to manage those connections in an Android app? I want them only in application running state. When closing them those objects should vanish. As the application loses its BLE connections.

0 Answers0