Avoid same pending intent to be used multiple times

Avoid same pending intent to be used multiple times to avoid
receiving intent with previous subId

Bug: 136202259
Bug: 136589116

Test: Verified that manual test passes and unit test also

ONSTests (20 Tests)
------------------
[1/20] com.android.ons.ONSNetworkScanCtlrTest#testStartFastNetworkScan: PASSED (177ms)
[2/20] com.android.ons.ONSNetworkScanCtlrTest#testStartFastNetworkScanFail: PASSED (26ms)
[3/20] com.android.ons.ONSNetworkScanCtlrTest#testStartFastNetworkScanWithMultipleNetworks: PASSED (0ms)
[4/20] com.android.ons.ONSNetworkScanCtlrTest#testStopNetworkScan: PASSED (102ms)
[5/20] com.android.ons.ONSProfileSelectorTest#testStartProfileSelectionSuccess: PASSED (554ms)
[6/20] com.android.ons.ONSProfileSelectorTest#testStartProfileSelectionSuccessWithSameArgumentsAgain: PASSED (1.057s)
[7/20] com.android.ons.ONSProfileSelectorTest#testStartProfileSelectionWithActivePrimarySimOnESim: PASSED (5.155s)
[8/20] com.android.ons.ONSProfileSelectorTest#testStartProfileSelectionWithNoOpportunisticSub: PASSED (151ms)
[9/20] com.android.ons.ONSProfileSelectorTest#testselectProfileForDataWithInActiveSub: PASSED (51ms)
[10/20] com.android.ons.ONSProfileSelectorTest#testselectProfileForDataWithInvalidSubId: PASSED (26ms)
[11/20] com.android.ons.ONSProfileSelectorTest#testselectProfileForDataWithNoOpportunsticSub: PASSED (26ms)
[12/20] com.android.ons.ONSProfileSelectorTest#testselectProfileForDataWithValidSub: PASSED (51ms)
[13/20] com.android.ons.OpportunisticNetworkServiceTest#testGetPreferredDataSubscriptionId: PASSED (529ms)
[14/20] com.android.ons.OpportunisticNetworkServiceTest#testSetPreferredDataSubscriptionId: PASSED (26ms)
[15/20] com.android.ons.OpportunisticNetworkServiceTest#testSystemPreferredDataWhileCarrierAppIsActive: PASSED (51ms)
[16/20] com.android.ons.OpportunisticNetworkServiceTest#testCheckEnable: PASSED (26ms)
[17/20] com.android.ons.OpportunisticNetworkServiceTest#testHandleSimStateChange: PASSED (604ms)
[18/20] com.android.ons.OpportunisticNetworkServiceTest#testUpdateAvailableNetworksWithSuccess: PASSED (26ms)
[19/20] com.android.ons.OpportunisticNetworkServiceTest#testUpdateAvailableNetworksWithSameArgumenAsPrevious: PASSED (126ms)
[20/20] com.android.ons.OpportunisticNetworkServiceTest#testUpdateAvailableNetworksWithInvalidArguments: PASSED (26ms)

Change-Id: I42428e7c6ffa32cdd764094388a0d39aaf583e81
diff --git a/src/com/android/ons/ONSProfileSelector.java b/src/com/android/ons/ONSProfileSelector.java
index 1922514..55173c5 100644
--- a/src/com/android/ons/ONSProfileSelector.java
+++ b/src/com/android/ons/ONSProfileSelector.java
@@ -117,7 +117,9 @@
                     if (subId == SubscriptionManager.INVALID_SUBSCRIPTION_ID) {
                         sendUpdateNetworksCallbackHelper(mNetworkScanCallback,
                                 TelephonyManager.UPDATE_AVAILABLE_NETWORKS_INVALID_ARGUMENTS);
-                        mNetworkScanCallback = null;
+                        synchronized (mLock) {
+                            mNetworkScanCallback = null;
+                        }
                         return;
                     }
 
@@ -129,14 +131,16 @@
                 @Override
                 public void onError(int error) {
                     log("Network scan failed with error " + error);
-                    if (mIsEnabled && mAvailableNetworkInfos != null
+                    synchronized (mLock) {
+                        if (mIsEnabled && mAvailableNetworkInfos != null
                             && mAvailableNetworkInfos.size() > 0) {
-                        handleNetworkScanResult(mAvailableNetworkInfos.get(0).getSubId());
-                    } else {
-                        if (mNetworkScanCallback != null) {
-                            sendUpdateNetworksCallbackHelper(mNetworkScanCallback,
+                            handleNetworkScanResult(mAvailableNetworkInfos.get(0).getSubId());
+                        } else {
+                            if (mNetworkScanCallback != null) {
+                                sendUpdateNetworksCallbackHelper(mNetworkScanCallback,
                                     TelephonyManager.UPDATE_AVAILABLE_NETWORKS_INVALID_ARGUMENTS);
-                            mNetworkScanCallback = null;
+                                mNetworkScanCallback = null;
+                            }
                         }
                     }
                 }
@@ -152,7 +156,10 @@
                                 TelephonyManager.UPDATE_AVAILABLE_NETWORKS_ABORTED);
                         }
                         mProfileSelectionCallback.onProfileSelectionDone();
-                        mNetworkScanCallback = null;
+                        synchronized (mLock) {
+                            mNetworkScanCallback = null;
+                            mAvailableNetworkInfos = null;
+                        }
                     } else {
                         logDebug("switch to sub:" + subId);
                         switchToSubscription(subId);
@@ -247,13 +254,17 @@
 
     private int getSubIdUsingAvailableNetworks(String mcc, String mnc, int priorityLevel) {
         String mccMnc = mcc + mnc;
-        for (AvailableNetworkInfo availableNetworkInfo : mAvailableNetworkInfos) {
-            if (availableNetworkInfo.getPriority() != priorityLevel) {
-                continue;
-            }
-            for (String availableMccMnc : availableNetworkInfo.getMccMncs()) {
-                if (TextUtils.equals(availableMccMnc, mccMnc)) {
-                    return availableNetworkInfo.getSubId();
+        synchronized (mLock) {
+            if (mAvailableNetworkInfos != null) {
+                for (AvailableNetworkInfo availableNetworkInfo : mAvailableNetworkInfos) {
+                    if (availableNetworkInfo.getPriority() != priorityLevel) {
+                        continue;
+                    }
+                    for (String availableMccMnc : availableNetworkInfo.getMccMncs()) {
+                        if (TextUtils.equals(availableMccMnc, mccMnc)) {
+                            return availableNetworkInfo.getSubId();
+                        }
+                    }
                 }
             }
         }
@@ -315,8 +326,7 @@
         callbackIntent.putExtra("subId", subId);
         mSubId = subId;
         PendingIntent replyIntent = PendingIntent.getService(mContext,
-                1, callbackIntent,
-                Intent.FILL_IN_ACTION);
+                1, callbackIntent, PendingIntent.FLAG_ONE_SHOT);
         mSubscriptionManager.switchToSubscription(subId, replyIntent);
     }
 
@@ -346,6 +356,8 @@
                 TelephonyManager.UPDATE_AVAILABLE_NETWORKS_ABORTED);
         }
         mProfileSelectionCallback.onProfileSelectionDone();
+        mNetworkScanCallback = null;
+        mAvailableNetworkInfos = null;
     }
 
     private void updateToken() {
@@ -453,6 +465,13 @@
         }
 
         if (isSame(availableNetworks, mAvailableNetworkInfos)) {
+            logDebug("received duplicate requests");
+            /* If we receive same request more than once, send abort response for earlier one
+               and send actual response for the latest callback.
+            */
+            sendUpdateNetworksCallbackHelper(mNetworkScanCallback,
+                TelephonyManager.UPDATE_AVAILABLE_NETWORKS_ABORTED);
+            mNetworkScanCallback = callbackStub;
             return;
         }
 
@@ -484,6 +503,7 @@
                             TelephonyManager.UPDATE_AVAILABLE_NETWORKS_ABORTED);
                     }
                     mProfileSelectionCallback.onProfileSelectionDone();
+                    mAvailableNetworkInfos = null;
                 }
             } else {
                 mNetworkScanCallback = callbackStub;
@@ -604,13 +624,14 @@
     }
 
     private void stopProfileScanningPrecedure() {
-        if (mNetworkScanCallback != null) {
-            sendUpdateNetworksCallbackHelper(mNetworkScanCallback,
-                    TelephonyManager.UPDATE_AVAILABLE_NETWORKS_ABORTED);
-            mNetworkScanCallback = null;
-        }
-        mNetworkScanCtlr.stopNetworkScan();
         synchronized (mLock) {
+            if (mNetworkScanCallback != null) {
+                sendUpdateNetworksCallbackHelper(mNetworkScanCallback,
+                        TelephonyManager.UPDATE_AVAILABLE_NETWORKS_ABORTED);
+                mNetworkScanCallback = null;
+            }
+            mNetworkScanCtlr.stopNetworkScan();
+
             mAvailableNetworkInfos = null;
             mIsEnabled = false;
         }
diff --git a/tests/src/com/android/ons/ONSProfileSelectorTest.java b/tests/src/com/android/ons/ONSProfileSelectorTest.java
index e43f78d..a3b5a72 100644
--- a/tests/src/com/android/ons/ONSProfileSelectorTest.java
+++ b/tests/src/com/android/ons/ONSProfileSelectorTest.java
@@ -42,6 +42,7 @@
 import java.util.List;
 
 public class ONSProfileSelectorTest extends ONSBaseTest {
+
     private MyONSProfileSelector mONSProfileSelector;
     private boolean testFailed;
     private boolean mCallbackInvoked;
@@ -55,20 +56,21 @@
     private static final String TAG = "ONSProfileSelectorTest";
 
     MyONSProfileSelector.ONSProfileSelectionCallback mONSProfileSelectionCallback =
-            new MyONSProfileSelector.ONSProfileSelectionCallback() {
-        public void onProfileSelectionDone() {
-            mCallbackInvoked = true;
-            setReady(true);
-        }
-    };
+        new MyONSProfileSelector.ONSProfileSelectionCallback() {
+            public void onProfileSelectionDone() {
+                mCallbackInvoked = true;
+                setReady(true);
+            }
+        };
 
     public class MyONSProfileSelector extends ONSProfileSelector {
+
         public SubscriptionManager.OnOpportunisticSubscriptionsChangedListener mProfileChngLstnrCpy;
         public BroadcastReceiver mProfileSelectorBroadcastReceiverCpy;
         public ONSNetworkScanCtlr.NetworkAvailableCallBack mNetworkAvailableCallBackCpy;
 
         public MyONSProfileSelector(Context c,
-                MyONSProfileSelector.ONSProfileSelectionCallback aNSProfileSelectionCallback) {
+            MyONSProfileSelector.ONSProfileSelectionCallback aNSProfileSelectionCallback) {
             super(c, aNSProfileSelectionCallback);
         }
 
@@ -81,7 +83,7 @@
         }
 
         protected void init(Context c,
-                MyONSProfileSelector.ONSProfileSelectionCallback aNSProfileSelectionCallback) {
+            MyONSProfileSelector.ONSProfileSelectionCallback aNSProfileSelectionCallback) {
             super.init(c, aNSProfileSelectionCallback);
             this.mSubscriptionManager = ONSProfileSelectorTest.this.mSubscriptionManager;
             this.mSubscriptionBoundTelephonyManager =
@@ -116,11 +118,11 @@
         CellIdentityLte cellIdentityLte = new CellIdentityLte(310, 210, 1, 1, 1);
         CellInfoLte cellInfoLte = new CellInfoLte();
         cellInfoLte.setCellIdentity(cellIdentityLte);
-        results2.add((CellInfo)cellInfoLte);
+        results2.add((CellInfo) cellInfoLte);
         ArrayList<String> mccMncs = new ArrayList<>();
         mccMncs.add("310210");
         AvailableNetworkInfo availableNetworkInfo = new AvailableNetworkInfo(1, 1, mccMncs,
-                new ArrayList<Integer>());
+            new ArrayList<Integer>());
         ArrayList<AvailableNetworkInfo> availableNetworkInfos = new ArrayList<AvailableNetworkInfo>();
         availableNetworkInfos.add(availableNetworkInfo);
 
@@ -141,9 +143,9 @@
                 Looper.prepare();
                 doReturn(true).when(mONSNetworkScanCtlr).startFastNetworkScan(anyObject());
                 doReturn(new ArrayList<>()).when(mSubscriptionManager)
-                        .getOpportunisticSubscriptions();
+                    .getOpportunisticSubscriptions();
                 mONSProfileSelector = new MyONSProfileSelector(mContext,
-                        mONSProfileSelectionCallback);
+                    mONSProfileSelectionCallback);
                 mONSProfileSelector.updateOppSubs();
                 mONSProfileSelector.startProfileSelection(availableNetworkInfos, mCallback);
                 mLooper = Looper.myLooper();
@@ -168,20 +170,20 @@
     public void testStartProfileSelectionSuccess() {
         List<SubscriptionInfo> subscriptionInfoList = new ArrayList<SubscriptionInfo>();
         SubscriptionInfo subscriptionInfo = new SubscriptionInfo(5, "", 1, "TMO", "TMO", 1, 1,
-                "123", 1, null, "310", "210", "", false, null, "1");
+            "123", 1, null, "310", "210", "", false, null, "1");
         SubscriptionInfo subscriptionInfo2 = new SubscriptionInfo(5, "", 1, "TMO", "TMO", 1, 1,
-                "123", 1, null, "310", "211", "", false, null, "1");
+            "123", 1, null, "310", "211", "", false, null, "1");
         subscriptionInfoList.add(subscriptionInfo);
 
         List<CellInfo> results2 = new ArrayList<CellInfo>();
         CellIdentityLte cellIdentityLte = new CellIdentityLte(310, 210, 1, 1, 1);
         CellInfoLte cellInfoLte = new CellInfoLte();
         cellInfoLte.setCellIdentity(cellIdentityLte);
-        results2.add((CellInfo)cellInfoLte);
+        results2.add((CellInfo) cellInfoLte);
         ArrayList<String> mccMncs = new ArrayList<>();
         mccMncs.add("310210");
         AvailableNetworkInfo availableNetworkInfo = new AvailableNetworkInfo(1, 1, mccMncs,
-                new ArrayList<Integer>());
+            new ArrayList<Integer>());
         ArrayList<AvailableNetworkInfo> availableNetworkInfos = new ArrayList<AvailableNetworkInfo>();
         availableNetworkInfos.add(availableNetworkInfo);
 
@@ -198,16 +200,17 @@
             @Override
             public void run() {
                 Looper.prepare();
-                doReturn(subscriptionInfoList).when(mSubscriptionManager).getOpportunisticSubscriptions();
+                doReturn(subscriptionInfoList).when(mSubscriptionManager)
+                    .getOpportunisticSubscriptions();
                 doReturn(true).when(mSubscriptionManager).isActiveSubId(anyInt());
                 doReturn(true).when(mSubscriptionBoundTelephonyManager).enableModemForSlot(
                     anyInt(), anyBoolean());
                 mONSProfileSelector = new MyONSProfileSelector(mContext,
-                        new MyONSProfileSelector.ONSProfileSelectionCallback() {
-                    public void onProfileSelectionDone() {
-                        setReady(true);
-                    }
-                });
+                    new MyONSProfileSelector.ONSProfileSelectionCallback() {
+                        public void onProfileSelectionDone() {
+                            setReady(true);
+                        }
+                    });
                 mONSProfileSelector.updateOppSubs();
                 mONSProfileSelector.startProfileSelection(availableNetworkInfos, mCallback);
                 mLooper = Looper.myLooper();
@@ -265,7 +268,8 @@
             @Override
             public void run() {
                 Looper.prepare();
-                doReturn(opportunisticSubscriptionInfoList).when(mSubscriptionManager).getOpportunisticSubscriptions();
+                doReturn(opportunisticSubscriptionInfoList).when(mSubscriptionManager)
+                    .getOpportunisticSubscriptions();
                 doReturn(false).when(mSubscriptionManager).isActiveSubId(anyInt());
                 doReturn(activeSubscriptionInfoList).when(mSubscriptionManager)
                     .getActiveSubscriptionInfoList(anyBoolean());
@@ -316,9 +320,10 @@
             public void run() {
                 Looper.prepare();
                 mONSProfileSelector = new MyONSProfileSelector(mContext,
-                        new MyONSProfileSelector.ONSProfileSelectionCallback() {
-                            public void onProfileSelectionDone() {}
-                        });
+                    new MyONSProfileSelector.ONSProfileSelectionCallback() {
+                        public void onProfileSelectionDone() {
+                        }
+                    });
                 mLooper = Looper.myLooper();
                 setReady(true);
                 Looper.loop();
@@ -337,7 +342,7 @@
     public void testselectProfileForDataWithInActiveSub() {
         List<SubscriptionInfo> subscriptionInfoList = new ArrayList<SubscriptionInfo>();
         SubscriptionInfo subscriptionInfo = new SubscriptionInfo(5, "", 1, "TMO", "TMO", 1, 1,
-                "123", 1, null, "310", "210", "", false, null, "1");
+            "123", 1, null, "310", "210", "", false, null, "1");
         subscriptionInfoList.add(subscriptionInfo);
         mReady = false;
         doReturn(new ArrayList<>()).when(mSubscriptionManager).getOpportunisticSubscriptions();
@@ -346,9 +351,10 @@
             public void run() {
                 Looper.prepare();
                 mONSProfileSelector = new MyONSProfileSelector(mContext,
-                        new MyONSProfileSelector.ONSProfileSelectionCallback() {
-                            public void onProfileSelectionDone() {}
-                        });
+                    new MyONSProfileSelector.ONSProfileSelectionCallback() {
+                        public void onProfileSelectionDone() {
+                        }
+                    });
                 mLooper = Looper.myLooper();
                 setReady(true);
                 Looper.loop();
@@ -366,20 +372,21 @@
     public void testselectProfileForDataWithInvalidSubId() {
         List<SubscriptionInfo> subscriptionInfoList = new ArrayList<SubscriptionInfo>();
         SubscriptionInfo subscriptionInfo = new SubscriptionInfo(5, "", 1, "TMO", "TMO", 1, 1,
-                "123", 1, null, "310", "210", "", false, null, "1");
+            "123", 1, null, "310", "210", "", false, null, "1");
         subscriptionInfoList.add(subscriptionInfo);
         mReady = false;
         doReturn(subscriptionInfoList).when(mSubscriptionManager).getOpportunisticSubscriptions();
         doNothing().when(mSubscriptionManager).setPreferredDataSubscriptionId(
-                anyInt(), anyBoolean(), any(), any());
+            anyInt(), anyBoolean(), any(), any());
         new Thread(new Runnable() {
             @Override
             public void run() {
                 Looper.prepare();
                 mONSProfileSelector = new MyONSProfileSelector(mContext,
-                        new MyONSProfileSelector.ONSProfileSelectionCallback() {
-                            public void onProfileSelectionDone() {}
-                        });
+                    new MyONSProfileSelector.ONSProfileSelectionCallback() {
+                        public void onProfileSelectionDone() {
+                        }
+                    });
                 mLooper = Looper.myLooper();
                 setReady(true);
                 Looper.loop();
@@ -392,30 +399,31 @@
         // Testing selectProfileForData with INVALID_SUBSCRIPTION_ID and the function should
         // return true.
         mONSProfileSelector.selectProfileForData(
-                SubscriptionManager.INVALID_SUBSCRIPTION_ID, false, null);
+            SubscriptionManager.INVALID_SUBSCRIPTION_ID, false, null);
     }
 
     @Test
     public void testselectProfileForDataWithValidSub() {
         List<SubscriptionInfo> subscriptionInfoList = new ArrayList<SubscriptionInfo>();
         SubscriptionInfo subscriptionInfo = new SubscriptionInfo(5, "", 1, "TMO", "TMO", 1, 1,
-                "123", 1, null, "310", "210", "", false, null, "1");
+            "123", 1, null, "310", "210", "", false, null, "1");
         subscriptionInfoList.add(subscriptionInfo);
         mReady = false;
         doReturn(subscriptionInfoList).when(mSubscriptionManager)
-                .getActiveSubscriptionInfoList();
+            .getActiveSubscriptionInfoList();
         doNothing().when(mSubscriptionManager).setPreferredDataSubscriptionId(
-                anyInt(), anyBoolean(), any(), any());
+            anyInt(), anyBoolean(), any(), any());
         new Thread(new Runnable() {
             @Override
             public void run() {
                 Looper.prepare();
                 doReturn(subscriptionInfoList).when(mSubscriptionManager)
-                        .getOpportunisticSubscriptions();
+                    .getOpportunisticSubscriptions();
                 mONSProfileSelector = new MyONSProfileSelector(mContext,
-                        new MyONSProfileSelector.ONSProfileSelectionCallback() {
-                            public void onProfileSelectionDone() {}
-                        });
+                    new MyONSProfileSelector.ONSProfileSelectionCallback() {
+                        public void onProfileSelectionDone() {
+                        }
+                    });
                 mONSProfileSelector.updateOppSubs();
                 mLooper = Looper.myLooper();
                 setReady(true);
@@ -430,4 +438,109 @@
         // return true.
         mONSProfileSelector.selectProfileForData(5, false, null);
     }
+
+    @Test
+    public void testStartProfileSelectionSuccessWithSameArgumentsAgain() {
+        List<SubscriptionInfo> subscriptionInfoList = new ArrayList<SubscriptionInfo>();
+        SubscriptionInfo subscriptionInfo = new SubscriptionInfo(5, "", 1, "TMO", "TMO", 1, 1,
+            "123", 1, null, "310", "210", "", false, null, "1");
+        SubscriptionInfo subscriptionInfo2 = new SubscriptionInfo(5, "", 1, "TMO", "TMO", 1, 1,
+            "123", 1, null, "310", "211", "", false, null, "1");
+        subscriptionInfoList.add(subscriptionInfo);
+
+        List<CellInfo> results2 = new ArrayList<CellInfo>();
+        CellIdentityLte cellIdentityLte = new CellIdentityLte(310, 210, 1, 1, 1);
+        CellInfoLte cellInfoLte = new CellInfoLte();
+        cellInfoLte.setCellIdentity(cellIdentityLte);
+        results2.add((CellInfo) cellInfoLte);
+        ArrayList<String> mccMncs = new ArrayList<>();
+        mccMncs.add("310210");
+        AvailableNetworkInfo availableNetworkInfo = new AvailableNetworkInfo(1, 1, mccMncs,
+            new ArrayList<Integer>());
+        ArrayList<AvailableNetworkInfo> availableNetworkInfos = new ArrayList<AvailableNetworkInfo>();
+        availableNetworkInfos.add(availableNetworkInfo);
+
+        IUpdateAvailableNetworksCallback mCallback = new IUpdateAvailableNetworksCallback.Stub() {
+            @Override
+            public void onComplete(int result) {
+                mResult = result;
+            }
+        };
+
+        mResult = -1;
+        mReady = false;
+        mONSProfileSelector = new MyONSProfileSelector(mContext,
+            new MyONSProfileSelector.ONSProfileSelectionCallback() {
+                public void onProfileSelectionDone() {
+                    setReady(true);
+                }
+            });
+        new Thread(new Runnable() {
+            @Override
+            public void run() {
+                Looper.prepare();
+                doReturn(subscriptionInfoList).when(mSubscriptionManager)
+                    .getOpportunisticSubscriptions();
+                doReturn(true).when(mSubscriptionManager).isActiveSubId(anyInt());
+                doReturn(true).when(mSubscriptionBoundTelephonyManager).enableModemForSlot(
+                    anyInt(), anyBoolean());
+
+                mONSProfileSelector.updateOppSubs();
+                mONSProfileSelector.startProfileSelection(availableNetworkInfos, mCallback);
+                mLooper = Looper.myLooper();
+                setReady(true);
+                Looper.loop();
+            }
+        }).start();
+
+        // Wait till initialization is complete.
+        waitUntilReady();
+        mReady = false;
+        mDataSubId = -1;
+
+        // Testing startProfileSelection with oppotunistic sub.
+        // On success onProfileSelectionDone must get invoked.
+        assertFalse(mReady);
+        waitForMs(500);
+        mONSProfileSelector.mNetworkAvailableCallBackCpy.onNetworkAvailability(results2);
+        Intent callbackIntent = new Intent(MyONSProfileSelector.ACTION_SUB_SWITCH);
+        callbackIntent.putExtra("sequenceId", 1);
+        callbackIntent.putExtra("subId", 5);
+        waitUntilReady();
+        assertEquals(TelephonyManager.UPDATE_AVAILABLE_NETWORKS_SUCCESS, mResult);
+        assertTrue(mReady);
+
+        mResult = -1;
+        mReady = false;
+        new Thread(new Runnable() {
+            @Override
+            public void run() {
+                Looper.prepare();
+                doReturn(subscriptionInfoList).when(mSubscriptionManager)
+                    .getOpportunisticSubscriptions();
+                doReturn(true).when(mSubscriptionManager).isActiveSubId(anyInt());
+                doReturn(true).when(mSubscriptionBoundTelephonyManager).enableModemForSlot(
+                    anyInt(), anyBoolean());
+                mONSProfileSelector.updateOppSubs();
+                mONSProfileSelector.startProfileSelection(availableNetworkInfos, mCallback);
+                mLooper = Looper.myLooper();
+                setReady(true);
+                Looper.loop();
+            }
+        }).start();
+
+        // Wait till initialization is complete.
+        waitUntilReady();
+        mReady = false;
+        mDataSubId = -1;
+
+        // Testing startProfileSelection with oppotunistic sub.
+        // On success onProfileSelectionDone must get invoked.
+        assertFalse(mReady);
+        waitForMs(500);
+        mONSProfileSelector.mNetworkAvailableCallBackCpy.onNetworkAvailability(results2);
+        waitUntilReady();
+        assertEquals(TelephonyManager.UPDATE_AVAILABLE_NETWORKS_SUCCESS, mResult);
+        assertTrue(mReady);
+    }
 }
diff --git a/tests/src/com/android/ons/OpportunisticNetworkServiceTest.java b/tests/src/com/android/ons/OpportunisticNetworkServiceTest.java
index 88fbb7c..ae28862 100644
--- a/tests/src/com/android/ons/OpportunisticNetworkServiceTest.java
+++ b/tests/src/com/android/ons/OpportunisticNetworkServiceTest.java
@@ -1,4 +1,4 @@
-/*
+  /*
  * Copyright (C) 2019 The Android Open Source Project
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
@@ -148,7 +148,7 @@
         mOpportunisticNetworkService.mIsEnabled = true;
         mOpportunisticNetworkService.mONSConfigInputHashMap = mockONSConfigInputHashMap;
         mOpportunisticNetworkService.handleSimStateChange();
-        waitForMs(500);
+        waitForMs(50);
         verify(mockONSConfigInputHashMap,times(1)).get(SYSTEM_APP_CONFIG_NAME);
     }