summaryrefslogtreecommitdiff
path: root/app/src/main/java/se/leap/bitmaskclient/tethering/WifiHotspotObserver.java
blob: 578c5552c8a79a4cb6f7d259c94acbeea3bbfa70 (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
55
package se.leap.bitmaskclient.tethering;

import android.content.Context;
import android.content.IntentFilter;
import android.net.wifi.WifiManager;

import java.lang.reflect.Method;

public class WifiHotspotObserver {
    private static WifiHotspotObserver instance;

    private boolean isEnabled;
    private WifiManager wifiManager;
    private WifiHotspotBroadcastReceiver broadcastReceiver;

    private WifiHotspotObserver() {
    }

    public static void init(Context context) {
        if (instance == null) {
            instance = new WifiHotspotObserver();
            instance.broadcastReceiver = new WifiHotspotBroadcastReceiver();
            IntentFilter intentFilter = new IntentFilter("android.net.wifi.WIFI_AP_STATE_CHANGED");
            context.getApplicationContext().registerReceiver(instance.broadcastReceiver, intentFilter);
            instance.wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            instance.setEnabled(instance.isWifiApEnabled());
        }
    }

    private boolean isWifiApEnabled() {
        try {
            Method method = instance.wifiManager.getClass().getMethod("getWifiApState");
            int tmp = ((Integer) method.invoke(wifiManager));
            return WifiHotspotState.WIFI_AP_STATE_ENABLED.ordinal() == tmp % 10;
        } catch (Exception e) {
            return false;
        }
    }

    public static WifiHotspotObserver getInstance() {
        if (instance == null) {
            throw new RuntimeException("Call init() first!");
        }

        return instance;
    }

    void setEnabled(boolean enabled) {
        isEnabled = enabled;
    }

    public boolean isEnabled() {
        return isEnabled;
    }
}