Merge "Update TelephonyProvider to add group ID."
diff --git a/src/com/android/providers/telephony/CarrierIdProvider.java b/src/com/android/providers/telephony/CarrierIdProvider.java
index 5e090dd..6dfa07b 100644
--- a/src/com/android/providers/telephony/CarrierIdProvider.java
+++ b/src/com/android/providers/telephony/CarrierIdProvider.java
@@ -25,6 +25,7 @@
 import android.content.pm.PackageManager;
 import android.database.Cursor;
 import android.database.MatrixCursor;
+import android.database.SQLException;
 import android.database.sqlite.SQLiteDatabase;
 import android.database.sqlite.SQLiteOpenHelper;
 import android.database.sqlite.SQLiteQueryBuilder;
@@ -74,7 +75,7 @@
     private static final String TAG = CarrierIdProvider.class.getSimpleName();
 
     private static final String DATABASE_NAME = "carrierIdentification.db";
-    private static final int DATABASE_VERSION = 4;
+    private static final int DATABASE_VERSION = 5;
 
     private static final String ASSETS_PB_FILE = "carrier_list.pb";
     private static final String VERSION_KEY = "version";
@@ -145,7 +146,8 @@
             CarrierId.All.SPN,
             CarrierId.All.APN,
             CarrierId.All.ICCID_PREFIX,
-            CarrierId.All.PRIVILEGE_ACCESS_RULE));
+            CarrierId.All.PRIVILEGE_ACCESS_RULE,
+            CarrierId.PARENT_CARRIER_ID));
 
     private CarrierIdDatabaseHelper mDbHelper;
 
@@ -172,6 +174,7 @@
                 + CarrierId.All.PRIVILEGE_ACCESS_RULE + " TEXT,"
                 + CarrierId.CARRIER_NAME + " TEXT,"
                 + CarrierId.CARRIER_ID + " INTEGER DEFAULT -1,"
+                + CarrierId.PARENT_CARRIER_ID + " INTEGER DEFAULT -1,"
                 + "UNIQUE (" + TextUtils.join(", ", CARRIERS_ID_UNIQUE_FIELDS) + "));";
     }
 
@@ -325,6 +328,7 @@
          */
         public CarrierIdDatabaseHelper(Context context) {
             super(context, DATABASE_NAME, null, DATABASE_VERSION);
+            Log.d(TAG, "CarrierIdDatabaseHelper: " + DATABASE_VERSION);
             setWriteAheadLoggingEnabled(false);
         }
 
@@ -350,6 +354,9 @@
             if (oldVersion < DATABASE_VERSION) {
                 dropCarrierTable(db);
                 createCarrierTable(db);
+                // force rewrite carrier id db
+                setAppliedVersion(0);
+                updateDatabaseFromPb(db);
             }
         }
     }
@@ -412,7 +419,9 @@
     private void convertCarrierAttrToContentValues(ContentValues cv, List<ContentValues> cvs,
             CarrierIdProto.CarrierAttribute attr, int index) {
         if (index > CARRIER_ATTR_END_IDX) {
-            cvs.add(new ContentValues(cv));
+            ContentValues carrier = new ContentValues(cv);
+            if (!cvs.contains(carrier))
+            cvs.add(carrier);
             return;
         }
         boolean found = false;
@@ -435,7 +444,7 @@
                 break;
             case GID1_INDEX:
                 for (String str : attr.gid1) {
-                    cv.put(CarrierId.All.GID1, str);
+                    cv.put(CarrierId.All.GID1, str.toLowerCase());
                     convertCarrierAttrToContentValues(cv, cvs, attr, index + 1);
                     cv.remove(CarrierId.All.GID1);
                     found = true;
@@ -443,7 +452,7 @@
                 break;
             case GID2_INDEX:
                 for (String str : attr.gid2) {
-                    cv.put(CarrierId.All.GID2, str);
+                    cv.put(CarrierId.All.GID2, str.toLowerCase());
                     convertCarrierAttrToContentValues(cv, cvs, attr, index + 1);
                     cv.remove(CarrierId.All.GID2);
                     found = true;
@@ -459,7 +468,7 @@
                 break;
             case SPN_INDEX:
                 for (String str : attr.spn) {
-                    cv.put(CarrierId.All.SPN, str);
+                    cv.put(CarrierId.All.SPN, str.toLowerCase());
                     convertCarrierAttrToContentValues(cv, cvs, attr, index + 1);
                     cv.remove(CarrierId.All.SPN);
                     found = true;
diff --git a/src/com/android/providers/telephony/MmsSmsDatabaseHelper.java b/src/com/android/providers/telephony/MmsSmsDatabaseHelper.java
index 07fa377..fa823ff 100644
--- a/src/com/android/providers/telephony/MmsSmsDatabaseHelper.java
+++ b/src/com/android/providers/telephony/MmsSmsDatabaseHelper.java
@@ -24,6 +24,8 @@
 import android.content.SharedPreferences;
 import android.content.pm.PackageManager;
 import android.database.Cursor;
+import android.database.DatabaseErrorHandler;
+import android.database.DefaultDatabaseErrorHandler;
 import android.database.sqlite.SQLiteDatabase;
 import android.database.sqlite.SQLiteException;
 import android.database.sqlite.SQLiteOpenHelper;
@@ -240,6 +242,7 @@
 
     private static MmsSmsDatabaseHelper sDeInstance = null;
     private static MmsSmsDatabaseHelper sCeInstance = null;
+    private static MmsSmsDatabaseErrorHandler sDbErrorHandler = null;
 
     private static final String[] BIND_ARGS_NONE = new String[0];
 
@@ -259,12 +262,34 @@
     // cache for INITIAL_CREATE_DONE shared pref so access to it can be avoided when possible
     private static AtomicBoolean sInitialCreateDone = new AtomicBoolean(false);
 
-    private MmsSmsDatabaseHelper(Context context) {
-        super(context, DATABASE_NAME, null, DATABASE_VERSION);
+    /**
+     * The primary purpose of this DatabaseErrorHandler is to broadcast an intent on corruption and
+     * print a Slog.wtf so database corruption can be caught earlier.
+     */
+    private static class MmsSmsDatabaseErrorHandler implements DatabaseErrorHandler {
+        private DefaultDatabaseErrorHandler mDefaultDatabaseErrorHandler
+                = new DefaultDatabaseErrorHandler();
+        private Context mContext;
+
+        MmsSmsDatabaseErrorHandler(Context context) {
+            mContext = context;
+        }
+
+        @Override
+        public void onCorruption(SQLiteDatabase dbObj) {
+            String logMsg = "Corruption reported by sqlite on database: " + dbObj.getPath();
+            localLogWtf(logMsg);
+            sendDbLostIntent(mContext, true);
+            // Let the default error handler take other actions
+            mDefaultDatabaseErrorHandler.onCorruption(dbObj);
+        }
+    }
+
+    private MmsSmsDatabaseHelper(Context context, MmsSmsDatabaseErrorHandler dbErrorHandler) {
+        super(context, DATABASE_NAME, null, DATABASE_VERSION, dbErrorHandler);
         mContext = context;
         // Memory optimization - close idle connections after 30s of inactivity
         setIdleConnectionTimeout(IDLE_CONNECTION_TIMEOUT_MS);
-        setWriteAheadLoggingEnabled(false);
         try {
             PhoneFactory.addLocalLog(TAG, 100);
         } catch (IllegalArgumentException e) {
@@ -272,12 +297,27 @@
         }
     }
 
+    private static synchronized MmsSmsDatabaseErrorHandler getDbErrorHandler(Context context) {
+        if (sDbErrorHandler == null) {
+            sDbErrorHandler = new MmsSmsDatabaseErrorHandler(context);
+        }
+        return sDbErrorHandler;
+    }
+
+    private static void sendDbLostIntent(Context context, boolean isCorrupted) {
+        // Broadcast ACTION_SMS_MMS_DB_LOST
+        Intent intent = new Intent(Sms.Intents.ACTION_SMS_MMS_DB_LOST);
+        intent.putExtra(Sms.Intents.EXTRA_IS_CORRUPTED, isCorrupted);
+        intent.addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
+        context.sendBroadcast(intent, android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE);
+    }
     /**
      * Returns a singleton helper for the combined MMS and SMS database in device encrypted storage.
      */
     /* package */ static synchronized MmsSmsDatabaseHelper getInstanceForDe(Context context) {
         if (sDeInstance == null) {
-            sDeInstance = new MmsSmsDatabaseHelper(ProviderUtil.getDeviceEncryptedContext(context));
+            Context deContext = ProviderUtil.getDeviceEncryptedContext(context);
+            sDeInstance = new MmsSmsDatabaseHelper(deContext, getDbErrorHandler(deContext));
         }
         return sDeInstance;
     }
@@ -289,8 +329,8 @@
     /* package */ static synchronized MmsSmsDatabaseHelper getInstanceForCe(Context context) {
         if (sCeInstance == null) {
             if (StorageManager.isFileEncryptedNativeOrEmulated()) {
-                sCeInstance = new MmsSmsDatabaseHelper(
-                    ProviderUtil.getCredentialEncryptedContext(context));
+                Context ceContext = ProviderUtil.getCredentialEncryptedContext(context);
+                sCeInstance = new MmsSmsDatabaseHelper(ceContext, getDbErrorHandler(ceContext));
             } else {
                 sCeInstance = getInstanceForDe(context);
             }
@@ -495,6 +535,7 @@
                 // disappeared mysteriously?
                 localLogWtf("onCreate: was already called once earlier");
                 intent.putExtra(Intents.EXTRA_IS_INITIAL_CREATE, false);
+                sendDbLostIntent(mContext, false);
             } else {
                 setInitialCreateDone();
                 intent.putExtra(Intents.EXTRA_IS_INITIAL_CREATE, true);
@@ -511,12 +552,12 @@
         createIndices(db);
     }
 
-    private void localLog(String logMsg) {
+    private static void localLog(String logMsg) {
         Log.d(TAG, logMsg);
         PhoneFactory.localLog(TAG, logMsg);
     }
 
-    private void localLogWtf(String logMsg) {
+    private static void localLogWtf(String logMsg) {
         Slog.wtf(TAG, logMsg);
         PhoneFactory.localLog(TAG, logMsg);
     }
diff --git a/src/com/android/providers/telephony/TelephonyProvider.java b/src/com/android/providers/telephony/TelephonyProvider.java
index 2d13222..a165784 100644
--- a/src/com/android/providers/telephony/TelephonyProvider.java
+++ b/src/com/android/providers/telephony/TelephonyProvider.java
@@ -47,8 +47,8 @@
 import static android.provider.Telephony.Carriers.NO_SET_SET;
 import static android.provider.Telephony.Carriers.NUMERIC;
 import static android.provider.Telephony.Carriers.OWNED_BY;
-import static android.provider.Telephony.Carriers.OWNED_BY_OTHERS;
 import static android.provider.Telephony.Carriers.OWNED_BY_DPC;
+import static android.provider.Telephony.Carriers.OWNED_BY_OTHERS;
 import static android.provider.Telephony.Carriers.PASSWORD;
 import static android.provider.Telephony.Carriers.PORT;
 import static android.provider.Telephony.Carriers.PROFILE_ID;
@@ -133,8 +133,8 @@
 import java.util.List;
 import java.util.Locale;
 import java.util.Map;
-import java.util.zip.CRC32;
 import java.util.Set;
+import java.util.zip.CRC32;
 
 public class TelephonyProvider extends ContentProvider
 {
@@ -167,7 +167,8 @@
     private static final int URL_ENFORCE_MANAGED = 20;
     private static final int URL_PREFERAPNSET = 21;
     private static final int URL_PREFERAPNSET_USING_SUBID = 22;
-
+    private static final int URL_SIM_APN_LIST = 23;
+    private static final int URL_SIM_APN_LIST_ID = 24;
 
     private static final String TAG = "TelephonyProvider";
     private static final String CARRIERS_TABLE = "carriers";
@@ -419,6 +420,8 @@
         s_urlMatcher.addURI("telephony", "carriers/filtered/#", URL_FILTERED_ID);
         // Only Called by DevicePolicyManager to enforce DPC records.
         s_urlMatcher.addURI("telephony", "carriers/enforce_managed", URL_ENFORCE_MANAGED);
+        s_urlMatcher.addURI("telephony", "carriers/sim_apn_list", URL_SIM_APN_LIST);
+        s_urlMatcher.addURI("telephony", "carriers/sim_apn_list/#", URL_SIM_APN_LIST_ID);
 
         s_currentNullMap = new ContentValues(1);
         s_currentNullMap.put(CURRENT, "0");
@@ -2697,6 +2700,19 @@
                 qb.setTables(SIMINFO_TABLE);
                 break;
             }
+            case URL_SIM_APN_LIST_ID: {
+                subIdString = url.getLastPathSegment();
+                try {
+                    subId = Integer.parseInt(subIdString);
+                } catch (NumberFormatException e) {
+                    loge("NumberFormatException" + e);
+                    return null;
+                }
+            }
+            //intentional fall through from above case
+            case URL_SIM_APN_LIST: {
+                return getSubscriptionMatchingAPNList(qb, projectionIn, sort, subId);
+            }
 
             default: {
                 return null;
@@ -2755,6 +2771,92 @@
         return ret;
     }
 
+    /**
+     * To find the current sim APN.
+     *
+     * There has three steps:
+     * 1. Query the APN based on carrier ID and fall back to query { MCC, MNC, MVNO }.
+     * 2. If can't find the current APN, then query the parent APN. Query based on
+     *    MNO carrier id and { MCC, MNC }.
+     * 3. else return empty cursor
+     *
+     */
+    private Cursor getSubscriptionMatchingAPNList(SQLiteQueryBuilder qb, String[] projectionIn,
+            String sort, int subId) {
+
+        Cursor ret;
+        final TelephonyManager tm = ((TelephonyManager)
+                getContext().getSystemService(Context.TELEPHONY_SERVICE))
+                .createForSubscriptionId(subId);
+        SQLiteDatabase db = getReadableDatabase();
+
+        // For query db one time, append step 1 and step 2 condition in one selection and
+        // separate results after the query is completed. Because IMSI has special match rule,
+        // so just query the MCC / MNC and filter the MVNO by ourselves
+        String carrierIDSelection = CARRIER_ID + " =? OR " + NUMERIC + " =? OR "
+                + CARRIER_ID + " =? ";
+
+
+        String mccmnc = tm.getSimOperator();
+        String carrierId = String.valueOf(tm.getSimCarrierId());
+        String mnoCarrierId = String.valueOf(tm.getSimMNOCarrierId());
+
+        ret = qb.query(db, null, carrierIDSelection,
+                new String[]{carrierId, mccmnc, mnoCarrierId}, null, null, sort);
+
+        if (DBG) log("match current APN size:  " + ret.getCount());
+
+        MatrixCursor currentCursor = new MatrixCursor(projectionIn);
+        MatrixCursor parentCursor = new MatrixCursor(projectionIn);
+
+        int carrierIdIndex = ret.getColumnIndex(CARRIER_ID);
+        int numericIndex = ret.getColumnIndex(NUMERIC);
+        int mvnoIndex = ret.getColumnIndex(MVNO_TYPE);
+        int mvnoDataIndex = ret.getColumnIndex(MVNO_MATCH_DATA);
+
+        IccRecords iccRecords = getIccRecords(subId);
+
+        //Separate the result into MatrixCursor
+        while (ret.moveToNext()) {
+            List<String> data = new ArrayList<>();
+            for (String column : projectionIn) {
+                data.add(ret.getString(ret.getColumnIndex(column)));
+            }
+
+            if (ret.getString(carrierIdIndex).equals(carrierId)) {
+                // 1. APN query result based on SIM carrier id
+                currentCursor.addRow(data);
+            } else if (!TextUtils.isEmpty(ret.getString(numericIndex)) &&
+                    ApnSettingUtils.mvnoMatches(iccRecords,
+                            ApnSetting.getMvnoTypeIntFromString(ret.getString(mvnoIndex)),
+                            ret.getString(mvnoDataIndex))) {
+                // 1. APN query result based on legacy SIM MCC/MCC and MVNO in case APN carrier id
+                // migration is not 100%. some APNSettings can not find match id.
+                // TODO: remove legacy {mcc,mnc, mvno} support in the future.
+                currentCursor.addRow(data);
+            } else if (ret.getString(carrierIdIndex).equals(mnoCarrierId)) {
+                // 2. APN query result based on SIM MNO carrier id in case no APN found from
+                // exact carrier id fallback to query the MNO carrier id
+                parentCursor.addRow(data);
+            } else if (!TextUtils.isEmpty(ret.getString(numericIndex))) {
+                // 2. APN query result based on SIM MCC/MNC
+                // TODO: remove legacy {mcc, mnc} support in the future.
+                parentCursor.addRow(data);
+            }
+        }
+
+        if (currentCursor.getCount() > 0) {
+            if (DBG) log("match Carrier Id APN: " + currentCursor.getCount());
+            return currentCursor;
+        } else if (parentCursor.getCount() > 0) {
+            if (DBG) log("match MNO Carrier ID APN: " + parentCursor.getCount());
+            return parentCursor;
+        } else {
+            if (DBG) log("APN no match");
+            return new MatrixCursor(projectionIn);
+        }
+    }
+
     @Override
     public String getType(Uri url)
     {
@@ -3356,14 +3458,10 @@
         }
 
         if (count > 0) {
-            Uri wfcNotifyUri = SubscriptionManager.WFC_ENABLED_CONTENT_URI;
-            Uri enhanced4GNotifyUri = SubscriptionManager.ENHANCED_4G_ENABLED_CONTENT_URI;
+            boolean usingSubId = false;
             switch (uriType) {
                 case URL_SIMINFO_USING_SUBID:
-                    wfcNotifyUri = Uri.withAppendedPath(
-                            SubscriptionManager.WFC_ENABLED_CONTENT_URI, "" + subId);
-                    enhanced4GNotifyUri = Uri.withAppendedPath(
-                            SubscriptionManager.ENHANCED_4G_ENABLED_CONTENT_URI, "" + subId);
+                    usingSubId = true;
                     // intentional fall through from above case
                 case URL_SIMINFO:
                     // skip notifying descendant URLs to avoid unneccessary wake up.
@@ -3377,11 +3475,34 @@
                     // notify observers on specific user settings changes.
                     if (values.containsKey(SubscriptionManager.WFC_IMS_ENABLED)) {
                         getContext().getContentResolver().notifyChange(
-                                wfcNotifyUri, null, true, UserHandle.USER_ALL);
+                                getNotifyContentUri(SubscriptionManager.WFC_ENABLED_CONTENT_URI,
+                                        usingSubId, subId), null, true, UserHandle.USER_ALL);
                     }
                     if (values.containsKey(SubscriptionManager.ENHANCED_4G_MODE_ENABLED)) {
                         getContext().getContentResolver().notifyChange(
-                                enhanced4GNotifyUri, null, true, UserHandle.USER_ALL);
+                                getNotifyContentUri(SubscriptionManager
+                                                .ADVANCED_CALLING_ENABLED_CONTENT_URI,
+                                        usingSubId, subId), null, true, UserHandle.USER_ALL);
+                    }
+                    if (values.containsKey(SubscriptionManager.VT_IMS_ENABLED)) {
+                        getContext().getContentResolver().notifyChange(
+                                getNotifyContentUri(SubscriptionManager.VT_ENABLED_CONTENT_URI,
+                                        usingSubId, subId), null, true, UserHandle.USER_ALL);
+                    }
+                    if (values.containsKey(SubscriptionManager.WFC_IMS_MODE)) {
+                        getContext().getContentResolver().notifyChange(
+                                getNotifyContentUri(SubscriptionManager.WFC_MODE_CONTENT_URI,
+                                        usingSubId, subId), null, true, UserHandle.USER_ALL);
+                    }
+                    if (values.containsKey(SubscriptionManager.WFC_IMS_ROAMING_MODE)) {
+                        getContext().getContentResolver().notifyChange(getNotifyContentUri(
+                                SubscriptionManager.WFC_ROAMING_MODE_CONTENT_URI,
+                                usingSubId, subId), null, true, UserHandle.USER_ALL);
+                    }
+                    if (values.containsKey(SubscriptionManager.WFC_IMS_ROAMING_ENABLED)) {
+                        getContext().getContentResolver().notifyChange(getNotifyContentUri(
+                                SubscriptionManager.WFC_ROAMING_ENABLED_CONTENT_URI,
+                                usingSubId, subId), null, true, UserHandle.USER_ALL);
                     }
                     break;
                 default:
@@ -3393,6 +3514,10 @@
         return count;
     }
 
+    private static Uri getNotifyContentUri(Uri uri, boolean usingSubId, int subId) {
+        return (usingSubId) ? Uri.withAppendedPath(uri, "" + subId) : uri;
+    }
+
     private void checkPermission() {
         int status = getContext().checkCallingOrSelfPermission(
                 "android.permission.WRITE_APN_SETTINGS");
diff --git a/tests/src/com/android/providers/telephony/TelephonyProviderTest.java b/tests/src/com/android/providers/telephony/TelephonyProviderTest.java
index 715f3dd..cf4409a 100644
--- a/tests/src/com/android/providers/telephony/TelephonyProviderTest.java
+++ b/tests/src/com/android/providers/telephony/TelephonyProviderTest.java
@@ -40,7 +40,6 @@
 import android.test.mock.MockContentResolver;
 import android.test.mock.MockContext;
 import android.test.suitebuilder.annotation.SmallTest;
-import android.text.TextUtils;
 import android.util.Log;
 
 import junit.framework.TestCase;
@@ -80,6 +79,7 @@
     private static final String TEST_OPERATOR = "123456";
     private static final String TEST_MCC = "123";
     private static final String TEST_MNC = "456";
+
     // Used to test the path for URL_TELEPHONY_USING_SUBID with subid 1
     private static final Uri CONTENT_URI_WITH_SUBID = Uri.parse(
             "content://telephony/carriers/subId/" + TEST_SUBID);
@@ -92,6 +92,8 @@
             "content://telephony/carriers/preferapn/subId/" + TEST_SUBID);
     private static final Uri URL_WFC_ENABLED_USING_SUBID = Uri.parse(
             "content://telephony/siminfo/" + TEST_SUBID);
+    private static final Uri URL_SIM_APN_LIST = Uri.parse(
+        "content://telephony/carriers/sim_apn_list");
 
     private static final String COLUMN_APN_ID = "apn_id";
 
@@ -1439,4 +1441,167 @@
         assertEquals(1, notifyWfcCount);
         assertEquals(0, notifyWfcCountWithTestSubId);
     }
+
+    @Test
+    @SmallTest
+    public void testGetCurrentAPNList_APNMatchTheCarrierID() {
+        // Test on getCurrentAPNList() step 1
+        TelephonyManager telephonyManager =
+                ((TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE));
+        doReturn(telephonyManager).when(telephonyManager).createForSubscriptionId(anyInt());
+
+        final String apnName = "apnName";
+        final String carrierName = "name";
+        final int carrierID = 100;
+        final String numeric = TEST_OPERATOR;
+        doReturn(carrierID).when(telephonyManager).getSimCarrierId();
+        doReturn(numeric).when(telephonyManager).getSimOperator();
+
+        // Insert the APN
+        ContentValues contentValues = new ContentValues();
+        contentValues.put(Carriers.APN, apnName);
+        contentValues.put(Carriers.NAME, carrierName);
+        contentValues.put(Carriers.CARRIER_ID, carrierID);
+        mContentResolver.insert(Carriers.CONTENT_URI, contentValues);
+
+        final String[] testProjection =
+            {
+                Carriers.APN,
+                Carriers.NAME,
+                Carriers.CARRIER_ID,
+            };
+        Cursor cursor = mContentResolver.query(URL_SIM_APN_LIST,
+            testProjection, null, null, null);
+
+        cursor.moveToFirst();
+        assertEquals(apnName, cursor.getString(0));
+        assertEquals(carrierName, cursor.getString(1));
+        assertEquals(String.valueOf(carrierID), cursor.getString(2));
+    }
+
+    @Test
+    @SmallTest
+    public void testGetCurrentAPNList_APNMatchTheMCCMNCAndMVNO() {
+        // Test on getCurrentAPNList() step 2
+        TelephonyManager telephonyManager =
+                ((TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE));
+        doReturn(telephonyManager).when(telephonyManager).createForSubscriptionId(anyInt());
+
+        final String apnName = "apnName";
+        final String carrierName = "name";
+        final String numeric = TEST_OPERATOR;
+        final String mvnoType = "spn";
+        final String mvnoData = TelephonyProviderTestable.TEST_SPN;
+        final int carrierId = 100;
+        doReturn(carrierId).when(telephonyManager).getSimCarrierId();
+        doReturn(numeric).when(telephonyManager).getSimOperator();
+        //TelephonyProviderTestable had mock iccreord
+
+        // The DB only have the MCC/MNC and MVNO APN
+        ContentValues contentValues = new ContentValues();
+        contentValues.put(Carriers.APN, apnName);
+        contentValues.put(Carriers.NAME, carrierName);
+        contentValues.put(Carriers.NUMERIC, numeric);
+        contentValues.put(Carriers.MVNO_TYPE, mvnoType);
+        contentValues.put(Carriers.MVNO_MATCH_DATA, mvnoData);
+        mContentResolver.insert(Carriers.CONTENT_URI, contentValues);
+
+        final String[] testProjection =
+            {
+                Carriers.APN,
+                Carriers.NAME,
+                Carriers.NUMERIC,
+                Carriers.MVNO_MATCH_DATA
+            };
+        Cursor cursor = mContentResolver.query(URL_SIM_APN_LIST,
+            testProjection, null, null, null);
+
+
+        cursor.moveToFirst();
+        assertEquals(apnName, cursor.getString(0));
+        assertEquals(carrierName, cursor.getString(1));
+        assertEquals(numeric, cursor.getString(2));
+        assertEquals(mvnoData, cursor.getString(3));
+    }
+
+    @Test
+    @SmallTest
+    public void testGetCurrentAPNList_APNMatchTheMNOCarrierID() {
+        // Test on getCurrentAPNList() step 3
+        TelephonyManager telephonyManager =
+                ((TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE));
+        doReturn(telephonyManager).when(telephonyManager).createForSubscriptionId(anyInt());
+
+        final String apnName = "apnName";
+        final String carrierName = "name";
+        final int carrierId = 100;
+        final int mnoCarrierId = 101;
+        final String numeric = TEST_OPERATOR;
+        doReturn(carrierId).when(telephonyManager).getSimCarrierId();
+        doReturn(mnoCarrierId).when(telephonyManager).getSimMNOCarrierId();
+        doReturn(numeric).when(telephonyManager).getSimOperator();
+
+        // The DB only have the MNO carrier id APN
+        ContentValues contentValues = new ContentValues();
+        contentValues.put(Carriers.APN, apnName);
+        contentValues.put(Carriers.NAME, carrierName);
+        contentValues.put(Carriers.CARRIER_ID, mnoCarrierId);
+        mContentResolver.insert(Carriers.CONTENT_URI, contentValues);
+
+        final String[] testProjection =
+            {
+                Carriers.APN,
+                Carriers.NAME,
+                Carriers.CARRIER_ID,
+            };
+        Cursor cursor = mContentResolver.query(URL_SIM_APN_LIST,
+            testProjection, null, null, null);
+
+        cursor.moveToFirst();
+        assertEquals(apnName, cursor.getString(0));
+        assertEquals(carrierName, cursor.getString(1));
+        assertEquals(String.valueOf(mnoCarrierId), cursor.getString(2));
+    }
+
+    @Test
+    @SmallTest
+    public void testGetCurrentAPNList_APNMatchTheParentMCCMNC() {
+        // Test on getCurrentAPNList() step 4
+        TelephonyManager telephonyManager =
+                ((TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE));
+        doReturn(telephonyManager).when(telephonyManager).createForSubscriptionId(anyInt());
+
+        final String apnName = "apnName";
+        final String carrierName = "name";
+        final String numeric = TEST_OPERATOR;
+        final String mvnoData = TelephonyProviderTestable.TEST_SPN;
+        final int carrierId = 100;
+        final int mnoCarrierId = 101;
+
+        doReturn(carrierId).when(telephonyManager).getSimCarrierId();
+        doReturn(numeric).when(telephonyManager).getSimOperator();
+        doReturn(mvnoData).when(telephonyManager).getSimOperatorName();
+        doReturn(mnoCarrierId).when(telephonyManager).getSimMNOCarrierId();
+
+        // The DB only have the MNO APN
+        ContentValues contentValues = new ContentValues();
+        contentValues.put(Carriers.APN, apnName);
+        contentValues.put(Carriers.NAME, carrierName);
+        contentValues.put(Carriers.NUMERIC, numeric);
+        mContentResolver.insert(Carriers.CONTENT_URI, contentValues);
+
+        final String[] testProjection =
+            {
+                Carriers.APN,
+                Carriers.NAME,
+                Carriers.NUMERIC,
+            };
+        Cursor cursor = mContentResolver.query(URL_SIM_APN_LIST,
+            testProjection, null, null, null);
+
+        cursor.moveToFirst();
+        assertEquals(apnName, cursor.getString(0));
+        assertEquals(carrierName, cursor.getString(1));
+        assertEquals(numeric, cursor.getString(2));
+    }
 }