summaryrefslogtreecommitdiff
path: root/app/java/src/WifiListenerReceiver.java
blob: 6bf93bd6321ddefe335df6540d30472722fb33bb (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
56
57
58
59
package org.pihole.dnsproxy;

import android.provider.Settings;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;

import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiInfo;

import android.os.Bundle;
import android.os.Handler;

import android.preference.PreferenceManager;

import android.util.Log;

public class WifiListenerReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent) {
        NetworkInfo networkInfo = (NetworkInfo) intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
        Intent dnsProxyService = new Intent(context, DNSProxyService.class);

        // start
        if (networkInfo.getState().equals(NetworkInfo.State.CONNECTED)) {
            SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);

            if (!sharedPreferences.getBoolean("use_wifi_listener_for_activation", false)) {
                return;
            }

            // wait a few moments for wifi to be fully there
            (new Handler()).postDelayed(new Runnable() {
                @Override
                public void run() {
                    WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
                    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                    String ssid = wifiInfo.getSSID();

                    // remove quotes around ssid
                    ssid = ssid.substring(1, ssid.length() - 1);

                    if (ssid.equals(sharedPreferences.getString("wifi_listener_ssid", ""))) {
                        DNSProxyService.start(context);
                    }
                }
            }, 1000);
        }

        // stop
        else if (networkInfo.getState().equals(NetworkInfo.State.DISCONNECTED) && DNSProxyService.isRunning()) {
            DNSProxyService.stop(context);
        }
    }
}