Merge "[Settings] Change the way in MobileNetworkSummaryController for getting the subscription info from room db"
diff --git a/src/com/android/settings/network/MobileNetworkRepository.java b/src/com/android/settings/network/MobileNetworkRepository.java
index 912b36b..aad2f79 100644
--- a/src/com/android/settings/network/MobileNetworkRepository.java
+++ b/src/com/android/settings/network/MobileNetworkRepository.java
@@ -298,6 +298,10 @@
             getUiccInfoBySubscriptionInfo(uiccSlotInfos, subInfo);
             insertUiccInfo();
             insertMobileNetworkInfo(context);
+            SubscriptionInfo firstRemovableSubInfo = SubscriptionUtil.getFirstRemovableSubscription(
+                    context);
+            SubscriptionInfo subscriptionOrDefault = SubscriptionUtil.getSubscriptionOrDefault(
+                    context, mSubId);
             Log.d(TAG, "convert subscriptionInfo to entity for subId = " + mSubId);
             return new SubscriptionInfoEntity(String.valueOf(mSubId),
                     subInfo.getSimSlotIndex(),
@@ -311,12 +315,11 @@
                     SubscriptionUtil.getUniqueSubscriptionDisplayName(subInfo, context).toString(),
                     SubscriptionUtil.isSubscriptionVisible(mSubscriptionManager, context, subInfo),
                     SubscriptionUtil.getFormattedPhoneNumber(context, subInfo),
-                    SubscriptionUtil.getFirstRemovableSubscription(context) == null ? false
-                            : SubscriptionUtil.getFirstRemovableSubscription(
-                                    context).getSubscriptionId() == mSubId,
+                    firstRemovableSubInfo == null ? false
+                            : firstRemovableSubInfo.getSubscriptionId() == mSubId,
                     String.valueOf(SubscriptionUtil.getDefaultSimConfig(context, mSubId)),
-                    SubscriptionUtil.getSubscriptionOrDefault(context, mSubId).getSubscriptionId()
-                            == mSubId,
+                    subscriptionOrDefault == null ? false
+                            : subscriptionOrDefault.getSubscriptionId() == mSubId,
                     mSubscriptionManager.isValidSubscriptionId(mSubId),
                     mSubscriptionManager.isUsableSubscriptionId(mSubId),
                     mSubscriptionManager.isActiveSubscriptionId(mSubId),
diff --git a/src/com/android/settings/network/MobileNetworkSummaryController.java b/src/com/android/settings/network/MobileNetworkSummaryController.java
index 1a85a7f..4358120 100644
--- a/src/com/android/settings/network/MobileNetworkSummaryController.java
+++ b/src/com/android/settings/network/MobileNetworkSummaryController.java
@@ -22,12 +22,12 @@
 import android.content.Context;
 import android.content.Intent;
 import android.os.UserManager;
-import android.provider.Settings;
-import android.telephony.SubscriptionManager;
 import android.telephony.euicc.EuiccManager;
+import android.util.Log;
 
 import androidx.lifecycle.Lifecycle;
 import androidx.lifecycle.LifecycleObserver;
+import androidx.lifecycle.LifecycleOwner;
 import androidx.lifecycle.OnLifecycleEvent;
 import androidx.preference.Preference;
 import androidx.preference.PreferenceScreen;
@@ -35,32 +35,36 @@
 import com.android.settings.R;
 import com.android.settings.core.PreferenceControllerMixin;
 import com.android.settings.dashboard.DashboardFragment;
-import com.android.settings.network.helper.SubscriptionAnnotation;
 import com.android.settings.network.telephony.MobileNetworkUtils;
 import com.android.settings.overlay.FeatureFactory;
 import com.android.settings.widget.AddPreference;
 import com.android.settingslib.Utils;
 import com.android.settingslib.core.AbstractPreferenceController;
 import com.android.settingslib.core.instrumentation.MetricsFeatureProvider;
+import com.android.settingslib.mobile.dataservice.MobileNetworkInfoEntity;
+import com.android.settingslib.mobile.dataservice.SubscriptionInfoEntity;
+import com.android.settingslib.mobile.dataservice.UiccInfoEntity;
 
 import java.util.List;
 import java.util.stream.Collectors;
 
 public class MobileNetworkSummaryController extends AbstractPreferenceController implements
-        SubscriptionsChangeListener.SubscriptionsChangeListenerClient, LifecycleObserver,
-        PreferenceControllerMixin {
+        LifecycleObserver, PreferenceControllerMixin,
+        MobileNetworkRepository.MobileNetworkCallback {
     private static final String TAG = "MobileNetSummaryCtlr";
 
     private static final String KEY = "mobile_network_list";
 
     private final MetricsFeatureProvider mMetricsFeatureProvider;
-
-    private SubscriptionManager mSubscriptionManager;
     private UserManager mUserManager;
-    private SubscriptionsChangeListener mChangeListener;
     private AddPreference mPreference;
 
-    private MobileNetworkSummaryStatus mStatusCache = new MobileNetworkSummaryStatus();
+    private MobileNetworkRepository mMobileNetworkRepository;
+    private List<SubscriptionInfoEntity> mSubInfoEntityList;
+    private List<UiccInfoEntity> mUiccInfoEntityList;
+    private List<MobileNetworkInfoEntity> mMobileNetworkInfoEntityList;
+    private boolean mIsAirplaneModeOn;
+    private LifecycleOwner mLifecycleOwner;
 
     /**
      * This controls the summary text and click behavior of the "Mobile network" item on the
@@ -77,26 +81,27 @@
      * and the summary text gives the count of SIMs</li>
      * </ul>
      */
-    public MobileNetworkSummaryController(Context context, Lifecycle lifecycle) {
+    public MobileNetworkSummaryController(Context context, Lifecycle lifecycle,
+            LifecycleOwner lifecycleOwner) {
         super(context);
         mMetricsFeatureProvider = FeatureFactory.getFactory(mContext).getMetricsFeatureProvider();
-        mSubscriptionManager = context.getSystemService(SubscriptionManager.class);
         mUserManager = context.getSystemService(UserManager.class);
+        mLifecycleOwner = lifecycleOwner;
+        mMobileNetworkRepository = new MobileNetworkRepository(context, this);
         if (lifecycle != null) {
-            mChangeListener = new SubscriptionsChangeListener(context, this);
             lifecycle.addObserver(this);
         }
     }
 
     @OnLifecycleEvent(ON_RESUME)
     public void onResume() {
-        mChangeListener.start();
+        mMobileNetworkRepository.addRegister(mLifecycleOwner);
         update();
     }
 
     @OnLifecycleEvent(ON_PAUSE)
     public void onPause() {
-        mChangeListener.stop();
+        mMobileNetworkRepository.removeRegister();
     }
 
     @Override
@@ -107,28 +112,27 @@
 
     @Override
     public CharSequence getSummary() {
-        mStatusCache.update(mContext, null);
-        List<SubscriptionAnnotation> subs = mStatusCache.getSubscriptionList();
 
-        if (subs.isEmpty()) {
-            if (mStatusCache.isEuiccConfigSupport()) {
+        if ((mSubInfoEntityList == null || mSubInfoEntityList.isEmpty()) || (
+                mUiccInfoEntityList == null || mUiccInfoEntityList.isEmpty()) || (
+                mMobileNetworkInfoEntityList == null || mMobileNetworkInfoEntityList.isEmpty())) {
+            if (MobileNetworkUtils.showEuiccSettingsDetecting(mContext)) {
                 return mContext.getResources().getString(
                         R.string.mobile_network_summary_add_a_network);
             }
             // set empty string to override previous text for carrier when SIM available
             return "";
-        } else if (subs.size() == 1) {
-            SubscriptionAnnotation info = subs.get(0);
-            CharSequence displayName = mStatusCache.getDisplayName(info.getSubscriptionId());
-            if (info.getSubInfo().isEmbedded() || info.isActive()
-                    || mStatusCache.isPhysicalSimDisableSupport()) {
+        } else if (mSubInfoEntityList.size() == 1) {
+            SubscriptionInfoEntity info = mSubInfoEntityList.get(0);
+            CharSequence displayName = info.uniqueName;
+            if (info.isEmbedded || mUiccInfoEntityList.get(0).isActive
+                    || mMobileNetworkInfoEntityList.get(0).showToggleForPhysicalSim) {
                 return displayName;
             }
             return mContext.getString(R.string.mobile_network_tap_to_activate, displayName);
         } else {
-            return subs.stream()
-                    .mapToInt(SubscriptionAnnotation::getSubscriptionId)
-                    .mapToObj(subId -> mStatusCache.getDisplayName(subId))
+            return mSubInfoEntityList.stream()
+                    .map(SubscriptionInfoEntity::getUniqueDisplayName)
                     .collect(Collectors.joining(", "));
         }
     }
@@ -149,7 +153,7 @@
         mPreference.setOnPreferenceClickListener(null);
         mPreference.setOnAddClickListener(null);
         mPreference.setFragment(null);
-        mPreference.setEnabled(!mChangeListener.isAirplaneModeOn());
+        mPreference.setEnabled(!mIsAirplaneModeOn);
     }
 
     private void update() {
@@ -157,11 +161,12 @@
             return;
         }
 
-        mStatusCache.update(mContext, statusCache -> initPreference());
-
-        List<SubscriptionAnnotation> subs = mStatusCache.getSubscriptionList();
-        if (subs.isEmpty()) {
-            if (mStatusCache.isEuiccConfigSupport()) {
+        initPreference();
+        if (((mSubInfoEntityList == null || mSubInfoEntityList.isEmpty())
+                || (mUiccInfoEntityList == null || mUiccInfoEntityList.isEmpty())
+                || (mMobileNetworkInfoEntityList == null
+                || mMobileNetworkInfoEntityList.isEmpty()))) {
+            if (MobileNetworkUtils.showEuiccSettingsDetecting(mContext)) {
                 mPreference.setOnPreferenceClickListener((Preference pref) -> {
                     logPreferenceClick(pref);
                     startAddSimFlow();
@@ -175,28 +180,26 @@
 
         // We have one or more existing subscriptions, so we want the plus button if eSIM is
         // supported.
-        if (mStatusCache.isEuiccConfigSupport()) {
-            mPreference.setAddWidgetEnabled(!mChangeListener.isAirplaneModeOn());
+        if (MobileNetworkUtils.showEuiccSettingsDetecting(mContext)) {
+            mPreference.setAddWidgetEnabled(!mIsAirplaneModeOn);
             mPreference.setOnAddClickListener(p -> {
                 logPreferenceClick(p);
                 startAddSimFlow();
             });
         }
 
-        if (subs.size() == 1) {
+        if (mSubInfoEntityList.size() == 1) {
             mPreference.setOnPreferenceClickListener((Preference pref) -> {
                 logPreferenceClick(pref);
-
-                SubscriptionAnnotation info = subs.get(0);
-                if (info.getSubInfo().isEmbedded() || info.isActive()
-                        || mStatusCache.isPhysicalSimDisableSupport()) {
-                    MobileNetworkUtils.launchMobileNetworkSettings(mContext,
-                            info.getSubInfo());
+                SubscriptionInfoEntity info = mSubInfoEntityList.get(0);
+                if (info.isEmbedded || mUiccInfoEntityList.get(0).isActive
+                        || mMobileNetworkInfoEntityList.get(0).showToggleForPhysicalSim) {
+                    MobileNetworkUtils.launchMobileNetworkSettings(mContext, info);
                     return true;
                 }
 
                 SubscriptionUtil.startToggleSubscriptionDialogActivity(
-                        mContext, info.getSubscriptionId(), true);
+                        mContext, Integer.parseInt(info.subId), true);
                 return true;
             });
         } else {
@@ -216,14 +219,35 @@
 
     @Override
     public void onAirplaneModeChanged(boolean airplaneModeEnabled) {
-        mStatusCache.update(mContext, statusCache -> update());
+        mIsAirplaneModeOn = airplaneModeEnabled;
+        update();
     }
 
     @Override
-    public void onSubscriptionsChanged() {
-        mStatusCache.update(mContext, statusCache -> {
-            refreshSummary(mPreference);
+    public void onAvailableSubInfoChanged(List<SubscriptionInfoEntity> subInfoEntityList) {
+        if ((mSubInfoEntityList != null &&
+                (subInfoEntityList.isEmpty() || !subInfoEntityList.equals(mSubInfoEntityList)))
+                || (!subInfoEntityList.isEmpty() && mSubInfoEntityList == null)) {
+            Log.d(TAG, "subInfo list from framework is changed, update the subInfo entity list.");
+            mSubInfoEntityList = subInfoEntityList;
             update();
-        });
+        }
+    }
+
+    @Override
+    public void onActiveSubInfoChanged(List<SubscriptionInfoEntity> activeSubInfoList) {
+    }
+
+    @Override
+    public void onAllUiccInfoChanged(List<UiccInfoEntity> uiccInfoEntityList) {
+        mUiccInfoEntityList = uiccInfoEntityList;
+        update();
+    }
+
+    @Override
+    public void onAllMobileNetworkInfoChanged(
+            List<MobileNetworkInfoEntity> mobileNetworkInfoEntityList) {
+        mMobileNetworkInfoEntityList = mobileNetworkInfoEntityList;
+        update();
     }
 }
diff --git a/src/com/android/settings/network/NetworkDashboardFragment.java b/src/com/android/settings/network/NetworkDashboardFragment.java
index 0cd24dc..0da2d50 100644
--- a/src/com/android/settings/network/NetworkDashboardFragment.java
+++ b/src/com/android/settings/network/NetworkDashboardFragment.java
@@ -27,6 +27,7 @@
 
 import androidx.appcompat.app.AlertDialog;
 import androidx.fragment.app.Fragment;
+import androidx.lifecycle.LifecycleOwner;
 
 import com.android.settings.R;
 import com.android.settings.Utils;
@@ -87,12 +88,12 @@
     @Override
     protected List<AbstractPreferenceController> createPreferenceControllers(Context context) {
         return buildPreferenceControllers(context, getSettingsLifecycle(), mMetricsFeatureProvider,
-                this /* fragment */, this /* mobilePlanHost */);
+                this /* fragment */, this /* mobilePlanHost */, this /* LifecycleOwner */);
     }
 
     private static List<AbstractPreferenceController> buildPreferenceControllers(Context context,
             Lifecycle lifecycle, MetricsFeatureProvider metricsFeatureProvider, Fragment fragment,
-            MobilePlanPreferenceHost mobilePlanHost) {
+            MobilePlanPreferenceHost mobilePlanHost, LifecycleOwner lifecycleOwner) {
         final MobilePlanPreferenceController mobilePlanPreferenceController =
                 new MobilePlanPreferenceController(context, mobilePlanHost);
         final InternetPreferenceController internetPreferenceController =
@@ -111,7 +112,7 @@
 
         final List<AbstractPreferenceController> controllers = new ArrayList<>();
 
-        controllers.add(new MobileNetworkSummaryController(context, lifecycle));
+        controllers.add(new MobileNetworkSummaryController(context, lifecycle, lifecycleOwner));
         controllers.add(new TetherPreferenceController(context, lifecycle));
         controllers.add(vpnPreferenceController);
         controllers.add(new ProxyPreferenceController(context));
@@ -172,7 +173,7 @@
                         context) {
                     return buildPreferenceControllers(context, null /* lifecycle */,
                             null /* metricsFeatureProvider */, null /* fragment */,
-                            null /* mobilePlanHost */);
+                            null /* mobilePlanHost */, null /* LifecycleOwner */);
                 }
             };
 }
diff --git a/src/com/android/settings/network/telephony/MobileNetworkUtils.java b/src/com/android/settings/network/telephony/MobileNetworkUtils.java
index 548ce28..d16d281 100644
--- a/src/com/android/settings/network/telephony/MobileNetworkUtils.java
+++ b/src/com/android/settings/network/telephony/MobileNetworkUtils.java
@@ -82,6 +82,7 @@
 import com.android.settingslib.core.instrumentation.Instrumentable;
 import com.android.settingslib.development.DevelopmentSettingsEnabler;
 import com.android.settingslib.graph.SignalDrawable;
+import com.android.settingslib.mobile.dataservice.SubscriptionInfoEntity;
 import com.android.settingslib.utils.ThreadUtils;
 
 import java.util.Arrays;
@@ -1031,4 +1032,22 @@
                 .launch();
     }
 
+    public static void launchMobileNetworkSettings(Context context, SubscriptionInfoEntity info) {
+        final int subId = Integer.valueOf(info.subId);
+        if (subId == SubscriptionManager.INVALID_SUBSCRIPTION_ID) {
+            Log.d(TAG, "launchMobileNetworkSettings fail, subId is invalid.");
+            return;
+        }
+
+        Log.d(TAG, "launchMobileNetworkSettings for SubscriptionInfoEntity subId: " + subId);
+        final Bundle extra = new Bundle();
+        extra.putInt(Settings.EXTRA_SUB_ID, subId);
+        new SubSettingLauncher(context)
+                .setTitleText(info.uniqueName)
+                .setDestination(MobileNetworkSettings.class.getCanonicalName())
+                .setSourceMetricsCategory(Instrumentable.METRICS_CATEGORY_UNKNOWN)
+                .setArguments(extra)
+                .launch();
+    }
+
 }
diff --git a/tests/robotests/src/com/android/settings/network/MobileNetworkSummaryControllerTest.java b/tests/robotests/src/com/android/settings/network/MobileNetworkSummaryControllerTest.java
index dcf086c..a6c4f67 100644
--- a/tests/robotests/src/com/android/settings/network/MobileNetworkSummaryControllerTest.java
+++ b/tests/robotests/src/com/android/settings/network/MobileNetworkSummaryControllerTest.java
@@ -40,7 +40,7 @@
 import android.telephony.euicc.EuiccManager;
 import android.text.TextUtils;
 
-import androidx.lifecycle.Lifecycle;
+import androidx.lifecycle.LifecycleOwner;
 import androidx.preference.PreferenceScreen;
 
 import com.android.settings.Settings.MobileNetworkActivity;
@@ -48,6 +48,7 @@
 import com.android.settings.network.helper.SubscriptionGrouping;
 import com.android.settings.widget.AddPreference;
 import com.android.settingslib.RestrictedLockUtils;
+import com.android.settingslib.core.lifecycle.Lifecycle;
 
 import org.junit.After;
 import org.junit.Before;
@@ -64,8 +65,7 @@
 
 @RunWith(RobolectricTestRunner.class)
 public class MobileNetworkSummaryControllerTest {
-    @Mock
-    private Lifecycle mLifecycle;
+
     @Mock
     private TelephonyManager mTelephonyManager;
     @Mock
@@ -76,10 +76,16 @@
     private PreferenceScreen mPreferenceScreen;
     @Mock
     private UserManager mUserManager;
+    @Mock
+    private MobileNetworkRepository mMobileNetworkRepository;
+    @Mock
+    private MobileNetworkRepository.MobileNetworkCallback mMobileNetworkCallback;
 
     private AddPreference mPreference;
     private Context mContext;
     private MobileNetworkSummaryController mController;
+    private LifecycleOwner mLifecycleOwner;
+    private Lifecycle mLifecycle;
 
     @Before
     public void setUp() {
@@ -89,13 +95,17 @@
         doReturn(mSubscriptionManager).when(mContext).getSystemService(SubscriptionManager.class);
         doReturn(mEuiccManager).when(mContext).getSystemService(EuiccManager.class);
         doReturn(mUserManager).when(mContext).getSystemService(UserManager.class);
+        mMobileNetworkRepository = new MobileNetworkRepository(mContext, mMobileNetworkCallback);
+        mLifecycleOwner = () -> mLifecycle;
+        mLifecycle = new Lifecycle(mLifecycleOwner);
+        mMobileNetworkRepository.addRegister(mLifecycleOwner);
 
         when(mTelephonyManager.getNetworkCountryIso()).thenReturn("");
         when(mSubscriptionManager.isActiveSubscriptionId(anyInt())).thenReturn(true);
         when(mEuiccManager.isEnabled()).thenReturn(true);
         Settings.Global.putInt(mContext.getContentResolver(), Settings.Global.EUICC_PROVISIONED, 1);
 
-        mController = new MobileNetworkSummaryController(mContext, mLifecycle);
+        mController = new MobileNetworkSummaryController(mContext, mLifecycle, mLifecycleOwner);
         mPreference = spy(new AddPreference(mContext, null));
         mPreference.setKey(mController.getPreferenceKey());
         when(mPreferenceScreen.findPreference(eq(mController.getPreferenceKey()))).thenReturn(
@@ -104,6 +114,7 @@
 
     @After
     public void tearDown() {
+        mMobileNetworkRepository.removeRegister();
         SubscriptionUtil.setActiveSubscriptionsForTesting(null);
         SubscriptionUtil.setAvailableSubscriptionsForTesting(null);
     }