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