1 /*
2  * Copyright (C) 2016 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 
17 package android.system.helpers;
18 
19 import android.app.DownloadManager;
20 import android.bluetooth.BluetoothAdapter;
21 import android.content.Context;
22 import android.net.ConnectivityManager;
23 import android.net.Network;
24 import android.net.NetworkInfo;
25 import android.net.wifi.WifiInfo;
26 import android.net.wifi.WifiManager;
27 import android.support.test.InstrumentationRegistry;
28 import android.telecom.TelecomManager;
29 import android.telephony.TelephonyManager;
30 import android.util.Log;
31 
32 import junit.framework.Assert;
33 
34 import java.io.IOException;
35 import java.net.HttpURLConnection;
36 import java.net.URL;
37 
38 /**
39  * Implement common helper methods for connectivity.
40  */
41 public class ConnectivityHelper {
42     private static final String TAG = ConnectivityHelper.class.getSimpleName();
43     private final static String DEFAULT_PING_SITE = "http://www.google.com";
44 
45     public static final int TIMEOUT = 1000;
46     private static ConnectivityHelper sInstance = null;
47     private Context mContext = null;
48 
ConnectivityHelper()49     public ConnectivityHelper() {
50         mContext = InstrumentationRegistry.getTargetContext();
51     }
52 
getInstance()53     public static ConnectivityHelper getInstance() {
54         if (sInstance == null) {
55             sInstance = new ConnectivityHelper();
56         }
57         return sInstance;
58     }
59 
getTelecomManager()60     public TelecomManager getTelecomManager() {
61         return (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
62     }
63 
getWifiManager()64     public WifiManager getWifiManager() {
65         return (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
66     }
67 
getConnectivityManager()68     public ConnectivityManager getConnectivityManager() {
69         return (ConnectivityManager) (ConnectivityManager) mContext
70                 .getSystemService(Context.CONNECTIVITY_SERVICE);
71     }
72 
getDownloadManager()73     public DownloadManager getDownloadManager() {
74         return (DownloadManager) (DownloadManager) mContext
75                 .getSystemService(Context.DOWNLOAD_SERVICE);
76     }
77 
getBluetoothAdapter()78     public BluetoothAdapter getBluetoothAdapter() {
79         return BluetoothAdapter.getDefaultAdapter();
80     }
81 
82    /**
83      * Checks if device connection is active either through wifi or mobile data by sending an HTTP
84      * request, check for HTTP_OK
85      */
isConnected()86     public boolean isConnected() throws InterruptedException {
87         int counter = 7;
88         long TIMEOUT_MS = TIMEOUT;
89         HttpURLConnection conn = null;
90         while (--counter > 0) {
91             try{
92                 URL url = new URL(DEFAULT_PING_SITE);
93                 conn = (HttpURLConnection) url.openConnection();
94                 conn.setRequestMethod("GET");
95                 conn.setConnectTimeout(TIMEOUT * 60); // 1 minute
96                 conn.setReadTimeout(TIMEOUT * 60); // 1 minute
97                 Log.i(TAG, "connection response code is " + conn.getResponseCode());
98                 Log.i(TAG, " counter = " + counter);
99                 return true;
100             } catch (IOException ex) {
101                 // Wifi being flaky in the lab, test retries 10 times to connect to google.com
102                 // as IOException is throws connection isn't made and response stream is null
103                 // so for retrying purpose, exception hasn't been rethrown
104                 Log.i(TAG, ex.getMessage());
105             } finally {
106                 if (conn != null) {
107                     conn.disconnect();
108                 }
109             }
110             Thread.sleep(TIMEOUT_MS);
111             TIMEOUT_MS = 2 * TIMEOUT_MS;
112         }
113         Log.i(TAG, " counter = " + counter);
114         return false;
115     }
116 
117     /**
118      * Disconnects and disables network
119      * @return true/false
120      */
disconnectWifi()121     public int disconnectWifi() {
122         Assert.assertTrue("Wifi not disconnected", getWifiManager().disconnect());
123         int netId = getWifiManager().getConnectionInfo().getNetworkId();
124         getWifiManager().disableNetwork(netId);
125         getWifiManager().saveConfiguration();
126         return netId;
127     }
128 
129     /**
130      * Ensures wifi is enabled in device
131      * @throws InterruptedException
132      */
ensureWifiEnabled()133     public void ensureWifiEnabled() throws InterruptedException {
134         // Device already connected to wifi as part of tradefed setup
135         if (!getWifiManager().isWifiEnabled()) {
136             getWifiManager().enableNetwork(getWifiManager().getConnectionInfo().getNetworkId(),
137                     true);
138             int counter = 5;
139             while (--counter > 0 && !getWifiManager().isWifiEnabled()) {
140                 Thread.sleep(TIMEOUT * 5);
141             }
142         }
143         Assert.assertTrue("Wifi should be enabled by now", getWifiManager().isWifiEnabled());
144     }
145 
146     /**
147      * Checks whether device has wifi connection for data service
148      * @return true/false
149      */
hasWifiData()150     public boolean hasWifiData() {
151         NetworkInfo netInfo = getConnectivityManager().getActiveNetworkInfo();
152         Assert.assertNotNull(netInfo);
153         return (netInfo.getType() == ConnectivityManager.TYPE_WIFI);
154     }
155 
156     /**
157      * Checks whether device has mobile connection for data service
158      * @return true/false
159      */
hasMobileData()160     public boolean hasMobileData() {
161         NetworkInfo netInfo = getConnectivityManager().getActiveNetworkInfo();
162         Assert.assertNotNull(netInfo);
163         return (netInfo.getType() == ConnectivityManager.TYPE_MOBILE);
164     }
165 
166     /**
167      * Checks whether device has sim
168      * @return true/false
169      */
hasDeviceSim()170     public boolean hasDeviceSim() {
171         TelephonyManager telMgr = (TelephonyManager) mContext
172                 .getSystemService(mContext.TELEPHONY_SERVICE);
173         return (telMgr.getSimState() == TelephonyManager.SIM_STATE_READY);
174     }
175 
176     /**
177      * Get connected wifi SSID.
178      * @return connected wifi SSID
179      */
getCurrentWifiSSID()180     public String getCurrentWifiSSID() {
181         WifiInfo connectionInfo = getWifiManager().getConnectionInfo();
182         if (connectionInfo != null) {
183             return connectionInfo.getSSID();
184         }
185         return null;
186     }
187 
188     /**
189      * Ensure bluetooth is enabled on device.
190      * @throws InterruptedException
191      */
ensureBluetoothEnabled()192     public void ensureBluetoothEnabled() throws InterruptedException {
193         if (!getBluetoothAdapter().isEnabled()) {
194             getBluetoothAdapter().enable();
195         }
196         int counter = 5;
197         while (--counter > 0 && !getBluetoothAdapter().isEnabled()) {
198             Thread.sleep(TIMEOUT * 2);
199         }
200     }
201 
202     /**
203      * Check whether device has mobile data available.
204      * @return true/false
205      */
mobileDataAvailable()206     public boolean mobileDataAvailable() {
207         Network[] networkArray = getConnectivityManager().getAllNetworks();
208         for (Network net: networkArray) {
209             if (getConnectivityManager().getNetworkInfo(net).getType()
210                     == ConnectivityManager.TYPE_MOBILE) {
211                 return true;
212             }
213         }
214         return false;
215     }
216 }
217