From 96ca1bf768a70c55e33cd0a7bf3b760174bdd39f Mon Sep 17 00:00:00 2001 From: Patches Date: Sat, 30 Apr 2016 15:05:05 -0500 Subject: [PATCH 1/2] Update CHANGE.md --- CHANGE.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/CHANGE.md b/CHANGE.md index 8ce007bc..655a0cb3 100644 --- a/CHANGE.md +++ b/CHANGE.md @@ -1,5 +1,15 @@ ## v1.0.2 - 04/30/2016 +#####Update README.md +commit cd98623b74763e4d12a0c682b5023fdd5f169d91
+Author: Patches
+Date: Sat Apr 30 15:02:43 2016 -0500 + +#####Update CHANGE.md +commit af298c3a986c4418cf0003e33f9d591daec58dc5
+Author: Patches
+Date: Sat Apr 30 14:54:13 2016 -0500 + #####Create CHANGE.md commit c16118744ff2a52881c4af6f4afc8438262888c8
Author: Patches
From 2e2246e63fb4dc3b16b3a59c2081b9e9c39c4388 Mon Sep 17 00:00:00 2001 From: isuPatches Date: Sat, 22 Oct 2016 04:08:05 -0500 Subject: [PATCH 2/2] More functionality, switching to espresso tests, updating libs, and providing logging option closes #9 closes #10 closes #11 closes #12 --- app/build.gradle | 21 +- .../java/com/metova/wisefy/WiseFyTest.java | 1005 +++++++++++++---- .../base/BaseInstrumentationTestCase.java | 37 - .../com/metova/wisefy/base/BaseTestClass.java | 23 + .../wisefy/util/GetManagerUtilTest.java | 34 +- .../com/metova/wisefy/util/TestUtils.java | 32 + .../main/java/com/metova/wisefy/WiseFy.java | 799 +++++++------ .../metova/wisefy/util/GetManagerUtil.java | 1 - .../java/com/metova/wisefy/util/LogUtil.java | 45 +- .../java/com/metova/wisefy/util/SSIDUtil.java | 33 + build.gradle | 7 +- gradle/wrapper/gradle-wrapper.properties | 4 +- 12 files changed, 1391 insertions(+), 650 deletions(-) delete mode 100644 app/src/androidTest/java/com/metova/wisefy/base/BaseInstrumentationTestCase.java create mode 100644 app/src/androidTest/java/com/metova/wisefy/base/BaseTestClass.java create mode 100644 app/src/androidTest/java/com/metova/wisefy/util/TestUtils.java create mode 100644 app/src/main/java/com/metova/wisefy/util/SSIDUtil.java diff --git a/app/build.gradle b/app/build.gradle index f089ecbf..f96cc849 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -24,7 +24,7 @@ task jacocoDebugTestReport(type: JacocoReport, dependsOn: ["connectedDebugAndroi classDirectories = classDirs additionalSourceDirs = files(coverageSourceDirs) sourceDirectories = files(coverageSourceDirs) - executionData = files(['build/outputs/code-coverage/connected/coverage.ec']) + executionData = files([fileTree(dir: 'build/outputs/code-coverage/connected', include: '**/*.ec')]) onlyIf = { true @@ -46,14 +46,22 @@ dexcount { } android { - compileSdkVersion 23 - buildToolsVersion "23.0.2" + + testOptions { + // Allows Android code to be called from unit tests without causing a crash. + // Helpful for allowing Log.d()-type calls + unitTests.returnDefaultValues = true; + } + + compileSdkVersion 24 + buildToolsVersion "24.0.3" defaultConfig { minSdkVersion 16 - targetSdkVersion 23 + targetSdkVersion 24 versionCode 3 versionName "1.0.2" + testInstrumentationRunner 'android.support.test.runner.AndroidJUnitRunner' } buildTypes { @@ -72,12 +80,13 @@ android { dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) - compile 'com.android.support:appcompat-v7:23.3.0' + compile 'com.android.support:appcompat-v7:24.2.1' + androidTestCompile 'com.android.support:support-annotations:24.2.1' + androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2' androidTestCompile 'org.mockito:mockito-core:1.10.19' androidTestCompile 'com.google.dexmaker:dexmaker:1.2' androidTestCompile 'com.google.dexmaker:dexmaker-mockito:1.2' - androidTestCompile 'com.jayway.android.robotium:robotium-solo:5.5.4' testCompile 'junit:junit:4.12' } \ No newline at end of file diff --git a/app/src/androidTest/java/com/metova/wisefy/WiseFyTest.java b/app/src/androidTest/java/com/metova/wisefy/WiseFyTest.java index fa947bf0..59eb8470 100644 --- a/app/src/androidTest/java/com/metova/wisefy/WiseFyTest.java +++ b/app/src/androidTest/java/com/metova/wisefy/WiseFyTest.java @@ -2,206 +2,395 @@ import android.app.Activity; -import android.content.Context; +import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.wifi.ScanResult; import android.net.wifi.WifiConfiguration; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; -import com.metova.wisefy.base.BaseInstrumentationTestCase; +import android.support.test.rule.ActivityTestRule; +import com.metova.wisefy.base.BaseTestClass; import com.metova.wisefy.util.GetManagerUtil; import com.metova.wisefy.util.TestActivity; -import com.robotium.solo.Condition; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; import java.util.ArrayList; import java.util.List; +import static com.metova.wisefy.util.TestUtils.*; +import static org.junit.Assert.*; import static org.mockito.Mockito.*; -public class WiseFyTest extends BaseInstrumentationTestCase { +public class WiseFyTest extends BaseTestClass { - private WifiManager mMockWiFiManager; + @Rule + public ActivityTestRule mActivityTestRule = new ActivityTestRule<>(TestActivity.class); private ConnectivityManager mMockConnectivityManager; private GetManagerUtil mMockGetManagerUtil; + private WifiManager mMockWiFiManager; + public WiseFyTest() { super(TestActivity.class); } - @Override - protected void setUp() throws Exception { - super.setUp(); + @Before + public void setUp() { mMockWiFiManager = mock(WifiManager.class); mMockConnectivityManager = mock(ConnectivityManager.class); mMockGetManagerUtil = mock(GetManagerUtil.class); when(mMockGetManagerUtil.getWiFiManager(any(Activity.class))).thenReturn(mMockWiFiManager); when(mMockGetManagerUtil.getConnectivityManager(any(Activity.class))).thenReturn(mMockConnectivityManager); + + WiseFy.getSmarts().mGetManagerUtil = mMockGetManagerUtil; + + mActivityTestRule.launchActivity(new Intent()); } + @Test public void testAddOpenNetwork() { - WiseFy.getSmarts().addOpenNetwork(getActivity(), "HAHA"); - WifiManager wifiManager = getLiveWiFiManager(getActivity()); - boolean foundWifiConfiguration = false; - for(WifiConfiguration wifiConfiguration : wifiManager.getConfiguredNetworks()) { - if(wifiConfiguration.SSID.replaceAll("\"", "").equals("HAHA")) { - foundWifiConfiguration = true; - break; - } - } + int result = WiseFy.getSmarts().addOpenNetwork(mActivityTestRule.getActivity(), OPEN_NETWORK_SSID); + assertNotEquals(WiseFy.WIFI_MANAGER_FAILURE, result); + } - assertEquals(true, foundWifiConfiguration); + @Test + public void testAddOpenNetworkFailureToAdd() { + when(mMockWiFiManager.addNetwork(any(WifiConfiguration.class))).thenReturn(WiseFy.WIFI_MANAGER_FAILURE); + int result = WiseFy.getSmarts().addOpenNetwork(mActivityTestRule.getActivity(), OPEN_NETWORK_SSID); + assertEquals(WiseFy.WIFI_MANAGER_FAILURE, result); + } + + @Test + public void testAddOpenNetworkNullActivity() { + int result = WiseFy.getSmarts().addOpenNetwork(null, OPEN_NETWORK_SSID); + assertEquals(WiseFy.WISE_MANAGER_FAILURE, result); + } - WiseFy.getSmarts().removeNetwork(getActivity(), "HAHA"); + @Test + public void testAddOpenNetworkNullPassword() { + int result = WiseFy.getSmarts().addOpenNetwork(mActivityTestRule.getActivity(), null); + assertEquals(WiseFy.WISE_MANAGER_FAILURE, result); } + @Test + public void testAddOpenNetworkNullWifiManager() { + when(mMockGetManagerUtil.getWiFiManager(any(Activity.class))).thenReturn(null); + int result = WiseFy.getSmarts().addOpenNetwork(mActivityTestRule.getActivity(), OPEN_NETWORK_SSID); + assertEquals(WiseFy.WISE_MANAGER_FAILURE, result); + } + + @Test public void testAddWEPNetwork() { - WiseFy.getSmarts().addWEPNetwork(getActivity(), "HAHA", "123456"); - WifiManager wifiManager = getLiveWiFiManager(getActivity()); - boolean foundWifiConfiguration = false; - for(WifiConfiguration wifiConfiguration : wifiManager.getConfiguredNetworks()) { - if(wifiConfiguration.SSID.replaceAll("\"", "").equals("HAHA")) { - foundWifiConfiguration = true; - break; - } - } + int result = WiseFy.getSmarts().addWEPNetwork(mActivityTestRule.getActivity(), WEP_NETWORK_SSID, WEP_NETWORK_PASSWORD); + assertNotEquals(WiseFy.WIFI_MANAGER_FAILURE, result); + } - assertEquals(true, foundWifiConfiguration); + @Test + public void testAddWEPNetworkFailureToAdd() { + when(mMockWiFiManager.addNetwork(any(WifiConfiguration.class))).thenReturn(WiseFy.WIFI_MANAGER_FAILURE); + int result = WiseFy.getSmarts().addWEPNetwork(mActivityTestRule.getActivity(), WEP_NETWORK_SSID, WEP_NETWORK_PASSWORD); + assertEquals(WiseFy.WIFI_MANAGER_FAILURE, result); + } - WiseFy.getSmarts().removeNetwork(getActivity(), "HAHA"); + @Test + public void testAddWEPNetworkNullActivity() { + int result = WiseFy.getSmarts().addWEPNetwork(null, WEP_NETWORK_SSID, WEP_NETWORK_PASSWORD); + assertEquals(WiseFy.WISE_MANAGER_FAILURE, result); } + @Test + public void testAddWEPNetworkNullSSID() { + int result = WiseFy.getSmarts().addWEPNetwork(mActivityTestRule.getActivity(), null, WEP_NETWORK_PASSWORD); + assertEquals(WiseFy.WISE_MANAGER_FAILURE, result); + } + + @Test + public void testAddWEPNetworkNullPassword() { + int result = WiseFy.getSmarts().addWEPNetwork(mActivityTestRule.getActivity(), WEP_NETWORK_SSID, null); + assertEquals(WiseFy.WISE_MANAGER_FAILURE, result); + } + + @Test + public void testAddWEPNetworkNullWifiManager() { + when(mMockGetManagerUtil.getWiFiManager(any(Activity.class))).thenReturn(null); + int result = WiseFy.getSmarts().addWEPNetwork(mActivityTestRule.getActivity(), WEP_NETWORK_SSID, WEP_NETWORK_PASSWORD); + assertEquals(WiseFy.WISE_MANAGER_FAILURE, result); + } + + @Test public void testAddWPA2Network() { - WiseFy.getSmarts().addWPA2Network(getActivity(), "HAHA", "12345678"); - WifiManager wifiManager = getLiveWiFiManager(getActivity()); - boolean foundWifiConfiguration = false; - for(WifiConfiguration wifiConfiguration : wifiManager.getConfiguredNetworks()) { - if(wifiConfiguration.SSID.replaceAll("\"", "").equals("HAHA")) { - foundWifiConfiguration = true; - break; - } - } + int result = WiseFy.getSmarts().addWPA2Network(mActivityTestRule.getActivity(), WPA2_NETWORK_SSID, WPA2_NETWORK_PASSWORD); + assertNotEquals(WiseFy.WIFI_MANAGER_FAILURE, result); + } - assertEquals(true, foundWifiConfiguration); + @Test + public void testAddWPA2NetworkFailureToAdd() { + when(mMockWiFiManager.addNetwork(any(WifiConfiguration.class))).thenReturn(WiseFy.WIFI_MANAGER_FAILURE); + int result = WiseFy.getSmarts().addWPA2Network(mActivityTestRule.getActivity(), WPA2_NETWORK_SSID, WPA2_NETWORK_PASSWORD); + assertEquals(WiseFy.WIFI_MANAGER_FAILURE, result); + } + + @Test + public void testAddWPA2NetworkNullActivity() { + int result = WiseFy.getSmarts().addWPA2Network(null, WPA2_NETWORK_SSID, WPA2_NETWORK_PASSWORD); + assertEquals(WiseFy.WISE_MANAGER_FAILURE, result); + } - WiseFy.getSmarts().removeNetwork(getActivity(), "HAHA"); + @Test + public void testAddWPA2NetworkNullSSID() { + int result = WiseFy.getSmarts().addWPA2Network(mActivityTestRule.getActivity(), null, WPA2_NETWORK_PASSWORD); + assertEquals(WiseFy.WISE_MANAGER_FAILURE, result); } + @Test + public void testAddWPA2NetworkNullPassword() { + int result = WiseFy.getSmarts().addWPA2Network(mActivityTestRule.getActivity(), WPA2_NETWORK_SSID, null); + assertEquals(WiseFy.WISE_MANAGER_FAILURE, result); + } + + @Test + public void testAddWPA2NetworkNullWifiManager() { + when(mMockGetManagerUtil.getWiFiManager(any(Activity.class))).thenReturn(null); + int result = WiseFy.getSmarts().addWPA2Network(mActivityTestRule.getActivity(), WPA2_NETWORK_SSID, WPA2_NETWORK_PASSWORD); + assertEquals(WiseFy.WISE_MANAGER_FAILURE, result); + } + + @Test public void testCalculateBar() { int result = WiseFy.getSmarts().calculateBars(-35, 5); assertEquals(4, result); } + @Test public void testCompareSignalLevel() { int result = WiseFy.getSmarts().compareSignalLevel(-35, -70); assertEquals(35, result); } - public void testDisableWiFi() { - WiseFy.getSmarts().mGetManagerUtil = GetManagerUtil.getInstance(); - final WifiManager wifiManager = getLiveWiFiManager(getActivity()); - if(!wifiManager.isWifiEnabled()) { - wifiManager.setWifiEnabled(true); - } - assertTrue(getSolo().waitForCondition(new Condition() { - @Override - public boolean isSatisfied() { - return wifiManager.isWifiEnabled(); - } - }, 3000)); - WiseFy.getSmarts().disableWiFi(getActivity()); - assertTrue(getSolo().waitForCondition(new Condition() { - @Override - public boolean isSatisfied() { - return !wifiManager.isWifiEnabled(); - } - }, 3000)); - wifiManager.setWifiEnabled(true); - assertTrue(getSolo().waitForCondition(new Condition() { - @Override - public boolean isSatisfied() { - return wifiManager.isWifiEnabled(); - } - }, 3000)); - } - - public void testDisconnectFromCurrentNetwork() { - WiseFy.getSmarts().mGetManagerUtil = GetManagerUtil.getInstance(); - final String originalSSID = WiseFy.getSmarts().getCurrentNetwork(getActivity()).getSSID().replaceAll("\"", ""); - WiseFy.getSmarts().disconnectFromCurrentNetwork(getActivity()); - assertTrue(getSolo().waitForCondition(new Condition() { - @Override - public boolean isSatisfied() { - return WifiInfo.getDetailedStateOf(WiseFy.getSmarts().getCurrentNetwork(getActivity()).getSupplicantState()).equals(NetworkInfo.DetailedState.DISCONNECTED); - } - }, 10000)); - assertTrue(getSolo().waitForCondition(new Condition() { - @Override - public boolean isSatisfied() { - return WiseFy.getSmarts().reconnectToNetwork(getActivity(), originalSSID, 30); - } - }, 30000)); - } - - public void testEnableWiFi() { - WiseFy.getSmarts().mGetManagerUtil = GetManagerUtil.getInstance(); - final WifiManager wifiManager = getLiveWiFiManager(getActivity()); - if(wifiManager.isWifiEnabled()) { - wifiManager.setWifiEnabled(false); - } - assertTrue(getSolo().waitForCondition(new Condition() { - @Override - public boolean isSatisfied() { - return !wifiManager.isWifiEnabled(); - } - }, 3000)); - WiseFy.getSmarts().enableWiFi(getActivity()); - assertTrue(getSolo().waitForCondition(new Condition() { - @Override - public boolean isSatisfied() { - return wifiManager.isWifiEnabled(); - } - }, 3000)); + @Test + public void testConnectToNetworkFailureNoList() { + boolean result = WiseFy.getSmarts().connectToNetwork(mActivityTestRule.getActivity(), TEST_SSID, 1); + assertEquals(false, result); + } + + @Test + public void testConnectToNetworkFailureNotAvailable() { + List wifiList = new ArrayList<>(); + WifiConfiguration mWiFiConfiguration = new WifiConfiguration(); + mWiFiConfiguration.SSID = TEST_SSID; + wifiList.add(mWiFiConfiguration); + + WifiInfo mockWiFiInfo = mock(WifiInfo.class); + when(mockWiFiInfo.getSSID()).thenReturn(TEST_SSID); + + when(mMockWiFiManager.getConfiguredNetworks()).thenReturn(wifiList); + when(mMockWiFiManager.getConnectionInfo()).thenReturn(mockWiFiInfo); + + NetworkInfo mockNetworkInfo = mock(NetworkInfo.class); + + when(mMockConnectivityManager.getActiveNetworkInfo()).thenReturn(mockNetworkInfo); + when(mockNetworkInfo.isAvailable()).thenReturn(false); + when(mockNetworkInfo.isConnected()).thenReturn(true); + + boolean result = WiseFy.getSmarts().connectToNetwork(mActivityTestRule.getActivity(), TEST_SSID, 1); + assertEquals(false, result); + } + + @Test + public void testConnectToNetworkFailureNotConnected() { + List wifiList = new ArrayList<>(); + WifiConfiguration mWiFiConfiguration = new WifiConfiguration(); + mWiFiConfiguration.SSID = TEST_SSID; + wifiList.add(mWiFiConfiguration); + + WifiInfo mockWiFiInfo = mock(WifiInfo.class); + when(mockWiFiInfo.getSSID()).thenReturn(TEST_SSID); + + when(mMockWiFiManager.getConnectionInfo()).thenReturn(mockWiFiInfo); + when(mMockWiFiManager.getConfiguredNetworks()).thenReturn(wifiList); + + NetworkInfo mockNetworkInfo = mock(NetworkInfo.class); + + when(mMockConnectivityManager.getActiveNetworkInfo()).thenReturn(mockNetworkInfo); + when(mockNetworkInfo.isAvailable()).thenReturn(true); + when(mockNetworkInfo.isConnected()).thenReturn(false); + + boolean result = WiseFy.getSmarts().connectToNetwork(mActivityTestRule.getActivity(), TEST_SSID, 1); + assertEquals(false, result); + } + + @Test + public void testConnectToNetworkFailureNullActivity() { + boolean result = WiseFy.getSmarts().connectToNetwork(null, TEST_SSID, 1); + assertEquals(false, result); + } + + @Test + public void testConnectToNetworkFailureNullWifiManager() { + when(mMockGetManagerUtil.getWiFiManager(any(Activity.class))).thenReturn(null); + boolean result = WiseFy.getSmarts().connectToNetwork(null, TEST_SSID, 1); + assertEquals(false, result); } + @Test + public void testConnectToNetworkSuccess() { + List wifiList = new ArrayList<>(); + WifiConfiguration mWiFiConfiguration = new WifiConfiguration(); + mWiFiConfiguration.SSID = TEST_SSID; + wifiList.add(mWiFiConfiguration); + + WifiInfo mockWiFiInfo = mock(WifiInfo.class); + when(mockWiFiInfo.getSSID()).thenReturn(TEST_SSID); + + when(mMockWiFiManager.getConfiguredNetworks()).thenReturn(wifiList); + when(mMockWiFiManager.getConnectionInfo()).thenReturn(mockWiFiInfo); + + NetworkInfo mockNetworkInfo = mock(NetworkInfo.class); + + when(mMockConnectivityManager.getActiveNetworkInfo()).thenReturn(mockNetworkInfo); + when(mockNetworkInfo.isAvailable()).thenReturn(true); + when(mockNetworkInfo.isConnected()).thenReturn(true); + + boolean result = WiseFy.getSmarts().connectToNetwork(mActivityTestRule.getActivity(), TEST_SSID, 1); + assertEquals(true, result); + } + + @Test + public void testDisableWifiFailure() { + when(mMockWiFiManager.setWifiEnabled(anyBoolean())).thenReturn(true); + boolean result = WiseFy.getSmarts().disableWifi(mActivityTestRule.getActivity()); + verify(mMockWiFiManager).setWifiEnabled(false); + assertEquals(true, result); + } + + @Test + public void testDisableWifiNullActivity() { + boolean result = WiseFy.getSmarts().disableWifi(null); + assertEquals(false, result); + } + + @Test + public void testDisableWifiSuccess() { + when(mMockWiFiManager.setWifiEnabled(anyBoolean())).thenReturn(true); + boolean result = WiseFy.getSmarts().disableWifi(mActivityTestRule.getActivity()); + verify(mMockWiFiManager).setWifiEnabled(false); + assertEquals(true, result); + } + + @Test + public void testDisconnectFromCurrentNetworkFailure() { + when(mMockWiFiManager.disconnect()).thenReturn(false); + boolean result = WiseFy.getSmarts().disconnectFromCurrentNetwork(mActivityTestRule.getActivity()); + verify(mMockWiFiManager).disconnect(); + assertEquals(false, result); + } + + @Test + public void testDisconnectFromCurrentNetworkNullActivity() { + boolean result = WiseFy.getSmarts().disconnectFromCurrentNetwork(null); + assertEquals(false, result); + } + + @Test + public void testDisconnectFromCurrentNetworkSuccess() { + when(mMockWiFiManager.disconnect()).thenReturn(true); + boolean result = WiseFy.getSmarts().disconnectFromCurrentNetwork(mActivityTestRule.getActivity()); + verify(mMockWiFiManager).disconnect(); + assertEquals(true, result); + } + + @Test + public void testEnableWiFiFailure() { + when(mMockWiFiManager.setWifiEnabled(anyBoolean())).thenReturn(false); + boolean result = WiseFy.getSmarts().enableWifi(mActivityTestRule.getActivity()); + verify(mMockWiFiManager).setWifiEnabled(true); + assertEquals(false, result); + } + + @Test + public void testEnableWiFiNullActivity() { + boolean result = WiseFy.getSmarts().enableWifi(null); + assertEquals(false, result); + } + + @Test + public void testEnableWiFiSuccess() { + when(mMockWiFiManager.setWifiEnabled(anyBoolean())).thenReturn(true); + boolean result = WiseFy.getSmarts().enableWifi(mActivityTestRule.getActivity()); + verify(mMockWiFiManager).setWifiEnabled(true); + assertEquals(true, result); + } + + @Test public void testGetCurrentNetwork() { - WiseFy.getSmarts().mGetManagerUtil = mMockGetManagerUtil; WifiInfo mockWifiInfo = mock(WifiInfo.class); - when(mockWifiInfo.getSSID()).thenReturn("TEST SSID"); + when(mockWifiInfo.getSSID()).thenReturn(TEST_SSID); when(mMockWiFiManager.getConnectionInfo()).thenReturn(mockWifiInfo); - assertEquals("TEST SSID", WiseFy.getSmarts().getCurrentNetwork(getActivity()).getSSID()); + assertEquals(TEST_SSID, WiseFy.getSmarts().getCurrentNetwork(mActivityTestRule.getActivity()).getSSID()); } + @Test + public void testGetCurrentNetworkNullActivity() { + assertEquals(null, WiseFy.getSmarts().getCurrentNetwork(null)); + } + + @Test + public void testGetCurrentNetworkNullWifiManager() { + when(mMockGetManagerUtil.getWiFiManager(any(Activity.class))).thenReturn(null); + assertEquals(null, WiseFy.getSmarts().getCurrentNetwork(mActivityTestRule.getActivity())); + } + + @Test public void testGetNearbyAccessPoints() { - WiseFy.getSmarts().mGetManagerUtil = mMockGetManagerUtil; List scanResults = new ArrayList<>(); ScanResult scanResult1 = mock(ScanResult.class); - scanResult1.SSID = "Test SSID"; + scanResult1.SSID = TEST_SSID; scanResults.add(scanResult1); ScanResult scanResult2 = mock(ScanResult.class); - scanResult2.SSID = "Test SSID"; + scanResult2.SSID = TEST_SSID2; scanResults.add(scanResult2); when(mMockWiFiManager.getScanResults()).thenReturn(scanResults); - List results = WiseFy.getSmarts().getNearbyAccessPoints(getActivity(), false); + List results = WiseFy.getSmarts().getNearbyAccessPoints(mActivityTestRule.getActivity(), false); assertEquals(scanResults, results); assertEquals(2, results.size()); } - public void testGetNearbyAccessPointsFilterDuplicates() { - WiseFy.getSmarts().mGetManagerUtil = mMockGetManagerUtil; + @Test + public void testGetNearbyAccessPointsFilterDuplicatesDifferent() { List scanResults = new ArrayList<>(); ScanResult scanResult1 = mock(ScanResult.class); - scanResult1.SSID = "Test SSID"; + scanResult1.SSID = TEST_SSID; + scanResults.add(scanResult1); + ScanResult scanResult2 = mock(ScanResult.class); + scanResult2.SSID = TEST_SSID2; + scanResults.add(scanResult2); + + when(mMockWiFiManager.getScanResults()).thenReturn(scanResults); + + List results = WiseFy.getSmarts().getNearbyAccessPoints(mActivityTestRule.getActivity(), true); + + assertEquals(scanResults, results); + assertEquals(2, results.size()); + } + + @Test + public void testGetNearbyAccessPointsFilterDuplicatesHigher() { + List scanResults = new ArrayList<>(); + ScanResult scanResult1 = mock(ScanResult.class); + scanResult1.SSID = TEST_SSID; scanResult1.level = -35; scanResults.add(scanResult1); ScanResult scanResult2 = mock(ScanResult.class); - scanResult2.SSID = "Test SSID"; + scanResult2.SSID = TEST_SSID; scanResult2.level = -70; scanResults.add(scanResult2); @@ -210,94 +399,248 @@ public void testGetNearbyAccessPointsFilterDuplicates() { when(mMockWiFiManager.getScanResults()).thenReturn(scanResults); - List results = WiseFy.getSmarts().getNearbyAccessPoints(getActivity(), true); + List results = WiseFy.getSmarts().getNearbyAccessPoints(mActivityTestRule.getActivity(), true); + + assertEquals(expectedScanResults, results); + assertEquals(1, results.size()); + } + + @Test + public void testGetNearbyAccessPointsFilterDuplicatesLower() { + List scanResults = new ArrayList<>(); + ScanResult scanResult1 = mock(ScanResult.class); + scanResult1.SSID = TEST_SSID; + scanResult1.level = -70; + scanResults.add(scanResult1); + ScanResult scanResult2 = mock(ScanResult.class); + scanResult2.SSID = TEST_SSID; + scanResult2.level = -35; + scanResults.add(scanResult2); + + List expectedScanResults = new ArrayList<>(); + expectedScanResults.add(scanResult2); + + when(mMockWiFiManager.getScanResults()).thenReturn(scanResults); + + List results = WiseFy.getSmarts().getNearbyAccessPoints(mActivityTestRule.getActivity(), true); assertEquals(expectedScanResults, results); assertEquals(1, results.size()); } + @Test + public void testGetNearbyAccessPointsNullActivity() { + List results = WiseFy.getSmarts().getNearbyAccessPoints(null, true); + assertEquals(null, results); + } + + @Test + public void testGetNearbyAccessPointsNullWifiManager() { + when(mMockGetManagerUtil.getWiFiManager(any(Activity.class))).thenReturn(null); + List results = WiseFy.getSmarts().getNearbyAccessPoints(mActivityTestRule.getActivity(), true); + assertEquals(null, results); + } + + @Test public void testGetSavedNetworks() { - WiseFy.getSmarts().mGetManagerUtil = mMockGetManagerUtil; List wifiList = new ArrayList<>(); WifiConfiguration mWiFiConfiguration = new WifiConfiguration(); - mWiFiConfiguration.SSID = "TEST SSID"; + mWiFiConfiguration.SSID = TEST_SSID; wifiList.add(mWiFiConfiguration); when(mMockWiFiManager.getConfiguredNetworks()).thenReturn(wifiList); - assertEquals(wifiList, WiseFy.getSmarts().getSavedNetworks(getActivity())); + assertEquals(wifiList, WiseFy.getSmarts().getSavedNetworks(mActivityTestRule.getActivity())); } - public void testIsSecureWithWEP() { - ScanResult scanResult = mock(ScanResult.class); - scanResult.capabilities = "WEP"; - assertEquals(true, WiseFy.getSmarts().isSecure(scanResult)); + @Test + public void testGetSavedNetworksNullActivity() { + assertEquals(null, WiseFy.getSmarts().getSavedNetworks(null)); } - public void testIsSecureWithPSK() { - ScanResult scanResult = mock(ScanResult.class); - scanResult.capabilities = "PSK"; - assertEquals(true, WiseFy.getSmarts().isSecure(scanResult)); + @Test + public void testGetSavedNetworksNullWifiManager() { + when(mMockGetManagerUtil.getWiFiManager(any(Activity.class))).thenReturn(null); + assertEquals(null, WiseFy.getSmarts().getSavedNetworks(mActivityTestRule.getActivity())); } - public void testIsSecureWithEAP() { - ScanResult scanResult = mock(ScanResult.class); - scanResult.capabilities = "EAP"; - assertEquals(true, WiseFy.getSmarts().isSecure(scanResult)); + @Test + public void testIsDeviceConnectedToMobileNetworkFailureSuccess() { + NetworkInfo mockNetworkInfo = mock(NetworkInfo.class); + when(mockNetworkInfo.getTypeName()).thenReturn("MOBILE"); + + when(mMockConnectivityManager.getActiveNetworkInfo()).thenReturn(mockNetworkInfo); + when(mockNetworkInfo.isAvailable()).thenReturn(true); + when(mockNetworkInfo.isConnected()).thenReturn(true); + + boolean result = WiseFy.getSmarts().isDeviceConnectedToMobileNetwork(mActivityTestRule.getActivity()); + assertEquals(true, result); } - public void testIsSecureEmptyCapabilities() { - ScanResult scanResult = mock(ScanResult.class); - scanResult.capabilities = ""; - assertEquals(false, WiseFy.getSmarts().isSecure(scanResult)); + @Test + public void testIsDeviceConnectedToMobileNetworkFailureNotAvailable() { + NetworkInfo mockNetworkInfo = mock(NetworkInfo.class); + when(mockNetworkInfo.getTypeName()).thenReturn("MOBILE"); + + when(mMockConnectivityManager.getActiveNetworkInfo()).thenReturn(mockNetworkInfo); + when(mockNetworkInfo.isAvailable()).thenReturn(false); + when(mockNetworkInfo.isConnected()).thenReturn(true); + + boolean result = WiseFy.getSmarts().isDeviceConnectedToMobileNetwork(mActivityTestRule.getActivity()); + assertEquals(false, result); } - public void testIsSecureNullCapabilities() { - ScanResult scanResult = mock(ScanResult.class); - assertEquals(false, WiseFy.getSmarts().isSecure(scanResult)); - } - - public void testIsWiFiEnabledFalse() { - final WifiManager wifiManager = getLiveWiFiManager(getActivity()); - wifiManager.setWifiEnabled(false); - assertTrue(getSolo().waitForCondition(new Condition() { - @Override - public boolean isSatisfied() { - return !wifiManager.isWifiEnabled(); - } - }, 3000)); - assertEquals(false, WiseFy.getSmarts().isWifiEnabled(getActivity())); - wifiManager.setWifiEnabled(true); - assertTrue(getSolo().waitForCondition(new Condition() { - @Override - public boolean isSatisfied() { - return wifiManager.isWifiEnabled(); - } - }, 3000)); - } - - public void testIsWifiEnabledTrue() { - final WifiManager wifiManager = getLiveWiFiManager(getActivity()); - wifiManager.setWifiEnabled(true); - assertTrue(getSolo().waitForCondition(new Condition() { - @Override - public boolean isSatisfied() { - return wifiManager.isWifiEnabled(); - } - }, 3000)); - assertEquals(true, WiseFy.getSmarts().isWifiEnabled(getActivity())); - } - - public void testReconnectToNetworkSuccess() { - WiseFy.getSmarts().mGetManagerUtil = mMockGetManagerUtil; + @Test + public void testIsDeviceConnectedToMobileNetworkFailureNotConnected() { + NetworkInfo mockNetworkInfo = mock(NetworkInfo.class); + when(mockNetworkInfo.getTypeName()).thenReturn("MOBILE"); + + when(mMockConnectivityManager.getActiveNetworkInfo()).thenReturn(mockNetworkInfo); + when(mockNetworkInfo.isAvailable()).thenReturn(true); + when(mockNetworkInfo.isConnected()).thenReturn(false); + + boolean result = WiseFy.getSmarts().isDeviceConnectedToMobileNetwork(mActivityTestRule.getActivity()); + assertEquals(false, result); + } + + @Test + public void testIsDeviceConnectedToMobileNetworkFailureWrongType() { + NetworkInfo mockNetworkInfo = mock(NetworkInfo.class); + when(mockNetworkInfo.getTypeName()).thenReturn("WRONG TYPE"); + + when(mMockConnectivityManager.getActiveNetworkInfo()).thenReturn(mockNetworkInfo); + when(mockNetworkInfo.isAvailable()).thenReturn(true); + when(mockNetworkInfo.isConnected()).thenReturn(true); + + boolean result = WiseFy.getSmarts().isDeviceConnectedToMobileNetwork(null); + assertEquals(false, result); + } + + @Test + public void testIsDeviceConnectedToMobileNetworkNullActivity() { + boolean result = WiseFy.getSmarts().isDeviceConnectedToMobileNetwork(null); + assertEquals(false, result); + } + + @Test + public void testIsDeviceConnectedToMobileNetworkNullConfigurationManager() { + when(mMockGetManagerUtil.getConnectivityManager(any(Activity.class))).thenReturn(null); + boolean result = WiseFy.getSmarts().isDeviceConnectedToMobileNetwork(mActivityTestRule.getActivity()); + assertEquals(false, result); + } + + @Test + public void testIsDeviceConnectedToMobileOrWifiNetworkFailureSuccessMobile() { + NetworkInfo mockNetworkInfo = mock(NetworkInfo.class); + when(mockNetworkInfo.getTypeName()).thenReturn("MOBILE"); + + when(mMockConnectivityManager.getActiveNetworkInfo()).thenReturn(mockNetworkInfo); + when(mockNetworkInfo.isAvailable()).thenReturn(true); + when(mockNetworkInfo.isConnected()).thenReturn(true); + + boolean result = WiseFy.getSmarts().isDeviceConnectedToMobileOrWifiNetwork(mActivityTestRule.getActivity()); + assertEquals(true, result); + } + + @Test + public void testIsDeviceConnectedToMobileOrWifiNetworkFailureSuccessWifi() { + NetworkInfo mockNetworkInfo = mock(NetworkInfo.class); + when(mockNetworkInfo.getTypeName()).thenReturn("WIFI"); + + when(mMockConnectivityManager.getActiveNetworkInfo()).thenReturn(mockNetworkInfo); + when(mockNetworkInfo.isAvailable()).thenReturn(true); + when(mockNetworkInfo.isConnected()).thenReturn(true); + + boolean result = WiseFy.getSmarts().isDeviceConnectedToMobileOrWifiNetwork(mActivityTestRule.getActivity()); + assertEquals(true, result); + } + + @Test + public void testIsDeviceConnectedToMobileOrWifiNetworkFailureNotAvailableMobile() { + NetworkInfo mockNetworkInfo = mock(NetworkInfo.class); + when(mockNetworkInfo.getTypeName()).thenReturn("MOBILE"); + + when(mMockConnectivityManager.getActiveNetworkInfo()).thenReturn(mockNetworkInfo); + when(mockNetworkInfo.isAvailable()).thenReturn(false); + when(mockNetworkInfo.isConnected()).thenReturn(true); + + boolean result = WiseFy.getSmarts().isDeviceConnectedToMobileOrWifiNetwork(mActivityTestRule.getActivity()); + assertEquals(false, result); + } + + @Test + public void testIsDeviceConnectedToMobileOrWifiNetworkFailureNotAvailableWifi() { + NetworkInfo mockNetworkInfo = mock(NetworkInfo.class); + when(mockNetworkInfo.getTypeName()).thenReturn("WIFI"); + + when(mMockConnectivityManager.getActiveNetworkInfo()).thenReturn(mockNetworkInfo); + when(mockNetworkInfo.isAvailable()).thenReturn(false); + when(mockNetworkInfo.isConnected()).thenReturn(true); + + boolean result = WiseFy.getSmarts().isDeviceConnectedToMobileOrWifiNetwork(mActivityTestRule.getActivity()); + assertEquals(false, result); + } + + @Test + public void testIsDeviceConnectedToMobileOrWifiNetworkFailureNotConnectedMobile() { + NetworkInfo mockNetworkInfo = mock(NetworkInfo.class); + when(mockNetworkInfo.getTypeName()).thenReturn("MOBILE"); + + when(mMockConnectivityManager.getActiveNetworkInfo()).thenReturn(mockNetworkInfo); + when(mockNetworkInfo.isAvailable()).thenReturn(true); + when(mockNetworkInfo.isConnected()).thenReturn(false); + + boolean result = WiseFy.getSmarts().isDeviceConnectedToMobileOrWifiNetwork(mActivityTestRule.getActivity()); + assertEquals(false, result); + } + + @Test + public void testIsDeviceConnectedToMobileOrWifiNetworkFailureNotConnectedWifi() { + NetworkInfo mockNetworkInfo = mock(NetworkInfo.class); + when(mockNetworkInfo.getTypeName()).thenReturn("WIFI"); + + when(mMockConnectivityManager.getActiveNetworkInfo()).thenReturn(mockNetworkInfo); + when(mockNetworkInfo.isAvailable()).thenReturn(true); + when(mockNetworkInfo.isConnected()).thenReturn(false); + + boolean result = WiseFy.getSmarts().isDeviceConnectedToMobileOrWifiNetwork(mActivityTestRule.getActivity()); + assertEquals(false, result); + } + + @Test + public void testIsDeviceConnectedToMobileOrWifiNetworkFailureWrongType() { + NetworkInfo mockNetworkInfo = mock(NetworkInfo.class); + when(mockNetworkInfo.getTypeName()).thenReturn("WRONG TYPE"); + + when(mMockConnectivityManager.getActiveNetworkInfo()).thenReturn(mockNetworkInfo); + when(mockNetworkInfo.isAvailable()).thenReturn(true); + when(mockNetworkInfo.isConnected()).thenReturn(true); + + boolean result = WiseFy.getSmarts().isDeviceConnectedToMobileOrWifiNetwork(null); + assertEquals(false, result); + } + + @Test + public void testIsDeviceConnectedToMobileWifiNetworkNullActivity() { + boolean result = WiseFy.getSmarts().isDeviceConnectedToMobileOrWifiNetwork(null); + assertEquals(false, result); + } + + @Test + public void testIsDeviceConnectedToMobileOrWifiNetworkNullConfigurationManager() { + when(mMockGetManagerUtil.getConnectivityManager(any(Activity.class))).thenReturn(null); + boolean result = WiseFy.getSmarts().isDeviceConnectedToMobileOrWifiNetwork(mActivityTestRule.getActivity()); + assertEquals(false, result); + } + + @Test + public void testIsDeviceConnectedToSSID() { List wifiList = new ArrayList<>(); WifiConfiguration mWiFiConfiguration = new WifiConfiguration(); - mWiFiConfiguration.SSID = "TEST SSID"; + mWiFiConfiguration.SSID = TEST_SSID; wifiList.add(mWiFiConfiguration); WifiInfo mockWiFiInfo = mock(WifiInfo.class); - when(mockWiFiInfo.getSSID()).thenReturn("TEST SSID"); - - when(mMockWiFiManager.getConnectionInfo()).thenReturn(mockWiFiInfo); + when(mockWiFiInfo.getSSID()).thenReturn(TEST_SSID); when(mMockWiFiManager.getConfiguredNetworks()).thenReturn(wifiList); when(mMockWiFiManager.getConnectionInfo()).thenReturn(mockWiFiInfo); @@ -308,22 +651,43 @@ public void testReconnectToNetworkSuccess() { when(mockNetworkInfo.isAvailable()).thenReturn(true); when(mockNetworkInfo.isConnected()).thenReturn(true); - boolean result = WiseFy.getSmarts().reconnectToNetwork(getActivity(), "TEST SSID", 1); + boolean result = WiseFy.getSmarts().isDeviceConnectedToSSID(mActivityTestRule.getActivity(), TEST_SSID); assertEquals(true, result); } - public void testReconnectToNetworkFailureNotAvailable() { - WiseFy.getSmarts().mGetManagerUtil = mMockGetManagerUtil; + @Test + public void testIsDeviceConnectedToSSIDFailureOtherSSID() { List wifiList = new ArrayList<>(); WifiConfiguration mWiFiConfiguration = new WifiConfiguration(); - mWiFiConfiguration.SSID = "TEST SSID"; + mWiFiConfiguration.SSID = TEST_SSID2; wifiList.add(mWiFiConfiguration); WifiInfo mockWiFiInfo = mock(WifiInfo.class); - when(mockWiFiInfo.getSSID()).thenReturn("TEST SSID"); + when(mockWiFiInfo.getSSID()).thenReturn(TEST_SSID2); + when(mMockWiFiManager.getConfiguredNetworks()).thenReturn(wifiList); when(mMockWiFiManager.getConnectionInfo()).thenReturn(mockWiFiInfo); + NetworkInfo mockNetworkInfo = mock(NetworkInfo.class); + + when(mMockConnectivityManager.getActiveNetworkInfo()).thenReturn(mockNetworkInfo); + when(mockNetworkInfo.isAvailable()).thenReturn(true); + when(mockNetworkInfo.isConnected()).thenReturn(true); + + boolean result = WiseFy.getSmarts().isDeviceConnectedToSSID(mActivityTestRule.getActivity(), TEST_SSID); + assertEquals(false, result); + } + + @Test + public void testIsDeviceConnectedToSSIDFailureNotAvailable() { + List wifiList = new ArrayList<>(); + WifiConfiguration mWiFiConfiguration = new WifiConfiguration(); + mWiFiConfiguration.SSID = TEST_SSID; + wifiList.add(mWiFiConfiguration); + + WifiInfo mockWiFiInfo = mock(WifiInfo.class); + when(mockWiFiInfo.getSSID()).thenReturn(TEST_SSID); + when(mMockWiFiManager.getConfiguredNetworks()).thenReturn(wifiList); when(mMockWiFiManager.getConnectionInfo()).thenReturn(mockWiFiInfo); @@ -333,21 +697,19 @@ public void testReconnectToNetworkFailureNotAvailable() { when(mockNetworkInfo.isAvailable()).thenReturn(false); when(mockNetworkInfo.isConnected()).thenReturn(true); - boolean result = WiseFy.getSmarts().reconnectToNetwork(getActivity(), "TEST SSID", 1); + boolean result = WiseFy.getSmarts().isDeviceConnectedToSSID(mActivityTestRule.getActivity(), TEST_SSID); assertEquals(false, result); } - public void testReconnectToNetworkFailureNotConnected() { - WiseFy.getSmarts().mGetManagerUtil = mMockGetManagerUtil; + @Test + public void testIsDeviceConnectedToSSIDFailureNotConnected() { List wifiList = new ArrayList<>(); WifiConfiguration mWiFiConfiguration = new WifiConfiguration(); - mWiFiConfiguration.SSID = "TEST SSID"; + mWiFiConfiguration.SSID = TEST_SSID; wifiList.add(mWiFiConfiguration); WifiInfo mockWiFiInfo = mock(WifiInfo.class); - when(mockWiFiInfo.getSSID()).thenReturn("TEST SSID"); - - when(mMockWiFiManager.getConnectionInfo()).thenReturn(mockWiFiInfo); + when(mockWiFiInfo.getSSID()).thenReturn(TEST_SSID); when(mMockWiFiManager.getConfiguredNetworks()).thenReturn(wifiList); when(mMockWiFiManager.getConnectionInfo()).thenReturn(mockWiFiInfo); @@ -358,45 +720,270 @@ public void testReconnectToNetworkFailureNotConnected() { when(mockNetworkInfo.isAvailable()).thenReturn(true); when(mockNetworkInfo.isConnected()).thenReturn(false); - boolean result = WiseFy.getSmarts().reconnectToNetwork(getActivity(), "TEST SSID", 1); + boolean result = WiseFy.getSmarts().isDeviceConnectedToSSID(mActivityTestRule.getActivity(), TEST_SSID); assertEquals(false, result); } - public void testReconnectToNetworkFailureNoList() { - WiseFy.getSmarts().mGetManagerUtil = mMockGetManagerUtil; - boolean result = WiseFy.getSmarts().reconnectToNetwork(getActivity(), "TEST SSID", 1); + @Test + public void testIsDeviceConnectedToSSIDFailureNullActivity() { + boolean result = WiseFy.getSmarts().isDeviceConnectedToSSID(null, TEST_SSID); assertEquals(false, result); } - public void testSearchSSIDNotFound() { - WiseFy.getSmarts().mGetManagerUtil = mMockGetManagerUtil; + @Test + public void testIsDeviceConnectedToSSIDFailureNullWifiManager() { + when(mMockGetManagerUtil.getWiFiManager(any(Activity.class))).thenReturn(null); + boolean result = WiseFy.getSmarts().isDeviceConnectedToSSID(mActivityTestRule.getActivity(), TEST_SSID); + assertEquals(false, result); + } + + @Test + public void testIsDeviceConnectedToWifiNetworkFailureSuccess() { + NetworkInfo mockNetworkInfo = mock(NetworkInfo.class); + when(mockNetworkInfo.getTypeName()).thenReturn("WIFI"); + + when(mMockConnectivityManager.getActiveNetworkInfo()).thenReturn(mockNetworkInfo); + when(mockNetworkInfo.isAvailable()).thenReturn(true); + when(mockNetworkInfo.isConnected()).thenReturn(true); + + boolean result = WiseFy.getSmarts().isDeviceConnectedToWifiNetwork(mActivityTestRule.getActivity()); + assertEquals(true, result); + } + + @Test + public void testIsDeviceConnectedToWifiNetworkFailureNotAvailable() { + NetworkInfo mockNetworkInfo = mock(NetworkInfo.class); + when(mockNetworkInfo.getTypeName()).thenReturn("WIFI"); + + when(mMockConnectivityManager.getActiveNetworkInfo()).thenReturn(mockNetworkInfo); + when(mockNetworkInfo.isAvailable()).thenReturn(false); + when(mockNetworkInfo.isConnected()).thenReturn(true); + + boolean result = WiseFy.getSmarts().isDeviceConnectedToWifiNetwork(mActivityTestRule.getActivity()); + assertEquals(false, result); + } + + @Test + public void testIsDeviceConnectedToWifiNetworkFailureNotConnected() { + NetworkInfo mockNetworkInfo = mock(NetworkInfo.class); + when(mockNetworkInfo.getTypeName()).thenReturn("WIFI"); + + when(mMockConnectivityManager.getActiveNetworkInfo()).thenReturn(mockNetworkInfo); + when(mockNetworkInfo.isAvailable()).thenReturn(true); + when(mockNetworkInfo.isConnected()).thenReturn(false); + + boolean result = WiseFy.getSmarts().isDeviceConnectedToWifiNetwork(mActivityTestRule.getActivity()); + assertEquals(false, result); + } + + @Test + public void testIsDeviceConnectedToWifiNetworkFailureWrongType() { + NetworkInfo mockNetworkInfo = mock(NetworkInfo.class); + when(mockNetworkInfo.getTypeName()).thenReturn("WRONG TYPE"); + + when(mMockConnectivityManager.getActiveNetworkInfo()).thenReturn(mockNetworkInfo); + when(mockNetworkInfo.isAvailable()).thenReturn(true); + when(mockNetworkInfo.isConnected()).thenReturn(true); + + boolean result = WiseFy.getSmarts().isDeviceConnectedToWifiNetwork(null); + assertEquals(false, result); + } + + @Test + public void testIsDeviceConnectedToWifiNetworkNullActivity() { + boolean result = WiseFy.getSmarts().isDeviceConnectedToWifiNetwork(null); + assertEquals(false, result); + } + + @Test + public void testIsDeviceConnectedToWifiNetworkNullConfigurationManager() { + when(mMockGetManagerUtil.getConnectivityManager(any(Activity.class))).thenReturn(null); + boolean result = WiseFy.getSmarts().isDeviceConnectedToWifiNetwork(mActivityTestRule.getActivity()); + assertEquals(false, result); + } + + @Test + public void testIsNetworkInConfigurationListFailure() { + assertEquals(false, WiseFy.getSmarts().isNetworkInConfigurationList(mActivityTestRule.getActivity(), TEST_SSID)); + } + + @Test + public void testIsNetworkInConfigurationListFailureNoNetworks() { + List wifiList = new ArrayList<>(); + when(mMockWiFiManager.getConfiguredNetworks()).thenReturn(wifiList); + assertEquals(false, WiseFy.getSmarts().isNetworkInConfigurationList(mActivityTestRule.getActivity(), TEST_SSID)); + } + + @Test + public void testIsNetworkInConfigurationListSuccess() { + List wifiList = new ArrayList<>(); + WifiConfiguration mWiFiConfiguration = new WifiConfiguration(); + mWiFiConfiguration.SSID = TEST_SSID; + wifiList.add(mWiFiConfiguration); + when(mMockWiFiManager.getConfiguredNetworks()).thenReturn(wifiList); + assertEquals(true, WiseFy.getSmarts().isNetworkInConfigurationList(mActivityTestRule.getActivity(), TEST_SSID)); + } + + @Test + public void testIsNetworkInConfigurationNullActivity() { + assertEquals(false, WiseFy.getSmarts().isNetworkInConfigurationList(null, TEST_SSID)); + } + + @Test + public void testIsNetworkInConfigurationNullWifiManager() { + when(mMockGetManagerUtil.getWiFiManager(any(Activity.class))).thenReturn(null); + assertEquals(false, WiseFy.getSmarts().isNetworkInConfigurationList(mActivityTestRule.getActivity(), TEST_SSID)); + } + + @Test + public void testIsNetworkSecureWithWEP() { + ScanResult scanResult = mock(ScanResult.class); + scanResult.capabilities = "WEP"; + assertEquals(true, WiseFy.getSmarts().isNetworkSecure(scanResult)); + } + + @Test + public void testIsNetworkSecureWithPSK() { + ScanResult scanResult = mock(ScanResult.class); + scanResult.capabilities = "PSK"; + assertEquals(true, WiseFy.getSmarts().isNetworkSecure(scanResult)); + } + + @Test + public void testIsNetworkSecureWithEAP() { + ScanResult scanResult = mock(ScanResult.class); + scanResult.capabilities = "EAP"; + assertEquals(true, WiseFy.getSmarts().isNetworkSecure(scanResult)); + } + + @Test + public void testIsNetworkSecureEmptyCapabilities() { + ScanResult scanResult = mock(ScanResult.class); + scanResult.capabilities = ""; + assertEquals(false, WiseFy.getSmarts().isNetworkSecure(scanResult)); + } + + @Test + public void testIsNetworkSecureNullCapabilities() { + ScanResult scanResult = mock(ScanResult.class); + assertEquals(false, WiseFy.getSmarts().isNetworkSecure(scanResult)); + } + + @Test + public void testIsWifiEnabledFailure() { + when(mMockWiFiManager.isWifiEnabled()).thenReturn(false); + assertEquals(false, WiseFy.getSmarts().isWifiEnabled(mActivityTestRule.getActivity())); + } + + @Test + public void testIsWifiEnabledSuccess() { + when(mMockWiFiManager.isWifiEnabled()).thenReturn(true); + assertEquals(true, WiseFy.getSmarts().isWifiEnabled(mActivityTestRule.getActivity())); + } + + @Test + public void testIsWifiEnabledNullActivity() { + assertEquals(false, WiseFy.getSmarts().isWifiEnabled(null)); + } + + @Test + public void testIsWifiEnabledNullWifiManager() { + when(mMockGetManagerUtil.getWiFiManager(any(Activity.class))).thenReturn(null); + assertEquals(false, WiseFy.getSmarts().isWifiEnabled(mActivityTestRule.getActivity())); + } + + @Test + public void testRemoveNetworkFailure() { + when(mMockWiFiManager.getConfiguredNetworks()).thenReturn(getTestWifiConfiguration()); + when(mMockWiFiManager.removeNetwork(anyInt())).thenReturn(false); + + boolean result = WiseFy.getSmarts().removeNetwork(mActivityTestRule.getActivity(), TEST_SSID); + assertEquals(false, result); + } + + @Test + public void testRemoveNetworkFailureNotInList() { + List wifiList = new ArrayList<>(); + when(mMockWiFiManager.getConfiguredNetworks()).thenReturn(wifiList); + when(mMockWiFiManager.removeNetwork(anyInt())).thenReturn(false); + + boolean result = WiseFy.getSmarts().removeNetwork(mActivityTestRule.getActivity(), TEST_SSID); + assertEquals(false, result); + } + + @Test + public void testRemoveNetworkNullActivity() { + boolean result = WiseFy.getSmarts().removeNetwork(null, TEST_SSID); + assertEquals(false, result); + } + + @Test + public void testRemoveNetworkNullWifiManager() { + when(mMockGetManagerUtil.getWiFiManager(any(Activity.class))).thenReturn(null); + boolean result = WiseFy.getSmarts().removeNetwork(null, TEST_SSID); + assertEquals(false, result); + } + + @Test + public void testRemoveNetworkSuccess() { + List wifiList = new ArrayList<>(); + WifiConfiguration mWiFiConfiguration = new WifiConfiguration(); + mWiFiConfiguration.SSID = TEST_SSID; + wifiList.add(mWiFiConfiguration); + when(mMockWiFiManager.getConfiguredNetworks()).thenReturn(wifiList); + when(mMockWiFiManager.removeNetwork(anyInt())).thenReturn(true); + + boolean result = WiseFy.getSmarts().removeNetwork(mActivityTestRule.getActivity(), TEST_SSID); + assertEquals(true, result); + } + + @Test + public void testSearchSSIDNFailure() { WifiInfo mockWifiInfo = mock(WifiInfo.class); - when(mockWifiInfo.getSSID()).thenReturn("TEST SSID"); + when(mockWifiInfo.getSSID()).thenReturn(TEST_SSID); when(mMockWiFiManager.getConnectionInfo()).thenReturn(mockWifiInfo); - assertEquals(null, WiseFy.getSmarts().searchForSSID(getActivity(), "TEST", 1)); + assertEquals(null, WiseFy.getSmarts().searchForSSID(mActivityTestRule.getActivity(), TEST_SSID, 1)); } - public void testSearchSSIDFound() { - WiseFy.getSmarts().mGetManagerUtil = mMockGetManagerUtil; + @Test + public void testSearchSSIDNullActivity() { + assertEquals(null, WiseFy.getSmarts().searchForSSID(null, TEST_SSID, 1)); + } + + @Test + public void testSearchSSIDNullWifiManager() { + when(mMockGetManagerUtil.getWiFiManager(any(Activity.class))).thenReturn(null); + assertEquals(null, WiseFy.getSmarts().searchForSSID(null, TEST_SSID, 1)); + } + + @Test + public void testSearchSSIDSuccess() { List scanResults = new ArrayList<>(); ScanResult scanResult = mock(ScanResult.class); - scanResult.SSID = "Test SSID"; + scanResult.SSID = TEST_SSID; scanResults.add(scanResult); WifiInfo mockWifiInfo = mock(WifiInfo.class); - when(mockWifiInfo.getSSID()).thenReturn("TEST SSID"); + when(mockWifiInfo.getSSID()).thenReturn(TEST_SSID); when(mMockWiFiManager.getConnectionInfo()).thenReturn(mockWifiInfo); when(mMockWiFiManager.getScanResults()).thenReturn(scanResults); - assertEquals("Test SSID", WiseFy.getSmarts().searchForSSID(getActivity(), "TEST", 1)); + assertEquals(TEST_SSID, WiseFy.getSmarts().searchForSSID(mActivityTestRule.getActivity(), TEST_SSID, 1)); } - /** - * HELPERS - */ + @Test + public void testSearchSSIDSuccessWithoutLogs() { + List scanResults = new ArrayList<>(); + ScanResult scanResult = mock(ScanResult.class); + scanResult.SSID = TEST_SSID; + scanResults.add(scanResult); + + WifiInfo mockWifiInfo = mock(WifiInfo.class); + when(mockWifiInfo.getSSID()).thenReturn(TEST_SSID); + when(mMockWiFiManager.getConnectionInfo()).thenReturn(mockWifiInfo); + when(mMockWiFiManager.getScanResults()).thenReturn(scanResults); - private WifiManager getLiveWiFiManager(Activity activity) { - return (WifiManager) activity.getSystemService(Context.WIFI_SERVICE); + assertEquals(TEST_SSID, WiseFy.getSmarts(false).searchForSSID(mActivityTestRule.getActivity(), TEST_SSID, 1)); } } \ No newline at end of file diff --git a/app/src/androidTest/java/com/metova/wisefy/base/BaseInstrumentationTestCase.java b/app/src/androidTest/java/com/metova/wisefy/base/BaseInstrumentationTestCase.java deleted file mode 100644 index 8aabc6ff..00000000 --- a/app/src/androidTest/java/com/metova/wisefy/base/BaseInstrumentationTestCase.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.metova.wisefy.base; - - -import android.app.Activity; -import android.test.ActivityInstrumentationTestCase2; -import com.robotium.solo.Solo; - - -public abstract class BaseInstrumentationTestCase extends ActivityInstrumentationTestCase2 { - - private Solo mSolo; - - public BaseInstrumentationTestCase(Class activityClass) { - super(activityClass); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - - System.setProperty("dexmaker.dexcache", getInstrumentation().getTargetContext().getCacheDir().toString()); - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - getSolo().finishOpenedActivities(); - } - - - protected Solo getSolo() { - if (mSolo == null) { - mSolo = new Solo(getInstrumentation(), getActivity()); - } - return mSolo; - } -} \ No newline at end of file diff --git a/app/src/androidTest/java/com/metova/wisefy/base/BaseTestClass.java b/app/src/androidTest/java/com/metova/wisefy/base/BaseTestClass.java new file mode 100644 index 00000000..6ef3498a --- /dev/null +++ b/app/src/androidTest/java/com/metova/wisefy/base/BaseTestClass.java @@ -0,0 +1,23 @@ +package com.metova.wisefy.base; + + +import android.app.Activity; +import android.content.Context; +import android.support.test.InstrumentationRegistry; +import android.support.test.rule.ActivityTestRule; + + +public abstract class BaseTestClass extends ActivityTestRule { + + private Context targetContext = InstrumentationRegistry.getTargetContext(); + + + public BaseTestClass(Class activityClass) { + super(activityClass); + } + + + public Context getTargetContext() { + return targetContext; + } +} \ No newline at end of file diff --git a/app/src/androidTest/java/com/metova/wisefy/util/GetManagerUtilTest.java b/app/src/androidTest/java/com/metova/wisefy/util/GetManagerUtilTest.java index aed8ba81..d38e140a 100644 --- a/app/src/androidTest/java/com/metova/wisefy/util/GetManagerUtilTest.java +++ b/app/src/androidTest/java/com/metova/wisefy/util/GetManagerUtilTest.java @@ -3,21 +3,43 @@ import android.net.ConnectivityManager; import android.net.wifi.WifiManager; -import com.metova.wisefy.base.BaseInstrumentationTestCase; +import android.support.test.rule.ActivityTestRule; +import com.metova.wisefy.base.BaseTestClass; +import org.junit.Rule; +import org.junit.Test; +import static junit.framework.Assert.*; -public class GetManagerUtilTest extends BaseInstrumentationTestCase { +public class GetManagerUtilTest extends BaseTestClass { public GetManagerUtilTest() { super(TestActivity.class); } + + @Rule + public ActivityTestRule mActivityTestRule = new ActivityTestRule<>(TestActivity.class); + + @Test + public void testGetConnectivityManager() { + ConnectivityManager connectivityManager = GetManagerUtil.getInstance().getConnectivityManager(mActivityTestRule.getActivity()); + assertNotNull(connectivityManager); + } + + @Test + public void testGetConnectivityManagerNullActivity() { + ConnectivityManager connectivityManager = GetManagerUtil.getInstance().getConnectivityManager(null); + assertNull(connectivityManager); + } + + @Test public void testGetWiFiManager() { - WifiManager wifiManager = GetManagerUtil.getInstance().getWiFiManager(getActivity()); + WifiManager wifiManager = GetManagerUtil.getInstance().getWiFiManager(mActivityTestRule.getActivity()); assertNotNull(wifiManager); } - public void testGetConnectivityManager() { - ConnectivityManager connectivityManager = GetManagerUtil.getInstance().getConnectivityManager(getActivity()); - assertNotNull(connectivityManager); + @Test + public void testGetWiFiManagerNullActivity() { + WifiManager wifiManager = GetManagerUtil.getInstance().getWiFiManager(null); + assertNull(wifiManager); } } \ No newline at end of file diff --git a/app/src/androidTest/java/com/metova/wisefy/util/TestUtils.java b/app/src/androidTest/java/com/metova/wisefy/util/TestUtils.java new file mode 100644 index 00000000..4250840a --- /dev/null +++ b/app/src/androidTest/java/com/metova/wisefy/util/TestUtils.java @@ -0,0 +1,32 @@ +package com.metova.wisefy.util; + + +import android.net.wifi.WifiConfiguration; +import java.util.ArrayList; +import java.util.List; + + +public class TestUtils { + + public static final String OPEN_NETWORK_SSID = "Open Network"; + + public static final String WEP_NETWORK_SSID = "WEP Network"; + + public static final String WEP_NETWORK_PASSWORD = "12345678"; + + public static final String WPA2_NETWORK_SSID = "WPA2 Network"; + + public static final String WPA2_NETWORK_PASSWORD = "123456"; + + public static final String TEST_SSID = "Test Network"; + + public static final String TEST_SSID2 = "Test Network 2"; + + public static List getTestWifiConfiguration() { + List wifiList = new ArrayList<>(); + WifiConfiguration mWiFiConfiguration = new WifiConfiguration(); + mWiFiConfiguration.SSID = TEST_SSID; + wifiList.add(mWiFiConfiguration); + return wifiList; + } +} \ No newline at end of file diff --git a/app/src/main/java/com/metova/wisefy/WiseFy.java b/app/src/main/java/com/metova/wisefy/WiseFy.java index 411d8c50..43256c76 100644 --- a/app/src/main/java/com/metova/wisefy/WiseFy.java +++ b/app/src/main/java/com/metova/wisefy/WiseFy.java @@ -3,555 +3,571 @@ import android.app.Activity; import android.net.ConnectivityManager; +import android.net.NetworkInfo; import android.net.wifi.ScanResult; import android.net.wifi.WifiConfiguration; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; -import android.os.Build; import android.support.annotation.VisibleForTesting; import android.text.TextUtils; import com.metova.wisefy.util.GetManagerUtil; import com.metova.wisefy.util.LogUtil; +import com.metova.wisefy.util.SSIDUtil; import java.util.ArrayList; import java.util.List; public class WiseFy { - public static final String TAG = WiseFy.class.getSimpleName(); + private static final String TAG = WiseFy.class.getSimpleName(); @VisibleForTesting public GetManagerUtil mGetManagerUtil = GetManagerUtil.getInstance(); - private static final WiseFy WIFI_MANAGER = new WiseFy(); + public static final int WISE_MANAGER_FAILURE = -1000; + + public static final int WIFI_MANAGER_FAILURE = -1; + + private LogUtil mLogUtil = LogUtil.getInstance(); + + private SSIDUtil mSSIDUtil = SSIDUtil.getInstance(); + + private static final WiseFy WISE_FY = new WiseFy(); + + private static boolean sLoggingEnabled; /** * Private constructor with no setup */ private WiseFy() { + } /** - * @return instance of WiFiManager + * @return instance of WiseFy */ public static WiseFy getSmarts() { - return WIFI_MANAGER; + return WISE_FY; + } + + public static WiseFy getSmarts(boolean loggingEnabled) { + sLoggingEnabled = loggingEnabled; + return WISE_FY; } /** - * To add a WEP network to the user's configured network list + * To add an open network to the user's configured network list * - * @param activity- The activity to use as context to retrieve a wifi manager via getSystemService - * @param ssid - The ssid of the WEP network you want to add - * @param password - The password for the WEP network being added + * @param activity - The activity to use as context to retrieve a wifi manager via getSystemService + * @param ssid - The ssid of the open network you want to add + * + * @return int - The return code from WifiManager for network creation (-1 for failure) */ - public void addWEPNetwork(Activity activity, String ssid, String password) { - if (TextUtils.isEmpty(ssid)) { - LogUtil.d(TAG, "Breaking due to empty ssid or password. ssid: " + ssid); - return; + public int addOpenNetwork(Activity activity, String ssid) { + if (TextUtils.isEmpty(ssid) || activity == null || activity.isFinishing()) { + mLogUtil.w(TAG, "Breaking due to missing ssid or activity. ssid: " + ssid, sLoggingEnabled); + return WISE_MANAGER_FAILURE; } - if (activity != null) { - WifiManager wifiManager = mGetManagerUtil.getWiFiManager(activity); - if (wifiManager != null) { - boolean ssidAlreadyConfigured = false; - List list = wifiManager.getConfiguredNetworks(); - if (list != null) { - for (int i = 0; i < list.size(); i++) { - WifiConfiguration wifiConfiguration = list.get(i); - if (wifiConfiguration != null && wifiConfiguration.SSID != null) { - String ssidInList = wifiConfiguration.SSID.replaceAll("\"", ""); - - if (ssidInList.equals(ssid)) { - LogUtil.d(TAG, "Found SSID in list"); - wifiManager.disconnect(); - wifiManager.enableNetwork(wifiConfiguration.networkId, true); - wifiManager.reconnect(); - ssidAlreadyConfigured = true; - break; - } - } - } - } - - if (!ssidAlreadyConfigured) { - LogUtil.d(TAG, "Adding WEP network with SSID " + ssid); - - WifiConfiguration wifiConfig = new WifiConfiguration(); - // On devices with version Kitkat and below, We need to send SSID name - // with double quotes. On devices with version Lollipop, We need to send - // SSID name without double quotes - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { - wifiConfig.SSID = ssid; - } else { - wifiConfig.SSID = "\"" + ssid + "\""; - } - - wifiConfig.wepKeys[0] = "\"" + password + "\""; - wifiConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); - wifiConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN); - wifiConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA); - wifiConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN); - wifiConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED); - wifiConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP); - wifiConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP); - wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40); - wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104); - - int result = wifiManager.addNetwork(wifiConfig); - if(result != -1) { - wifiManager.saveConfiguration(); - } else { - LogUtil.d(TAG, "Failed to add network"); - } - } + WifiManager wifiManager = mGetManagerUtil.getWiFiManager(activity); + if (wifiManager != null) { + boolean ssidAlreadyConfigured = isNetworkInConfigurationList(wifiManager, ssid); + + if (!ssidAlreadyConfigured) { + mLogUtil.d(TAG, "Adding open network with SSID " + ssid, sLoggingEnabled); + + WifiConfiguration wifiConfig = new WifiConfiguration(); + + wifiConfig.SSID = mSSIDUtil.convertSSIDForConfig(ssid); + wifiConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); + wifiConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN); + wifiConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA); + wifiConfig.allowedAuthAlgorithms.clear(); + wifiConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP); + wifiConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP); + wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40); + wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104); + wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP); + wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP); + + return addNetwork(wifiManager, wifiConfig); } } + return WISE_MANAGER_FAILURE; } /** - * To add a WPA2 network to the user's configured network list + * To add a WEP network to the user's configured network list * - * @param activity- The activity to use as context to retrieve a wifi manager via getSystemService - * @param ssid - The ssid of the WPA2 network you want to add - * @param password - The password for the WPA2 network being added + * @param activity - The activity to use as context to retrieve a wifi manager via getSystemService + * @param ssid - The ssid of the WEP network you want to add + * @param password - The password for the WEP network being added + * + * @return int - The return code from WifiManager for network creation (-1 for failure) */ - public void addWPA2Network(Activity activity, String ssid, String password) { - if (TextUtils.isEmpty(ssid) || TextUtils.isEmpty(password)) { - LogUtil.d(TAG, "Breaking due to empty ssid or password. ssid: " + ssid + ", password: " + password); - return; + public int addWEPNetwork(Activity activity, String ssid, String password) { + if (TextUtils.isEmpty(ssid) || TextUtils.isEmpty(password) || activity == null || activity.isFinishing()) { + mLogUtil.w(TAG, "Breaking due to missing ssid, password, or activity. ssid: " + ssid + ", password: " + password, sLoggingEnabled); + return WISE_MANAGER_FAILURE; } - if (activity != null) { - WifiManager wifiManager = mGetManagerUtil.getWiFiManager(activity); - if (wifiManager != null) { - boolean ssidAlreadyConfigured = false; - List list = wifiManager.getConfiguredNetworks(); - if (list != null) { - for (int i = 0; i < list.size(); i++) { - WifiConfiguration wifiConfiguration = list.get(i); - if (wifiConfiguration != null && wifiConfiguration.SSID != null) { - String ssidInList = wifiConfiguration.SSID.replaceAll("\"", ""); - - if (ssidInList.equals(ssid)) { - LogUtil.d(TAG, "Found SSID in list"); - wifiManager.disconnect(); - wifiManager.enableNetwork(wifiConfiguration.networkId, true); - wifiManager.reconnect(); - ssidAlreadyConfigured = true; - break; - } - } - } - } - - if (!ssidAlreadyConfigured) { - LogUtil.d(TAG, "Adding WPA2 network with SSID " + ssid); - - WifiConfiguration wifiConfig = new WifiConfiguration(); - // On devices with version Kitkat and below, We need to send SSID name - // with double quotes. On devices with version Lollipop, We need to send - // SSID name without double quotes - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { - wifiConfig.SSID = ssid; - } else { - wifiConfig.SSID = "\"" + ssid + "\""; - } - - wifiConfig.preSharedKey = "\"" + password + "\""; - wifiConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN); - wifiConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK); - wifiConfig.status = WifiConfiguration.Status.ENABLED; - wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP); - wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP); - wifiConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP); - wifiConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP); - wifiConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN); - wifiConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA); - - wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP); - wifiConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP); - - int result = wifiManager.addNetwork(wifiConfig); - if(result != -1) { - wifiManager.saveConfiguration(); - } else { - LogUtil.d(TAG, "Failed to add network"); - } - } + WifiManager wifiManager = mGetManagerUtil.getWiFiManager(activity); + if (wifiManager != null) { + boolean ssidAlreadyConfigured = isNetworkInConfigurationList(wifiManager, ssid); + + if (!ssidAlreadyConfigured) { + mLogUtil.d(TAG, "Adding WEP network with SSID " + ssid, sLoggingEnabled); + + WifiConfiguration wifiConfig = new WifiConfiguration(); + wifiConfig.SSID = mSSIDUtil.convertSSIDForConfig(ssid); + wifiConfig.wepKeys[0] = "\"" + password + "\""; + wifiConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); + wifiConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN); + wifiConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA); + wifiConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN); + wifiConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED); + wifiConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP); + wifiConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP); + wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40); + wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104); + + return addNetwork(wifiManager, wifiConfig); } } + return WISE_MANAGER_FAILURE; } /** - * To add an open network to the user's configured network list + * To add a WPA2 network to the user's configured network list * - * @param activity- The activity to use as context to retrieve a wifi manager via getSystemService - * @param ssid - The ssid of the open network you want to add + * @param activity - The activity to use as context to retrieve a wifi manager via getSystemService + * @param ssid - The ssid of the WPA2 network you want to add + * @param password - The password for the WPA2 network being added + * + * @return int - The return code from WifiManager for network creation (-1 for failure) */ - public void addOpenNetwork(Activity activity, String ssid) { - if (TextUtils.isEmpty(ssid)) { - LogUtil.d(TAG, "Breaking due to empty ssid or password. ssid: " + ssid); - return; + public int addWPA2Network(Activity activity, String ssid, String password) { + if (TextUtils.isEmpty(ssid) || TextUtils.isEmpty(password) || activity == null || activity.isFinishing()) { + mLogUtil.w(TAG, "Breaking due to missing ssid, password, or activity. ssid: " + ssid + ", password: " + password, sLoggingEnabled); + return WISE_MANAGER_FAILURE; } - if (activity != null) { - boolean ssidAlreadyConfigured = false; - WifiManager wifiManager = mGetManagerUtil.getWiFiManager(activity); - if (wifiManager != null) { - List list = wifiManager.getConfiguredNetworks(); - if (list != null) { - for (int i = 0; i < list.size(); i++) { - WifiConfiguration wifiConfiguration = list.get(i); - if (wifiConfiguration != null && wifiConfiguration.SSID != null) { - String ssidInList = wifiConfiguration.SSID.replaceAll("\"", ""); - - if (ssidInList.equals(ssid)) { - LogUtil.d(TAG, "Found SSID in list"); - wifiManager.disconnect(); - wifiManager.enableNetwork(wifiConfiguration.networkId, true); - wifiManager.reconnect(); - ssidAlreadyConfigured = true; - break; - } - } - } - } - - if(!ssidAlreadyConfigured) { - LogUtil.d(TAG, "Adding open network with SSID " + ssid); - - WifiConfiguration wifiConfig = new WifiConfiguration(); - // On devices with version Kitkat and below, We need to send SSID name - // with double quotes. On devices with version Lollipop, We need to send - // SSID name without double quotes - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { - wifiConfig.SSID = ssid; - } else { - wifiConfig.SSID = "\"" + ssid + "\""; - } - - wifiConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); - wifiConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN); - wifiConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA); - wifiConfig.allowedAuthAlgorithms.clear(); - wifiConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP); - wifiConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP); - wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40); - wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104); - wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP); - wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP); - - int result = wifiManager.addNetwork(wifiConfig); - if(result != -1) { - wifiManager.saveConfiguration(); - } else { - LogUtil.d(TAG, "Failed to add network"); - } - } + WifiManager wifiManager = mGetManagerUtil.getWiFiManager(activity); + if (wifiManager != null) { + boolean ssidAlreadyConfigured = isNetworkInConfigurationList(wifiManager, ssid); + + if (!ssidAlreadyConfigured) { + mLogUtil.d(TAG, "Adding WPA2 network with SSID " + ssid, sLoggingEnabled); + + WifiConfiguration wifiConfig = new WifiConfiguration(); + wifiConfig.SSID = mSSIDUtil.convertSSIDForConfig(ssid); + wifiConfig.preSharedKey = "\"" + password + "\""; + wifiConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN); + wifiConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK); + wifiConfig.status = WifiConfiguration.Status.ENABLED; + wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP); + wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP); + wifiConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP); + wifiConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP); + wifiConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN); + wifiConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA); + + wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP); + wifiConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP); + + return addNetwork(wifiManager, wifiConfig); } } + return WISE_MANAGER_FAILURE; } /** - * To convert RRSI level for a network to number of bars + * To convert an RSSI level for a network to a number of bars * * @param rssiLevel - The signal strength of the network * @param targetNumberOfBars - How many bars or levels there will be total - * @return int - Number of bars + * + * @return int - The number of bars for the given RSSI value */ public int calculateBars(int rssiLevel, int targetNumberOfBars) { return WifiManager.calculateSignalLevel(rssiLevel, targetNumberOfBars); } /** - * Used to check if a given SSID is in a connected state + * To compare the signal strength of two networks * - * Used by reconnectToNetwork + * @param rssi1 - The signal strength of network 1 + * @param rssi2 - The signal strength of network 2 * - * @param activity - The activity to use as context to retrieve a wifi manager and a connectivity manager via getSystemService - * @param ssid - - * @param timeout - - * @return int - Number of bars + * @return int - Returns <0 if the first signal is weaker than the second signal, 0 if the two + * signals have the same strength, and >0 if the first signal is stronger than the second signal. */ - private boolean checkWifi(Activity activity, String ssid, int timeout) { - for (int x = 0; x < timeout; x++) { - if (activity == null || activity.isFinishing()) { - LogUtil.d(TAG, "Breaking due to no activity"); - break; - } + public int compareSignalLevel(int rssi1, int rssi2) { + return WifiManager.compareSignalLevel(rssi1, rssi2); + } + + /** + * Used to connect to a network + * + * Gets a list of saved networks, connects/reconnects to the given ssid, and then calls waitToConnectToSSID to verify connectivity + * + * @param activity - The activity to use as context to retrieve a wifi manager via getSystemService + * @param ssidToReconnectTo - The ssid to connect/reconnect to + * @param timeout - The approximate number of seconds to keep reconnecting for the SSID + * + * @return boolean - If the network was successfully reconnected + */ + public boolean connectToNetwork(Activity activity, String ssidToReconnectTo, int timeout) { + if (activity != null && !activity.isFinishing()) { + mLogUtil.d(TAG, "Connecting to network: " + ssidToReconnectTo, sLoggingEnabled); WifiManager wifiManager = mGetManagerUtil.getWiFiManager(activity); if (wifiManager != null) { - WifiInfo connectionInfo = wifiManager.getConnectionInfo(); - if (connectionInfo != null && connectionInfo.getSSID() != null) { - String currentSSID = connectionInfo.getSSID().replaceAll("\"", ""); - LogUtil.d(TAG, "Current SSID: " + currentSSID); - - if (currentSSID.equals(ssid)) { - LogUtil.d(TAG, "Correct SSID"); - ConnectivityManager connectivityManager = mGetManagerUtil.getConnectivityManager(activity); - if (connectivityManager != null - && connectivityManager.getActiveNetworkInfo() != null - && connectivityManager.getActiveNetworkInfo().isAvailable() - && connectivityManager.getActiveNetworkInfo().isConnected()) { - LogUtil.d(TAG, "Network is connected"); - return true; + List list = wifiManager.getConfiguredNetworks(); + if (list != null) { + for (int i = 0; i < list.size(); i++) { + WifiConfiguration wifiConfiguration = list.get(i); + if (wifiConfiguration != null && wifiConfiguration.SSID != null) { + String ssidInList = wifiConfiguration.SSID.replaceAll("\"", ""); + + mLogUtil.d(TAG, "Configured WiFi Network {index:" + i + ", ssidInList:" + ssidInList + "}", sLoggingEnabled); + if (ssidInList.equals(ssidToReconnectTo)) { + mLogUtil.d(TAG, "ssidToReconnectTo: " + ssidToReconnectTo + " matches ssidInList:" + ssidInList, sLoggingEnabled); + wifiManager.disconnect(); + wifiManager.enableNetwork(wifiConfiguration.networkId, true); + wifiManager.reconnect(); + return waitToConnectToSSID(activity, ssidToReconnectTo, timeout); + } } } } - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - // Do nothing - } } + mLogUtil.w(TAG, "ssidToReconnectTo: " + ssidToReconnectTo + " was not found in list to reconnect to", sLoggingEnabled); + } else { + mLogUtil.w(TAG, "No activity to reconnect to network", sLoggingEnabled); } return false; } /** - * To compare the signal strength of two networks - * - * @param rssi1 - The signal strength of network 1 - * @param rssi2 - The signal strength of network 2 - * @return int - Returns <0 if the first signal is weaker than the second signal, 0 if the two - * signals have the same strength, and >0 if the first signal is stronger than the second signal. - */ - public int compareSignalLevel(int rssi1, int rssi2) { - return WifiManager.compareSignalLevel(rssi1, rssi2); - } - - /** - * To disable WiFi on a user's device + * To disable Wifi on a user's device * * @param activity - The activity to use as context to retrieve a wifi manager via getSystemService + * + * @return boolean - If the command succeeded in disabling wifi */ - public void disableWiFi(Activity activity) { - if(activity != null) { + public boolean disableWifi(Activity activity) { + if (activity != null && !activity.isFinishing()) { WifiManager wifiManager = mGetManagerUtil.getWiFiManager(activity); - if(wifiManager != null) { - wifiManager.setWifiEnabled(false); + if (wifiManager != null) { + return wifiManager.setWifiEnabled(false); } } else { - LogUtil.w(TAG, "No activity to disable Wifi"); + mLogUtil.w(TAG, "No activity to disable Wifi", sLoggingEnabled); } + return false; } /** * To disconnect the user from their current network * * @param activity - The activity to use as context to retrieve a wifi manager via getSystemService + * + * @return boolean - If the command succeeded in disconnecting the device from the current network */ - public void disconnectFromCurrentNetwork(Activity activity) { - if (activity != null) { - LogUtil.d(TAG, "Disconnecting from current network"); + public boolean disconnectFromCurrentNetwork(Activity activity) { + if (activity != null && !activity.isFinishing()) { + mLogUtil.d(TAG, "Disconnecting from current network", sLoggingEnabled); WifiManager wifiManager = mGetManagerUtil.getWiFiManager(activity); - if(wifiManager != null) { - wifiManager.disconnect(); + if (wifiManager != null) { + return wifiManager.disconnect(); } } else { - LogUtil.w(TAG, "No activity to disconnect from current network"); + mLogUtil.w(TAG, "No activity to disconnect from current network", sLoggingEnabled); } + return false; } - /** - * To enable WiFi on a user's device + * To enable Wifi on a user's device * * @param activity - The activity to use as context to retrieve a wifi manager via getSystemService + * + * @return boolean - If the command succeeded in enabling wifi */ - public void enableWiFi(Activity activity) { - if (activity != null) { - LogUtil.d(TAG, "Enabling WiFi"); + public boolean enableWifi(Activity activity) { + if (activity != null && !activity.isFinishing()) { + mLogUtil.d(TAG, "Enabling WiFi", sLoggingEnabled); WifiManager wifiManager = mGetManagerUtil.getWiFiManager(activity); - if(wifiManager != null) { - wifiManager.setWifiEnabled(true); + if (wifiManager != null) { + return wifiManager.setWifiEnabled(true); } } else { - LogUtil.w(TAG, "No activity to enable Wifi"); + mLogUtil.w(TAG, "No activity to enable Wifi", sLoggingEnabled); } + return false; } /** * To retrieve the user's current network * * @param activity - The activity to use as context to retrieve a wifi manager via getSystemService - * @return WifiInfo|null - The user's current network info + * + * @return WifiInfo|null - The user's current network information */ public WifiInfo getCurrentNetwork(Activity activity) { - if(activity != null) { + if (activity != null && !activity.isFinishing()) { WifiManager wifiManager = mGetManagerUtil.getWiFiManager(activity); - if(wifiManager != null) { + if (wifiManager != null) { return wifiManager.getConnectionInfo(); - } else { - return null; } } else { - LogUtil.w(TAG, "No activity to get current network"); - return null; + mLogUtil.w(TAG, "No activity to get current network", sLoggingEnabled); } + return null; } /** * To retrieve a list of nearby access points * - * Setting filterDuplicates to true will not return SSIDs with a weaker signal strength (will always take the highest) + * *NOTE* Setting filterDuplicates to true will not return SSIDs with a weaker signal strength (will always take the highest) * * @param activity - The activity to use as context to retrieve a wifi manager via getSystemService - * @param filterDuplicates - + * @param filterDuplicates - If you want to exclude SSIDs with that same name that have a weaker signal strength + * * @return List|null - List of nearby access points */ public List getNearbyAccessPoints(Activity activity, boolean filterDuplicates) { - if(activity != null) { + if (activity != null && !activity.isFinishing()) { WifiManager wifiManager = mGetManagerUtil.getWiFiManager(activity); - if(wifiManager != null) { + if (wifiManager != null) { wifiManager.startScan(); - if(!filterDuplicates) { + if (!filterDuplicates) { return wifiManager.getScanResults(); } else { List scanResults = wifiManager.getScanResults(); List scanResultsToReturn = new ArrayList<>(); - for(ScanResult newScanResult : scanResults) { + for (ScanResult newScanResult : scanResults) { boolean found = false; for (int i = 0; i < scanResultsToReturn.size(); i++) { ScanResult scanResult = scanResultsToReturn.get(i); - if(newScanResult.SSID.equals(scanResult.SSID)) { + mLogUtil.d(TAG, "SSID 1: " + newScanResult.SSID + ". SSID 2: " + scanResult.SSID, sLoggingEnabled); + if (newScanResult.SSID.equalsIgnoreCase(scanResult.SSID)) { found = true; - LogUtil.d(TAG, "SSID did match"); + mLogUtil.d(TAG, "SSID did match", sLoggingEnabled); - LogUtil.d(TAG, "Current level: " + scanResult.level); - LogUtil.d(TAG, "New level: " + newScanResult.level); - LogUtil.d(TAG, "comparison result: " + WifiManager.compareSignalLevel(newScanResult.level, scanResult.level)); + mLogUtil.d(TAG, "Current level: " + scanResult.level, sLoggingEnabled); + mLogUtil.d(TAG, "New level: " + newScanResult.level, sLoggingEnabled); + mLogUtil.d(TAG, "comparison result: " + WifiManager.compareSignalLevel(newScanResult.level, scanResult.level), sLoggingEnabled); if (WifiManager.compareSignalLevel(newScanResult.level, scanResult.level) > 0) { - LogUtil.d(TAG, "New result has a higher signal strength, swapping"); + mLogUtil.d(TAG, "New result has a higher signal strength, swapping", sLoggingEnabled); scanResultsToReturn.set(i, newScanResult); } } else { - LogUtil.d(TAG, "SSID did not match"); + mLogUtil.d(TAG, "SSID did not match", sLoggingEnabled); } } - if(!found) { - LogUtil.d(TAG, "Found new wifi network"); + if (!found) { + mLogUtil.d(TAG, "Found new wifi network", sLoggingEnabled); scanResultsToReturn.add(newScanResult); } } return scanResultsToReturn; } - } else { - return null; } } else { - LogUtil.w(TAG, "No activity to get nearby networks"); - return null; + mLogUtil.w(TAG, "No activity to get nearby access points", sLoggingEnabled); + } + return null; } /** * To retrieve a list of saved networks on a user's device * * @param activity - The activity to use as context to retrieve a wifi manager via getSystemService + * * @return List|null - List of saved networks on a users device */ public List getSavedNetworks(Activity activity) { - if(activity != null) { + if (activity != null && !activity.isFinishing()) { WifiManager wifiManager = mGetManagerUtil.getWiFiManager(activity); - if(wifiManager != null) { + if (wifiManager != null) { return wifiManager.getConfiguredNetworks(); - } else { - return null; } } else { - LogUtil.w(TAG, "No activity to get saved networks"); - return null; + mLogUtil.w(TAG, "No activity to get saved networks", sLoggingEnabled); } + return null; } /** - * To check and return if a network is secure (WEP/PSK/EAP capabilities) + * To check if the device is connected to a mobile network * - * @param scanResult - The network to see if it is secure - * @return boolean - Whether the network is secure + * @param activity - The activity to use as context to retrieve a wifi manager and a connectivity manager via getSystemService + * + * @return bool - If the device is currently connected to a mobile network */ - public boolean isSecure(ScanResult scanResult) { - boolean isSecure = false; - if(scanResult != null && scanResult.capabilities != null) { - if (scanResult.capabilities.contains("WEP") || scanResult.capabilities.contains("PSK") || scanResult.capabilities.contains("EAP")) { - isSecure = true; + public boolean isDeviceConnectedToMobileNetwork(Activity activity) { + if (activity != null && !activity.isFinishing()) { + ConnectivityManager connectivityManager = mGetManagerUtil.getConnectivityManager(activity); + if (connectivityManager != null) { + NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); + if (networkInfo != null && networkInfo.getTypeName().equalsIgnoreCase("MOBILE")) { + if (networkInfo.isConnected() && networkInfo.isAvailable()) { + return true; + } + } } } - return isSecure; + return false; + } + + /** + * To check if the device is connected to a mobile or wifi network + * + * @param activity - The activity to use as context to retrieve a wifi manager and a connectivity manager via getSystemService + * + * @return bool - If the device is currently connected to a mobile or wifi network + */ + public boolean isDeviceConnectedToMobileOrWifiNetwork(Activity activity) { + if (activity != null && !activity.isFinishing()) { + ConnectivityManager connectivityManager = mGetManagerUtil.getConnectivityManager(activity); + if (connectivityManager != null) { + NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); + if (networkInfo.isConnected() && networkInfo.isAvailable()) { + return true; + } + } + } + return false; + } + + /** + * To check if the device is connected to a given SSID + * + * Used by connectToNetwork + * + * @param activity - The activity to use as context to retrieve a wifi manager and a connectivity manager via getSystemService + * @param ssid - The SSID to check if the device is attached to + * + * @return bool - If the device is currently attached to the given SSID + */ + public boolean isDeviceConnectedToSSID(Activity activity, String ssid) { + if (activity == null || activity.isFinishing()) { + mLogUtil.w(TAG, "Breaking due to no activity", sLoggingEnabled); + return false; + } + WifiManager wifiManager = mGetManagerUtil.getWiFiManager(activity); + if (wifiManager != null) { + WifiInfo connectionInfo = wifiManager.getConnectionInfo(); + if (connectionInfo != null && connectionInfo.getSSID() != null) { + String currentSSID = connectionInfo.getSSID().replaceAll("\"", ""); + mLogUtil.d(TAG, "Current SSID: " + currentSSID, sLoggingEnabled); + + if (currentSSID.equals(ssid)) { + mLogUtil.d(TAG, "Correct SSID", sLoggingEnabled); + ConnectivityManager connectivityManager = mGetManagerUtil.getConnectivityManager(activity); + if (connectivityManager != null + && connectivityManager.getActiveNetworkInfo() != null + && connectivityManager.getActiveNetworkInfo().isAvailable() + && connectivityManager.getActiveNetworkInfo().isConnected()) { + mLogUtil.d(TAG, "Network is connected", sLoggingEnabled); + return true; + } + } + } + } + return false; } + /** + * To check if the device is connected to a wifi network + * + * @param activity - The activity to use as context to retrieve a wifi manager and a connectivity manager via getSystemService + * + * @return bool - If the device is currently connected to a wifi network + */ + public boolean isDeviceConnectedToWifiNetwork(Activity activity) { + if (activity != null && !activity.isFinishing()) { + ConnectivityManager connectivityManager = mGetManagerUtil.getConnectivityManager(activity); + if (connectivityManager != null) { + NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); + if (networkInfo != null && networkInfo.getTypeName().equalsIgnoreCase("WIFI")) { + if (networkInfo.isConnected() && networkInfo.isAvailable()) { + return true; + } + } + } + } + return false; + } /** - * To check if Wifi is enabled on the device or not + * To check if an SSID is in the list of configured networks * * @param activity - The activity to use as context to retrieve a wifi manager via getSystemService - * @return boolean - if Wifi is enabled on device + * + * @return boolean - If the SSID is in the list of configured networks */ - public boolean isWifiEnabled(Activity activity) { - boolean isWifiEnabled = false; - if(activity != null) { - WifiManager wifiManager = GetManagerUtil.getInstance().getWiFiManager(activity); - isWifiEnabled = wifiManager.isWifiEnabled(); + public boolean isNetworkInConfigurationList(Activity activity, String ssid) { + if (activity != null && !activity.isFinishing()) { + WifiManager wifiManager = mGetManagerUtil.getWiFiManager(activity); + if(wifiManager != null) { + return isNetworkInConfigurationList(wifiManager, ssid); + } } else { - LogUtil.w(TAG, "No activity to get wifi config"); + mLogUtil.w(TAG, "No activity to check if network is in configuration list", sLoggingEnabled); } - return isWifiEnabled; + return false; } /** - * Used to reconnect to a network + * To check and return if a network is secure (WEP/PSK/EAP capabilities) + * + * @param scanResult - The network to see if it is secure * - * Gets a list of saved networks, reconnects to the given ssid, and then calls checkWifi to verify connectivity + * @return boolean - Whether the network is secure + */ + public boolean isNetworkSecure(ScanResult scanResult) { + boolean isSecure = false; + if (scanResult != null && scanResult.capabilities != null) { + if (scanResult.capabilities.contains("WEP") || scanResult.capabilities.contains("PSK") || scanResult.capabilities.contains("EAP")) { + isSecure = true; + } + } + return isSecure; + } + + /** + * To check if Wifi is enabled on the device or not * * @param activity - The activity to use as context to retrieve a wifi manager via getSystemService - * @param ssidToReconnectTo - The ssid to reconnect to - * @param timeout - The approximate number of seconds to keep reconnecting for the SSID - * @return boolean - If the network was successfully reconnected + * + * @return boolean - if Wifi is enabled on device */ - public boolean reconnectToNetwork(Activity activity, String ssidToReconnectTo, int timeout) { - if (activity != null) { - LogUtil.d(TAG, "Reconnecting to network: " + ssidToReconnectTo); + public boolean isWifiEnabled(Activity activity) { + if (activity != null && !activity.isFinishing()) { WifiManager wifiManager = mGetManagerUtil.getWiFiManager(activity); if (wifiManager != null) { - List list = wifiManager.getConfiguredNetworks(); - if (list != null) { - for (int i = 0; i < list.size(); i++) { - WifiConfiguration wifiConfiguration = list.get(i); - if (wifiConfiguration != null && wifiConfiguration.SSID != null) { - String ssidInList = wifiConfiguration.SSID.replaceAll("\"", ""); - - LogUtil.d(TAG, "Configured WiFi Network {index:" + i + ", ssidInList:" + ssidInList + "}"); - if (ssidInList.equals(ssidToReconnectTo)) { - LogUtil.d(TAG, "ssidToReconnectTo: " + ssidToReconnectTo + " matches ssidInList:" + ssidInList); - wifiManager.disconnect(); - wifiManager.enableNetwork(wifiConfiguration.networkId, true); - wifiManager.reconnect(); - return checkWifi(activity, ssidToReconnectTo, timeout); - } - } - } - } - + return wifiManager.isWifiEnabled(); } - LogUtil.w(TAG, "ssidToReconnectTo: " + ssidToReconnectTo + " was not found in list to reconnect to"); } else { - LogUtil.w(TAG, "No activity to reconnect to network"); + mLogUtil.w(TAG, "No activity to check if wifi is enabled", sLoggingEnabled); } return false; } - /** * To remove a configured network * * @param activity - The activity to use as context to retrieve a wifi manager via getSystemService * @param ssidToRemove - The ssid of the network you want to remove from the configured network list + * + * @return boolean - If the command succeeded in removing the network */ - public void removeNetwork(Activity activity, String ssidToRemove) { - if (activity != null) { + public boolean removeNetwork(Activity activity, String ssidToRemove) { + if (activity != null && !activity.isFinishing()) { WifiManager wifiManager = mGetManagerUtil.getWiFiManager(activity); if (wifiManager != null) { List list = wifiManager.getConfiguredNetworks(); @@ -561,55 +577,56 @@ public void removeNetwork(Activity activity, String ssidToRemove) { if (wifiConfiguration != null && wifiConfiguration.SSID != null) { String ssidInList = wifiConfiguration.SSID.replaceAll("\"", ""); - LogUtil.d(TAG, "Configured WiFi Network {index:" + i + ", ssidInList:" + ssidInList + "}"); + mLogUtil.d(TAG, "Configured WiFi Network {index:" + i + ", ssidInList:" + ssidInList + "}", sLoggingEnabled); if (ssidInList.equals(ssidToRemove)) { - LogUtil.d(TAG, "Removing network: " + ssidToRemove); + mLogUtil.d(TAG, "Removing network: " + ssidToRemove, sLoggingEnabled); wifiManager.disconnect(); - wifiManager.removeNetwork(wifiConfiguration.networkId); + boolean result = wifiManager.removeNetwork(wifiConfiguration.networkId); + if (result) { + mLogUtil.d(TAG, "Successfully removed network", sLoggingEnabled); + wifiManager.saveConfiguration(); + } else { + mLogUtil.d(TAG, "Failed to remove network", sLoggingEnabled); + } wifiManager.reconnect(); + return result; } } } } } - LogUtil.w(TAG, "SSID to remove: " + ssidToRemove + " was not found in list to reconnect to"); + mLogUtil.w(TAG, "SSID to remove: " + ssidToRemove + " was not found in list to remove network", sLoggingEnabled); } else { - LogUtil.w(TAG, "No activity to reconnect to network"); + mLogUtil.w(TAG, "No activity to remove network", sLoggingEnabled); } + return false; } /** - * To search local networks and see if any of them match a given ssid + * To search local networks and return the first one that contains a given ssid (non-case sensitive) * * @param activity - The activity to use as context to retrieve a wifi manager via getSystemService * @param ssidToSearchFor - The ssid to search for * @param timeout - The approximate number of seconds to keep searching for the SSID + * * @return String|null - The first SSID that contains the search ssid (if any, else null) */ public String searchForSSID(Activity activity, String ssidToSearchFor, int timeout) { - String ssid = null; - if(activity != null) { + if (activity != null && !activity.isFinishing()) { WifiManager wifiManager = mGetManagerUtil.getWiFiManager(activity); - if(wifiManager != null) { + if (wifiManager != null) { for (int x = 0; x < timeout; x++) { - LogUtil.d(TAG, "Scanning SSIDs, pass " + x); + mLogUtil.d(TAG, "Scanning SSIDs, pass " + x, sLoggingEnabled); wifiManager.startScan(); List networks = wifiManager.getScanResults(); - boolean ssidFound = false; for (ScanResult scanResult : networks) { - LogUtil.d(TAG, "scanResult.SSID: " + scanResult.SSID); - if (scanResult.SSID != null - && (scanResult.SSID.toUpperCase().contains(ssidToSearchFor))) { - LogUtil.d(TAG, "Found match, SSID: " + scanResult.SSID); - ssid = scanResult.SSID; - ssidFound = true; - break; + mLogUtil.d(TAG, "scanResult.SSID: " + scanResult.SSID, sLoggingEnabled); + if (scanResult.SSID != null && (scanResult.SSID.toUpperCase().contains(ssidToSearchFor.toUpperCase()))) { + mLogUtil.d(TAG, "Found match, SSID: " + scanResult.SSID, sLoggingEnabled); + return scanResult.SSID; } } - if (ssidFound) { - break; - } try { Thread.sleep(1000); @@ -619,8 +636,64 @@ public String searchForSSID(Activity activity, String ssidToSearchFor, int timeo } } } else { - LogUtil.w(TAG, "No activity to search for SSID"); + mLogUtil.w(TAG, "No activity to search for SSID", sLoggingEnabled); } - return ssid; + return null; + } + + /** + * HELPERS + */ + + /** + * + * @param wifiManager + * @param wifiConfig + * @return + */ + private int addNetwork(WifiManager wifiManager, WifiConfiguration wifiConfig) { + int result = wifiManager.addNetwork(wifiConfig); + if (result != WIFI_MANAGER_FAILURE) { + mLogUtil.d(TAG, "Successfully added network", sLoggingEnabled); + wifiManager.saveConfiguration(); + } else { + mLogUtil.e(TAG, "Failed to add network", sLoggingEnabled); + } + return result; + } + + private boolean isNetworkInConfigurationList(WifiManager wifiManager, String ssid) { + List list = wifiManager.getConfiguredNetworks(); + if (list != null && list.size() > 0) { + for (int i = 0; i < list.size(); i++) { + WifiConfiguration wifiConfiguration = list.get(i); + if (wifiConfiguration != null && wifiConfiguration.SSID != null) { + String ssidInList = wifiConfiguration.SSID.replaceAll("\"", ""); + mLogUtil.d(TAG, "SSID in list: " + ssidInList + ", SSID: " + ssid, sLoggingEnabled); + if (ssidInList.equals(ssid)) { + mLogUtil.d(TAG, "Found SSID in list", sLoggingEnabled); + return true; + } + } + } + } else { + mLogUtil.w(TAG, "Found 0 configured networks", sLoggingEnabled); + } + return false; + } + + private boolean waitToConnectToSSID(Activity activity, String ssid, int timeout) { + for (int x = 0; x < timeout; x++) { + boolean result = isDeviceConnectedToSSID(activity, ssid); + if (result) { + return result; + } + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + // Do nothing + } + } + return false; } } \ No newline at end of file diff --git a/app/src/main/java/com/metova/wisefy/util/GetManagerUtil.java b/app/src/main/java/com/metova/wisefy/util/GetManagerUtil.java index bca3b0f5..7187fb09 100644 --- a/app/src/main/java/com/metova/wisefy/util/GetManagerUtil.java +++ b/app/src/main/java/com/metova/wisefy/util/GetManagerUtil.java @@ -5,7 +5,6 @@ import android.content.Context; import android.net.ConnectivityManager; import android.net.wifi.WifiManager; - import com.metova.wisefy.WiseFy; diff --git a/app/src/main/java/com/metova/wisefy/util/LogUtil.java b/app/src/main/java/com/metova/wisefy/util/LogUtil.java index e47e270c..08f1cb20 100644 --- a/app/src/main/java/com/metova/wisefy/util/LogUtil.java +++ b/app/src/main/java/com/metova/wisefy/util/LogUtil.java @@ -7,45 +7,42 @@ public class LogUtil { - public static void d (String tag, String message) { - if(LogUtil.isLoggable(tag, Log.DEBUG)) { - Log.d(tag, message); - } - } + private static final LogUtil LOG_UTIL = new LogUtil(); - public static void d (String tag, String message, Throwable throwable) { - if(LogUtil.isLoggable(tag, Log.DEBUG)) { - Log.d(tag, message, throwable); - } + /** + * Private constructor with no setup + */ + private LogUtil() { } - public static void w (String tag, String message) { - if(LogUtil.isLoggable(tag, Log.WARN)) { - Log.w(tag, message); - } + /** + * @return instance of LogUtil + */ + public static LogUtil getInstance() { + return LOG_UTIL; } - public static void w (String tag, String message, Throwable throwable) { - if(LogUtil.isLoggable(tag, Log.WARN)) { - Log.w(tag, message, throwable); + public void d (String tag, String message, boolean loggingEnabled) { + if(isLoggable(tag, Log.DEBUG, loggingEnabled)) { + Log.d(tag, message); } } - public static void e (String tag, String message) { - if(LogUtil.isLoggable(tag, Log.ERROR)) { - Log.e(tag, message); + public void w (String tag, String message, boolean loggingEnabled) { + if(isLoggable(tag, Log.WARN, loggingEnabled)) { + Log.w(tag, message); } } - public static void e (String tag, String message, Throwable throwable) { - if(LogUtil.isLoggable(tag, Log.ERROR)) { - Log.e(tag, message, throwable); + public void e (String tag, String message, boolean loggingEnabled) { + if(isLoggable(tag, Log.ERROR, loggingEnabled)) { + Log.e(tag, message); } } - public static boolean isLoggable(String tag, int level) { + private boolean isLoggable(String tag, int level, boolean loggingEnabled) { boolean isLoggable; - if(BuildConfig.DEBUG) { + if(BuildConfig.DEBUG || loggingEnabled) { isLoggable = true; } else { if (tag.length() > 23) { diff --git a/app/src/main/java/com/metova/wisefy/util/SSIDUtil.java b/app/src/main/java/com/metova/wisefy/util/SSIDUtil.java new file mode 100644 index 00000000..a4b64832 --- /dev/null +++ b/app/src/main/java/com/metova/wisefy/util/SSIDUtil.java @@ -0,0 +1,33 @@ +package com.metova.wisefy.util; + + +import android.os.Build; + +public class SSIDUtil { + + private static final SSIDUtil SSID_UTIL = new SSIDUtil(); + + /** + * Private constructor with no setup + */ + private SSIDUtil() { + } + + /** + * @return instance of SSIDUtil + */ + public static SSIDUtil getInstance() { + return SSID_UTIL; + } + + public String convertSSIDForConfig(String ssid) { + // On devices with version Kitkat and below, We need to send SSID name + // with double quotes. On devices with version Lollipop, We need to send + // SSID name without double quotes + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + return ssid; + } else { + return "\"" + ssid + "\""; + } + } +} diff --git a/build.gradle b/build.gradle index bc44e4a6..c0fee68a 100644 --- a/build.gradle +++ b/build.gradle @@ -3,8 +3,11 @@ buildscript { jcenter() } dependencies { - classpath 'com.android.tools.build:gradle:2.0.0' - classpath 'com.getkeepsafe.dexcount:dexcount-gradle-plugin:0.5.0' + classpath 'com.android.tools.build:gradle:2.2.1' + classpath 'com.getkeepsafe.dexcount:dexcount-gradle-plugin:0.5.6' + classpath "org.jacoco:org.jacoco.core:0.7.7.201606060606" + classpath "org.jacoco:org.jacoco.agent:0.7.7.201606060606" + classpath "org.jacoco:org.jacoco.report:0.7.7.201606060606" } } diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 122a0dca..f73024bf 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ -#Mon Dec 28 10:00:20 PST 2015 +#Sat Oct 15 13:02:11 CDT 2016 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-2.10-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip