1/*
2 * Copyright 2014, The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.managedprovisioning;
18
19import android.content.BroadcastReceiver;
20import android.content.Context;
21import android.content.Intent;
22import android.content.IntentFilter;
23import android.net.ConnectivityManager;
24import android.net.NetworkInfo;
25import android.net.NetworkInfo.DetailedState;
26
27/**
28 * Monitor the state of the data network and the checkin service. Invoke a callback when the network
29 * is connected and checkin has succeeded. Callbacks are made on the thread that created this
30 * object.
31 */
32public class NetworkMonitor {
33    /** State notification callback. Expect some duplicate notifications. */
34    public interface Callback {
35
36        void onNetworkConnected();
37
38        void onNetworkDisconnected();
39    }
40
41    private Context mContext = null;
42    private Callback mCallback = null;
43
44    private boolean mNetworkConnected = false;
45
46    private boolean mReceiverRegistered;
47
48    /**
49     * Start watching the network and monitoring the checkin service. Immediately invokes one of the
50     * callback methods to report the current state, and then invokes callback methods over time as
51     * the state changes.
52     *
53     * @param context to use for intent observers and such
54     * @param callback to invoke when the network status changes
55     */
56    public NetworkMonitor(Context context, Callback callback) {
57        mContext = context;
58        mCallback = callback;
59
60        IntentFilter filter = new IntentFilter();
61        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
62
63        // Listen to immediate connectivity changes which are 3 seconds
64        // earlier than CONNECTIVITY_ACTION and may not have IPv6 routes
65        // setup. However, this may allow us to start up services like
66        // the CheckinService a bit earlier.
67        filter.addAction(ConnectivityManager.INET_CONDITION_ACTION);
68
69        context.registerReceiver(mBroadcastReceiver, filter);
70        mReceiverRegistered = true;
71
72    }
73
74    /**
75     * Stop watching the network and checkin service.
76     */
77    public synchronized void close() {
78        if (mCallback == null) {
79            return;
80        }
81        mCallback = null;
82
83        if (mReceiverRegistered) {
84            mContext.unregisterReceiver(mBroadcastReceiver);
85            mReceiverRegistered = false;
86        }
87    }
88
89    public final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
90        @Override
91        public void onReceive(Context context, Intent intent) {
92            ProvisionLogger.logd("onReceive " + intent.toString());
93
94            mNetworkConnected = isConnectedToWifi(context);
95
96            if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION) ||
97                    intent.getAction().equals(ConnectivityManager.INET_CONDITION_ACTION)) {
98                if (mNetworkConnected) {
99                    mCallback.onNetworkConnected();
100                } else {
101                    mCallback.onNetworkDisconnected();
102                }
103            }
104        }
105    };
106
107    private static NetworkInfo getActiveNetworkInfo(Context context) {
108        ConnectivityManager cm =
109                (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
110        if (cm != null) {
111            return cm.getActiveNetworkInfo();
112        }
113        return null;
114    }
115
116    public static boolean isConnectedToNetwork(Context context) {
117        NetworkInfo info = getActiveNetworkInfo(context);
118        return info != null && info.isConnected();
119    }
120
121    public static boolean isConnectedToWifi(Context context) {
122        NetworkInfo info = getActiveNetworkInfo(context);
123        return info != null
124                && info.isConnected()
125                && info.getType() == ConnectivityManager.TYPE_WIFI;
126    }
127
128    public boolean isNetworkConnected() {
129        return mNetworkConnected;
130    }
131}
132