Merge "Remove hotspot receiver from manifest." into oc-dev
diff --git a/AndroidManifest.xml b/AndroidManifest.xml
index cb20c51..ecba241 100644
--- a/AndroidManifest.xml
+++ b/AndroidManifest.xml
@@ -440,13 +440,6 @@
             </intent-filter>
         </activity>
 
-        <receiver
-            android:name=".HotspotOffReceiver" >
-            <intent-filter>
-                <action android:name="android.net.wifi.WIFI_AP_STATE_CHANGED" />
-            </intent-filter>
-        </receiver>
-
         <activity android:name="Settings$TetherSettingsActivity"
                 android:label="@string/tether_settings_title_all"
                 android:icon="@drawable/ic_settings_wireless"
diff --git a/src/com/android/settings/HotspotOffReceiver.java b/src/com/android/settings/HotspotOffReceiver.java
index 3db0ee9..4083082 100644
--- a/src/com/android/settings/HotspotOffReceiver.java
+++ b/src/com/android/settings/HotspotOffReceiver.java
@@ -4,12 +4,11 @@
 import android.content.BroadcastReceiver;
 import android.content.Context;
 import android.content.Intent;
+import android.content.IntentFilter;
 import android.net.ConnectivityManager;
 import android.net.wifi.WifiManager;
 import android.util.Log;
 
-import com.android.settingslib.TetherUtil;
-
 /**
  * This receiver catches when quick settings turns off the hotspot, so we can
  * cancel the alarm in that case.  All other cancels are handled in tethersettings.
@@ -19,6 +18,13 @@
     private static final String TAG = "HotspotOffReceiver";
     private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
 
+    private Context mContext;
+    private boolean mRegistered;
+
+    public HotspotOffReceiver(Context context) {
+        mContext = context;
+    }
+
     @Override
     public void onReceive(Context context, Intent intent) {
         if (WifiManager.WIFI_AP_STATE_CHANGED_ACTION.equals(intent.getAction())) {
@@ -31,4 +37,19 @@
             }
         }
     }
+
+    public void register() {
+        if (!mRegistered) {
+            mContext.registerReceiver(this,
+                new IntentFilter(WifiManager.WIFI_AP_STATE_CHANGED_ACTION));
+            mRegistered = true;
+        }
+    }
+
+    public void unregister() {
+        if (mRegistered) {
+            mContext.unregisterReceiver(this);
+            mRegistered = false;
+        }
+    }
 }
diff --git a/src/com/android/settings/TetherService.java b/src/com/android/settings/TetherService.java
index 610d320..fce3f27 100644
--- a/src/com/android/settings/TetherService.java
+++ b/src/com/android/settings/TetherService.java
@@ -41,7 +41,6 @@
 import android.util.Log;
 
 import com.android.internal.annotations.VisibleForTesting;
-import com.android.settingslib.TetherUtil;
 
 import java.util.ArrayList;
 import java.util.List;
@@ -69,6 +68,7 @@
     private UsageStatsManagerWrapper mUsageManagerWrapper;
     private ArrayList<Integer> mCurrentTethers;
     private ArrayMap<Integer, List<ResultReceiver>> mPendingCallbacks;
+    private HotspotOffReceiver mHotspotReceiver;
 
     @Override
     public IBinder onBind(Intent intent) {
@@ -94,6 +94,7 @@
         if (mUsageManagerWrapper == null) {
             mUsageManagerWrapper = new UsageStatsManagerWrapper(this);
         }
+        mHotspotReceiver = new HotspotOffReceiver(this);
     }
 
     @Override
@@ -181,6 +182,11 @@
         }
     }
 
+    @VisibleForTesting
+    void setHotspotOffReceiver(HotspotOffReceiver receiver) {
+        mHotspotReceiver = receiver;
+    }
+
     private ArrayList<Integer> stringToTethers(String tethersStr) {
         ArrayList<Integer> ret = new ArrayList<Integer>();
         if (TextUtils.isEmpty(tethersStr)) return ret;
@@ -276,7 +282,8 @@
         }
     }
 
-    private void scheduleAlarm() {
+    @VisibleForTesting
+    void scheduleAlarm() {
         Intent intent = new Intent(this, TetherService.class);
         intent.putExtra(ConnectivityManager.EXTRA_RUN_PROVISION, true);
 
@@ -289,6 +296,7 @@
         if (DEBUG) Log.d(TAG, "Scheduling alarm at interval " + periodMs);
         alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME, firstTime, periodMs,
                 pendingIntent);
+        mHotspotReceiver.register();
     }
 
     /**
@@ -302,7 +310,8 @@
         context.startService(intent);
     }
 
-    private void cancelAlarmIfNecessary() {
+    @VisibleForTesting
+    void cancelAlarmIfNecessary() {
         if (mCurrentTethers.size() != 0) {
             if (DEBUG) Log.d(TAG, "Tethering still active, not cancelling alarm");
             return;
@@ -312,6 +321,7 @@
         AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
         alarmManager.cancel(pendingIntent);
         if (DEBUG) Log.d(TAG, "Tethering no longer active, canceling recheck");
+        mHotspotReceiver.unregister();
     }
 
     private void fireCallbacksForType(int type, int result) {
diff --git a/tests/robotests/src/com/android/settings/TetherServiceTest.java b/tests/robotests/src/com/android/settings/TetherServiceTest.java
new file mode 100644
index 0000000..2d5a2fb
--- /dev/null
+++ b/tests/robotests/src/com/android/settings/TetherServiceTest.java
@@ -0,0 +1,87 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.settings;
+
+import static com.google.common.truth.Truth.assertThat;
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+
+import android.content.Context;
+import android.content.Intent;
+import android.net.wifi.WifiManager;
+import java.util.ArrayList;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.robolectric.annotation.Config;
+import org.robolectric.shadows.ShadowApplication;
+import org.robolectric.util.ReflectionHelpers;
+
+@RunWith(SettingsRobolectricTestRunner.class)
+@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
+public class TetherServiceTest {
+
+    @Mock
+    private Context mContext;
+
+    private ShadowApplication mShadowApplication;
+    private Context mAppContext;
+    private TetherService mService;
+
+    @Before
+    public void setUp() {
+        MockitoAnnotations.initMocks(this);
+        mShadowApplication = ShadowApplication.getInstance();
+        mAppContext = mShadowApplication.getApplicationContext();
+        mService = new TetherService();
+        ReflectionHelpers.setField(mService, "mBase", mAppContext);
+        mService.setHotspotOffReceiver(new HotspotOffReceiver(mContext));
+    }
+
+    @Test
+    public void scheduleAlarm_shouldRegisterReceiver() {
+        mService.setHotspotOffReceiver(new HotspotOffReceiver(mAppContext));
+
+        mService.scheduleAlarm();
+
+        assertThat(mShadowApplication.hasReceiverForIntent(
+            new Intent(WifiManager.WIFI_AP_STATE_CHANGED_ACTION))).isTrue();
+    }
+
+    @Test
+    public void cancelAlarmIfNecessary_hasActiveTethers_shouldNotUnregisterReceiver() {
+        mService.scheduleAlarm();
+        final ArrayList<Integer> tethers = new ArrayList<>();
+        tethers.add(1);
+        ReflectionHelpers.setField(mService, "mCurrentTethers", tethers);
+
+        mService.cancelAlarmIfNecessary();
+        verify(mContext, never()).unregisterReceiver(any(HotspotOffReceiver.class));
+    }
+
+    @Test
+    public void cancelAlarmIfNecessary_noActiveTethers_shouldUnregisterReceiver() {
+        final ArrayList<Integer> tethers = new ArrayList<>();
+        ReflectionHelpers.setField(mService, "mCurrentTethers", tethers);
+        mService.scheduleAlarm();
+
+        mService.cancelAlarmIfNecessary();
+        verify(mContext).unregisterReceiver(any(HotspotOffReceiver.class));
+    }
+}