summaryrefslogtreecommitdiff
path: root/app/src/main/java/com/javispedro/autobluetether/BtDeviceEnabledSetAdapter.java
blob: 7d2c8fc1f6acda4b1b04092720fe78e472732bb4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package com.javispedro.autobluetether;

import android.bluetooth.BluetoothDevice;
import android.content.SharedPreferences;
import android.util.ArraySet;
import android.util.Log;

import java.util.Set;

public class BtDeviceEnabledSetAdapter {
    private final static String TAG = "BtDeviceEnabledSetAd";

    private final SharedPreferences mPrefs;
    private final String mPrefsKey;
    private final ArraySet<String> mSet = new ArraySet<>();

    public BtDeviceEnabledSetAdapter(SharedPreferences prefs, String key) {
        mPrefs = prefs;
        mPrefsKey = key;

        readPrefs();
    }

    public boolean contains(BluetoothDevice device) {
        return mSet.contains(device.getAddress());
    }

    public void set(BluetoothDevice device, boolean enabled) {
        String address = device.getAddress();
        boolean currently = mSet.contains(address);
        if (enabled && !currently) {
            mSet.add(address);
            savePrefs();
        } else if (currently && !enabled) {
            mSet.remove(address);
            savePrefs();
        }
    }

    private void readPrefs() {
        mSet.clear();
        Set<String> prefsSet = mPrefs.getStringSet(mPrefsKey, null);
        if (prefsSet != null) {
            mSet.addAll(prefsSet);
        }
    }

    private void savePrefs() {
        SharedPreferences.Editor editor = mPrefs.edit();
        editor.putStringSet(mPrefsKey, mSet);
        editor.apply();
        Log.d(TAG, "saved " + mPrefsKey + ":" + mSet);
    }
}