Merge "Fix memory leaks in Settings" into pi-dev
diff --git a/AndroidManifest.xml b/AndroidManifest.xml
index fb74bf9..2c5f846 100644
--- a/AndroidManifest.xml
+++ b/AndroidManifest.xml
@@ -3314,10 +3314,15 @@
         </provider>
 
         <receiver
-            android:name=".slices.SliceBroadcastReceiver" >
-            <intent-filter>
-                <action android:name="com.android.settings.slice.action.WIFI_CHANGED"/>
-            </intent-filter>
+            android:name=".slices.SliceBroadcastReceiver"
+            android:exported="false">
+        </receiver>
+
+        <receiver
+            android:name=".slices.SliceRelayReceiver"
+            android:permission="android.permission.MANAGE_SLICE_PERMISSIONS"
+            android:exported="true">
+
         </receiver>
 
         <!-- Couldn't be triggered from outside of settings. Statsd can trigger it because we send
diff --git a/src/com/android/settings/SettingsActivity.java b/src/com/android/settings/SettingsActivity.java
index 971ae04..29cd77a 100644
--- a/src/com/android/settings/SettingsActivity.java
+++ b/src/com/android/settings/SettingsActivity.java
@@ -291,8 +291,10 @@
             launchSettingFragment(initialFragmentName, isSubSettings, intent);
         }
 
+        final boolean deviceProvisioned = Utils.isDeviceProvisioned(this);
         if (mIsShowingDashboard) {
-            findViewById(R.id.search_bar).setVisibility(View.VISIBLE);
+            findViewById(R.id.search_bar).setVisibility(
+                    deviceProvisioned ? View.VISIBLE : View.INVISIBLE);
             findViewById(R.id.action_bar).setVisibility(View.GONE);
             final Toolbar toolbar = findViewById(R.id.search_action_bar);
             FeatureFactory.getFactory(this).getSearchFeatureProvider()
@@ -311,7 +313,6 @@
 
         ActionBar actionBar = getActionBar();
         if (actionBar != null) {
-            boolean deviceProvisioned = Utils.isDeviceProvisioned(this);
             actionBar.setDisplayHomeAsUpEnabled(deviceProvisioned);
             actionBar.setHomeButtonEnabled(deviceProvisioned);
             actionBar.setDisplayShowTitleEnabled(!mIsShowingDashboard);
diff --git a/src/com/android/settings/password/ChooseLockGeneric.java b/src/com/android/settings/password/ChooseLockGeneric.java
index 62978b3..1a8afd0 100644
--- a/src/com/android/settings/password/ChooseLockGeneric.java
+++ b/src/com/android/settings/password/ChooseLockGeneric.java
@@ -164,6 +164,11 @@
         @Override
         public void onCreate(Bundle savedInstanceState) {
             super.onCreate(savedInstanceState);
+            final Activity activity = getActivity();
+            if (!Utils.isDeviceProvisioned(activity) && !canRunBeforeDeviceProvisioned()) {
+                activity.finish();
+                return;
+            }
 
             String chooseLockAction = getActivity().getIntent().getAction();
             mFingerprintManager = Utils.getFingerprintManagerOrNull(getActivity());
@@ -249,6 +254,10 @@
             addHeaderView();
         }
 
+        protected boolean canRunBeforeDeviceProvisioned() {
+            return false;
+        }
+
         protected void addHeaderView() {
             if (mForFingerprint) {
                 setHeaderView(R.layout.choose_lock_generic_fingerprint_header);
diff --git a/src/com/android/settings/password/SetupChooseLockGeneric.java b/src/com/android/settings/password/SetupChooseLockGeneric.java
index 179bd79..885f9df 100644
--- a/src/com/android/settings/password/SetupChooseLockGeneric.java
+++ b/src/com/android/settings/password/SetupChooseLockGeneric.java
@@ -129,6 +129,11 @@
             return layout.onCreateRecyclerView(inflater, parent, savedInstanceState);
         }
 
+        @Override
+        protected boolean canRunBeforeDeviceProvisioned() {
+            return true;
+        }
+
         /***
          * Disables preferences that are less secure than required quality and shows only secure
          * screen lock options here.
diff --git a/src/com/android/settings/search/actionbar/SearchMenuController.java b/src/com/android/settings/search/actionbar/SearchMenuController.java
index 1729ccd..131f788 100644
--- a/src/com/android/settings/search/actionbar/SearchMenuController.java
+++ b/src/com/android/settings/search/actionbar/SearchMenuController.java
@@ -25,6 +25,7 @@
 import android.view.MenuItem;
 
 import com.android.settings.R;
+import com.android.settings.Utils;
 import com.android.settings.overlay.FeatureFactory;
 import com.android.settings.search.SearchFeatureProvider;
 import com.android.settingslib.core.lifecycle.LifecycleObserver;
@@ -52,6 +53,9 @@
 
     @Override
     public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
+        if (!Utils.isDeviceProvisioned(mHost.getContext())) {
+            return;
+        }
         if (menu == null) {
             return;
         }
diff --git a/src/com/android/settings/slices/SettingsSliceProvider.java b/src/com/android/settings/slices/SettingsSliceProvider.java
index 841247b..3b5e72e 100644
--- a/src/com/android/settings/slices/SettingsSliceProvider.java
+++ b/src/com/android/settings/slices/SettingsSliceProvider.java
@@ -382,7 +382,7 @@
     void registerIntentToUri(IntentFilter intentFilter, Uri sliceUri) {
         Log.d(TAG, "Registering Uri for broadcast relay: " + sliceUri);
         mRegisteredUris.add(sliceUri);
-        SliceBroadcastRelay.registerReceiver(getContext(), sliceUri, SliceBroadcastReceiver.class,
+        SliceBroadcastRelay.registerReceiver(getContext(), sliceUri, SliceRelayReceiver.class,
                 intentFilter);
     }
 
diff --git a/src/com/android/settings/slices/SliceBroadcastReceiver.java b/src/com/android/settings/slices/SliceBroadcastReceiver.java
index d81734a..53fa4be 100644
--- a/src/com/android/settings/slices/SliceBroadcastReceiver.java
+++ b/src/com/android/settings/slices/SliceBroadcastReceiver.java
@@ -44,7 +44,6 @@
 import com.android.settings.notification.ZenModeSliceBuilder;
 import com.android.settings.overlay.FeatureFactory;
 import com.android.settings.wifi.WifiSliceBuilder;
-import com.android.settingslib.SliceBroadcastRelay;
 
 /**
  * Responds to actions performed on slices and notifies slices of updates in state changes.
@@ -84,12 +83,6 @@
             case ACTION_ZEN_MODE_SLICE_CHANGED:
                 ZenModeSliceBuilder.handleUriChange(context, intent);
                 break;
-            default:
-                final String uriString = intent.getStringExtra(SliceBroadcastRelay.EXTRA_URI);
-                if (!TextUtils.isEmpty(uriString)) {
-                    final Uri uri = Uri.parse(uriString);
-                    context.getContentResolver().notifyChange(uri, null /* observer */);
-                }
         }
     }
 
diff --git a/src/com/android/settings/slices/SliceRelayReceiver.java b/src/com/android/settings/slices/SliceRelayReceiver.java
new file mode 100644
index 0000000..c8ec12e
--- /dev/null
+++ b/src/com/android/settings/slices/SliceRelayReceiver.java
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2018 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.slices;
+
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.net.Uri;
+import android.text.TextUtils;
+import com.android.settingslib.SliceBroadcastRelay;
+
+/**
+ * Receives broadcasts to notify that Settings Slices are potentially stale.
+ */
+public class SliceRelayReceiver extends BroadcastReceiver {
+
+    @Override
+    public void onReceive(Context context, Intent intent) {
+        final String uriString = intent.getStringExtra(SliceBroadcastRelay.EXTRA_URI);
+        if (!TextUtils.isEmpty(uriString)) {
+            final Uri uri = Uri.parse(uriString);
+            context.getContentResolver().notifyChange(uri, null /* observer */);
+        }
+    }
+}
\ No newline at end of file
diff --git a/tests/robotests/src/com/android/settings/SettingsActivityTest.java b/tests/robotests/src/com/android/settings/SettingsActivityTest.java
index 2096629..54b01ea 100644
--- a/tests/robotests/src/com/android/settings/SettingsActivityTest.java
+++ b/tests/robotests/src/com/android/settings/SettingsActivityTest.java
@@ -16,6 +16,7 @@
 
 package com.android.settings;
 
+import static com.google.common.truth.Truth.assertThat;
 import static org.mockito.ArgumentMatchers.nullable;
 import static org.mockito.Matchers.anyInt;
 import static org.mockito.Mockito.doReturn;
@@ -27,17 +28,25 @@
 import android.app.ActivityManager;
 import android.app.FragmentManager;
 import android.app.FragmentTransaction;
+import android.content.Context;
 import android.content.Intent;
 import android.graphics.Bitmap;
+import android.os.Bundle;
+import android.provider.Settings.Global;
+import android.view.View;
 
 import com.android.settings.testutils.SettingsRobolectricTestRunner;
+import com.android.settings.testutils.shadow.SettingsShadowResources;
+import com.android.settings.testutils.shadow.SettingsShadowResourcesImpl;
 
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 import org.mockito.Mock;
 import org.mockito.MockitoAnnotations;
+import org.robolectric.Robolectric;
 import org.robolectric.RuntimeEnvironment;
+import org.robolectric.annotation.Config;
 
 @RunWith(SettingsRobolectricTestRunner.class)
 public class SettingsActivityTest {
@@ -49,16 +58,47 @@
     @Mock
     private Bitmap mBitmap;
     private SettingsActivity mActivity;
+    private Context mContext;
 
     @Before
     public void setUp() {
         MockitoAnnotations.initMocks(this);
 
+        mContext = RuntimeEnvironment.application;
         mActivity = spy(new SettingsActivity());
         doReturn(mBitmap).when(mActivity).getBitmapFromXmlResource(anyInt());
     }
 
     @Test
+    @Config(shadows = {
+        SettingsShadowResourcesImpl.class,
+        SettingsShadowResources.SettingsShadowTheme.class,
+    })
+    public void onCreate_deviceNotProvisioned_shouldDisableSearch() {
+        Global.putInt(mContext.getContentResolver(), Global.DEVICE_PROVISIONED, 0);
+        final Intent intent = new Intent(mContext, Settings.class);
+        final SettingsActivity activity =
+            Robolectric.buildActivity(SettingsActivity.class, intent).create(Bundle.EMPTY).get();
+
+        assertThat(activity.findViewById(R.id.search_bar).getVisibility())
+            .isEqualTo(View.INVISIBLE);
+    }
+
+    @Test
+    @Config(shadows = {
+        SettingsShadowResourcesImpl.class,
+        SettingsShadowResources.SettingsShadowTheme.class,
+    })
+    public void onCreate_deviceProvisioned_shouldEnableSearch() {
+        Global.putInt(mContext.getContentResolver(), Global.DEVICE_PROVISIONED, 1);
+        final Intent intent = new Intent(mContext, Settings.class);
+        final SettingsActivity activity =
+            Robolectric.buildActivity(SettingsActivity.class, intent).create(Bundle.EMPTY).get();
+
+        assertThat(activity.findViewById(R.id.search_bar).getVisibility()).isEqualTo(View.VISIBLE);
+    }
+
+    @Test
     public void launchSettingFragment_nullExtraShowFragment_shouldNotCrash() {
         when(mActivity.getFragmentManager()).thenReturn(mFragmentManager);
         when(mFragmentManager.beginTransaction()).thenReturn(mock(FragmentTransaction.class));
diff --git a/tests/robotests/src/com/android/settings/password/ChooseLockGenericTest.java b/tests/robotests/src/com/android/settings/password/ChooseLockGenericTest.java
new file mode 100644
index 0000000..7a14896
--- /dev/null
+++ b/tests/robotests/src/com/android/settings/password/ChooseLockGenericTest.java
@@ -0,0 +1,65 @@
+/*
+ * Copyright (C) 2018 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.password;
+
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import android.app.Activity;
+import android.content.Context;
+import android.os.Bundle;
+import android.provider.Settings.Global;
+
+import com.android.settings.password.ChooseLockGeneric.ChooseLockGenericFragment;
+import com.android.settings.testutils.SettingsRobolectricTestRunner;
+import com.android.settings.testutils.shadow.SettingsShadowResources;
+
+import org.junit.After;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.robolectric.RuntimeEnvironment;
+import org.robolectric.annotation.Config;
+
+@RunWith(SettingsRobolectricTestRunner.class)
+public class ChooseLockGenericTest {
+
+    @After
+    public void tearDown() {
+        Global.putInt(RuntimeEnvironment.application.getContentResolver(),
+            Global.DEVICE_PROVISIONED, 1);
+    }
+
+    @Test
+    @Config(shadows = SettingsShadowResources.SettingsShadowTheme.class)
+    public void onCreate_deviceNotProvisioned_shouldFinishActivity() {
+        final Context context = RuntimeEnvironment.application;
+        Global.putInt(context.getContentResolver(), Global.DEVICE_PROVISIONED, 0);
+        final Activity activity = mock(Activity.class);
+        when(activity.getContentResolver()).thenReturn(context.getContentResolver());
+        when(activity.getTheme()).thenReturn(context.getTheme());
+
+        final ChooseLockGenericFragment fragment = spy(new ChooseLockGenericFragment());
+        when(fragment.getActivity()).thenReturn(activity);
+        when(fragment.getArguments()).thenReturn(Bundle.EMPTY);
+
+        fragment.onCreate(Bundle.EMPTY);
+        verify(activity).finish();
+    }
+
+}
diff --git a/tests/robotests/src/com/android/settings/search/actionbar/SearchMenuControllerTest.java b/tests/robotests/src/com/android/settings/search/actionbar/SearchMenuControllerTest.java
index 7ff4acc..9900df2 100644
--- a/tests/robotests/src/com/android/settings/search/actionbar/SearchMenuControllerTest.java
+++ b/tests/robotests/src/com/android/settings/search/actionbar/SearchMenuControllerTest.java
@@ -17,11 +17,14 @@
 package com.android.settings.search.actionbar;
 
 import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.spy;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.verifyZeroInteractions;
 import static org.mockito.Mockito.when;
 
+import android.content.Context;
 import android.os.Bundle;
+import android.provider.Settings.Global;
 import android.view.Menu;
 import android.view.MenuItem;
 
@@ -35,6 +38,7 @@
 import org.junit.runner.RunWith;
 import org.mockito.Mock;
 import org.mockito.MockitoAnnotations;
+import org.robolectric.RuntimeEnvironment;
 
 @RunWith(SettingsRobolectricTestRunner.class)
 public class SearchMenuControllerTest {
@@ -43,12 +47,16 @@
     private Menu mMenu;
     private TestPreferenceFragment mPreferenceHost;
     private ObservableFragment mHost;
+    private Context mContext;
 
     @Before
     public void setUp() {
         MockitoAnnotations.initMocks(this);
-        mHost = new ObservableFragment();
+        mContext = RuntimeEnvironment.application;
+        mHost = spy(new ObservableFragment());
+        when(mHost.getContext()).thenReturn(mContext);
         mPreferenceHost = new TestPreferenceFragment();
+        Global.putInt(mContext.getContentResolver(), Global.DEVICE_PROVISIONED, 1);
 
         when(mMenu.add(Menu.NONE, Menu.NONE, 0 /* order */, R.string.search_menu))
                 .thenReturn(mock(MenuItem.class));
@@ -81,9 +89,23 @@
         verifyZeroInteractions(mMenu);
     }
 
+    @Test
+    public void init_deviceNotProvisioned_shouldNotAddMenu() {
+        Global.putInt(mContext.getContentResolver(), Global.DEVICE_PROVISIONED, 0);
+        SearchMenuController.init(mHost);
+        mHost.getLifecycle().onCreateOptionsMenu(mMenu, null /* inflater */);
+
+        verifyZeroInteractions(mMenu);
+    }
+
     private static class TestPreferenceFragment extends ObservablePreferenceFragment {
         @Override
         public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
         }
+
+        @Override
+        public Context getContext() {
+            return RuntimeEnvironment.application;
+        }
     }
 }
diff --git a/tests/robotests/src/com/android/settings/slices/SliceBroadcastReceiverTest.java b/tests/robotests/src/com/android/settings/slices/SliceBroadcastReceiverTest.java
index 25f0d0c..f8172e8 100644
--- a/tests/robotests/src/com/android/settings/slices/SliceBroadcastReceiverTest.java
+++ b/tests/robotests/src/com/android/settings/slices/SliceBroadcastReceiverTest.java
@@ -159,8 +159,12 @@
 
         assertThat(fakeToggleController.isChecked()).isFalse();
 
-        final Uri expectedUri = SliceBuilderUtils.getUri(
-                SettingsSlicesContract.PATH_SETTING_ACTION + "/" + key, false);
+        final Uri expectedUri = new Uri.Builder()
+                .scheme(ContentResolver.SCHEME_CONTENT)
+                .authority(SettingsSliceProvider.SLICE_AUTHORITY)
+                .appendPath(SettingsSlicesContract.PATH_SETTING_ACTION)
+                .appendPath(key)
+                .build();
         verify(resolver).notifyChange(eq(expectedUri), eq(null));
     }
 
diff --git a/tests/robotests/src/com/android/settings/slices/SliceRelayReceiverTest.java b/tests/robotests/src/com/android/settings/slices/SliceRelayReceiverTest.java
new file mode 100644
index 0000000..3388a16
--- /dev/null
+++ b/tests/robotests/src/com/android/settings/slices/SliceRelayReceiverTest.java
@@ -0,0 +1,72 @@
+/*
+ * Copyright (C) 2018 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.slices;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.verify;
+
+import android.content.ContentResolver;
+import android.content.Context;
+
+import android.content.Intent;
+import android.net.Uri;
+import android.provider.SettingsSlicesContract;
+import com.android.settings.testutils.SettingsRobolectricTestRunner;
+import com.android.settingslib.SliceBroadcastRelay;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.robolectric.RuntimeEnvironment;
+
+@RunWith(SettingsRobolectricTestRunner.class)
+public class SliceRelayReceiverTest {
+
+  private Context mContext;
+  private SliceRelayReceiver mSliceRelayReceiver;
+
+  @Before
+  public void setUp() {
+      mContext = spy(RuntimeEnvironment.application);
+      mSliceRelayReceiver = new SliceRelayReceiver();
+  }
+
+
+  @Test
+  public void onReceive_extraUri_notifiesChangeOnUri() {
+      // Monitor the ContentResolver
+      final ContentResolver resolver = spy(mContext.getContentResolver());
+      doReturn(resolver).when(mContext).getContentResolver();
+
+      final Uri uri = new Uri.Builder()
+          .scheme(ContentResolver.SCHEME_CONTENT)
+          .authority(SettingsSlicesContract.AUTHORITY)
+          .appendPath("path")
+          .build();
+
+      final Intent intent = new Intent();
+    intent.putExtra(SliceBroadcastRelay.EXTRA_URI, uri.toString());
+
+    mSliceRelayReceiver.onReceive(mContext, intent);
+
+    verify(resolver).notifyChange(eq(uri), any());
+
+  }
+}