Snap for 8564071 from 150ecf3f41853af1de320c17c042e87bc7c2a748 to mainline-sdkext-release

Change-Id: Ic05f40aa72e3f03ae1fb3d509f6d5c37558c77d7
diff --git a/Android.bp b/Android.bp
index 9da72a0..ef3c148 100644
--- a/Android.bp
+++ b/Android.bp
@@ -1,3 +1,8 @@
+package {
+    // See: http://go/android-license-faq
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_app {
     name: "CallLogBackup",
     // Only compile source java files in this apk.
diff --git a/AndroidManifest.xml b/AndroidManifest.xml
index 47e4640..e3f43a1 100644
--- a/AndroidManifest.xml
+++ b/AndroidManifest.xml
@@ -4,6 +4,7 @@
         android:sharedUserLabel="@string/sharedUserLabel">
 
     <uses-permission android:name="android.permission.QUERY_ALL_PACKAGES" />
+    <uses-permission android:name="com.android.voicemail.permission.READ_VOICEMAIL" />
 
     <application android:label="@string/app_label"
         android:allowBackup="true"
@@ -15,6 +16,7 @@
                 android:value="AEdPqrEAAAAIVhVYJjcc4bozis7qBfzzgREFk3nIkWGNc5VaRg" />
 
         <receiver android:name="CallLogChangeReceiver"
+                android:exported="true"
                 android:permission="android.permission.SEND_CALL_LOG_CHANGE">
             <!-- Sent when the call log changes.  We use it to trigger a backup request. -->
             <intent-filter>
diff --git a/MODULE_LICENSE_APACHE2 b/MODULE_LICENSE_APACHE2
deleted file mode 100644
index e69de29..0000000
--- a/MODULE_LICENSE_APACHE2
+++ /dev/null
diff --git a/NOTICE b/NOTICE
deleted file mode 100644
index a204d3c..0000000
--- a/NOTICE
+++ /dev/null
@@ -1,191 +0,0 @@
-
-   Copyright (c) 2015, 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.
-
-   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.
-
-
-                                 Apache License
-                           Version 2.0, January 2004
-                        http://www.apache.org/licenses/
-
-   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
-   1. Definitions.
-
-      "License" shall mean the terms and conditions for use, reproduction,
-      and distribution as defined by Sections 1 through 9 of this document.
-
-      "Licensor" shall mean the copyright owner or entity authorized by
-      the copyright owner that is granting the License.
-
-      "Legal Entity" shall mean the union of the acting entity and all
-      other entities that control, are controlled by, or are under common
-      control with that entity. For the purposes of this definition,
-      "control" means (i) the power, direct or indirect, to cause the
-      direction or management of such entity, whether by contract or
-      otherwise, or (ii) ownership of fifty percent (50%) or more of the
-      outstanding shares, or (iii) beneficial ownership of such entity.
-
-      "You" (or "Your") shall mean an individual or Legal Entity
-      exercising permissions granted by this License.
-
-      "Source" form shall mean the preferred form for making modifications,
-      including but not limited to software source code, documentation
-      source, and configuration files.
-
-      "Object" form shall mean any form resulting from mechanical
-      transformation or translation of a Source form, including but
-      not limited to compiled object code, generated documentation,
-      and conversions to other media types.
-
-      "Work" shall mean the work of authorship, whether in Source or
-      Object form, made available under the License, as indicated by a
-      copyright notice that is included in or attached to the work
-      (an example is provided in the Appendix below).
-
-      "Derivative Works" shall mean any work, whether in Source or Object
-      form, that is based on (or derived from) the Work and for which the
-      editorial revisions, annotations, elaborations, or other modifications
-      represent, as a whole, an original work of authorship. For the purposes
-      of this License, Derivative Works shall not include works that remain
-      separable from, or merely link (or bind by name) to the interfaces of,
-      the Work and Derivative Works thereof.
-
-      "Contribution" shall mean any work of authorship, including
-      the original version of the Work and any modifications or additions
-      to that Work or Derivative Works thereof, that is intentionally
-      submitted to Licensor for inclusion in the Work by the copyright owner
-      or by an individual or Legal Entity authorized to submit on behalf of
-      the copyright owner. For the purposes of this definition, "submitted"
-      means any form of electronic, verbal, or written communication sent
-      to the Licensor or its representatives, including but not limited to
-      communication on electronic mailing lists, source code control systems,
-      and issue tracking systems that are managed by, or on behalf of, the
-      Licensor for the purpose of discussing and improving the Work, but
-      excluding communication that is conspicuously marked or otherwise
-      designated in writing by the copyright owner as "Not a Contribution."
-
-      "Contributor" shall mean Licensor and any individual or Legal Entity
-      on behalf of whom a Contribution has been received by Licensor and
-      subsequently incorporated within the Work.
-
-   2. Grant of Copyright License. Subject to the terms and conditions of
-      this License, each Contributor hereby grants to You a perpetual,
-      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
-      copyright license to reproduce, prepare Derivative Works of,
-      publicly display, publicly perform, sublicense, and distribute the
-      Work and such Derivative Works in Source or Object form.
-
-   3. Grant of Patent License. Subject to the terms and conditions of
-      this License, each Contributor hereby grants to You a perpetual,
-      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
-      (except as stated in this section) patent license to make, have made,
-      use, offer to sell, sell, import, and otherwise transfer the Work,
-      where such license applies only to those patent claims licensable
-      by such Contributor that are necessarily infringed by their
-      Contribution(s) alone or by combination of their Contribution(s)
-      with the Work to which such Contribution(s) was submitted. If You
-      institute patent litigation against any entity (including a
-      cross-claim or counterclaim in a lawsuit) alleging that the Work
-      or a Contribution incorporated within the Work constitutes direct
-      or contributory patent infringement, then any patent licenses
-      granted to You under this License for that Work shall terminate
-      as of the date such litigation is filed.
-
-   4. Redistribution. You may reproduce and distribute copies of the
-      Work or Derivative Works thereof in any medium, with or without
-      modifications, and in Source or Object form, provided that You
-      meet the following conditions:
-
-      (a) You must give any other recipients of the Work or
-          Derivative Works a copy of this License; and
-
-      (b) You must cause any modified files to carry prominent notices
-          stating that You changed the files; and
-
-      (c) You must retain, in the Source form of any Derivative Works
-          that You distribute, all copyright, patent, trademark, and
-          attribution notices from the Source form of the Work,
-          excluding those notices that do not pertain to any part of
-          the Derivative Works; and
-
-      (d) If the Work includes a "NOTICE" text file as part of its
-          distribution, then any Derivative Works that You distribute must
-          include a readable copy of the attribution notices contained
-          within such NOTICE file, excluding those notices that do not
-          pertain to any part of the Derivative Works, in at least one
-          of the following places: within a NOTICE text file distributed
-          as part of the Derivative Works; within the Source form or
-          documentation, if provided along with the Derivative Works; or,
-          within a display generated by the Derivative Works, if and
-          wherever such third-party notices normally appear. The contents
-          of the NOTICE file are for informational purposes only and
-          do not modify the License. You may add Your own attribution
-          notices within Derivative Works that You distribute, alongside
-          or as an addendum to the NOTICE text from the Work, provided
-          that such additional attribution notices cannot be construed
-          as modifying the License.
-
-      You may add Your own copyright statement to Your modifications and
-      may provide additional or different license terms and conditions
-      for use, reproduction, or distribution of Your modifications, or
-      for any such Derivative Works as a whole, provided Your use,
-      reproduction, and distribution of the Work otherwise complies with
-      the conditions stated in this License.
-
-   5. Submission of Contributions. Unless You explicitly state otherwise,
-      any Contribution intentionally submitted for inclusion in the Work
-      by You to the Licensor shall be under the terms and conditions of
-      this License, without any additional terms or conditions.
-      Notwithstanding the above, nothing herein shall supersede or modify
-      the terms of any separate license agreement you may have executed
-      with Licensor regarding such Contributions.
-
-   6. Trademarks. This License does not grant permission to use the trade
-      names, trademarks, service marks, or product names of the Licensor,
-      except as required for reasonable and customary use in describing the
-      origin of the Work and reproducing the content of the NOTICE file.
-
-   7. Disclaimer of Warranty. Unless required by applicable law or
-      agreed to in writing, Licensor provides the Work (and each
-      Contributor provides its Contributions) on an "AS IS" BASIS,
-      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
-      implied, including, without limitation, any warranties or conditions
-      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
-      PARTICULAR PURPOSE. You are solely responsible for determining the
-      appropriateness of using or redistributing the Work and assume any
-      risks associated with Your exercise of permissions under this License.
-
-   8. Limitation of Liability. In no event and under no legal theory,
-      whether in tort (including negligence), contract, or otherwise,
-      unless required by applicable law (such as deliberate and grossly
-      negligent acts) or agreed to in writing, shall any Contributor be
-      liable to You for damages, including any direct, indirect, special,
-      incidental, or consequential damages of any character arising as a
-      result of this License or out of the use or inability to use the
-      Work (including but not limited to damages for loss of goodwill,
-      work stoppage, computer failure or malfunction, or any and all
-      other commercial damages or losses), even if such Contributor
-      has been advised of the possibility of such damages.
-
-   9. Accepting Warranty or Additional Liability. While redistributing
-      the Work or Derivative Works thereof, You may choose to offer,
-      and charge a fee for, acceptance of support, warranty, indemnity,
-      or other liability obligations and/or rights consistent with this
-      License. However, in accepting such obligations, You may act only
-      on Your own behalf and on Your sole responsibility, not on behalf
-      of any other Contributor, and only if You agree to indemnify,
-      defend, and hold each Contributor harmless for any liability
-      incurred by, or claims asserted against, such Contributor by reason
-      of your accepting any such warranty or additional liability.
-
-   END OF TERMS AND CONDITIONS
-
-
diff --git a/src/com/android/calllogbackup/CallLogBackupAgent.java b/src/com/android/calllogbackup/CallLogBackupAgent.java
index ca0613b..a64a373 100644
--- a/src/com/android/calllogbackup/CallLogBackupAgent.java
+++ b/src/com/android/calllogbackup/CallLogBackupAgent.java
@@ -16,18 +16,20 @@
 
 package com.android.calllogbackup;
 
+import static android.provider.CallLog.Calls.MISSED_REASON_NOT_MISSED;
+
 import android.app.backup.BackupAgent;
 import android.app.backup.BackupDataInput;
 import android.app.backup.BackupDataOutput;
 import android.content.ComponentName;
 import android.content.ContentResolver;
-import android.content.Context;
 import android.database.Cursor;
 import android.os.ParcelFileDescriptor;
 import android.provider.CallLog;
 import android.provider.CallLog.Calls;
-import android.provider.Settings;
 import android.telecom.PhoneAccountHandle;
+import android.telephony.SubscriptionInfo;
+import android.telephony.SubscriptionManager;
 import android.util.Log;
 
 import com.android.internal.annotations.VisibleForTesting;
@@ -45,6 +47,8 @@
 import java.io.IOException;
 import java.util.LinkedList;
 import java.util.List;
+import java.util.HashMap;
+import java.util.Map;
 import java.util.SortedSet;
 import java.util.TreeSet;
 
@@ -78,6 +82,8 @@
         int callBlockReason = Calls.BLOCK_REASON_NOT_BLOCKED;
         String callScreeningAppName = null;
         String callScreeningComponentName = null;
+        long missedReason = MISSED_REASON_NOT_MISSED;
+        int isPhoneAccountMigrationPending;
 
         @Override
         public String toString() {
@@ -102,11 +108,9 @@
 
     private static final String TAG = "CallLogBackupAgent";
 
-    private static final String USER_FULL_DATA_BACKUP_AWARE = "user_full_data_backup_aware";
-
     /** Current version of CallLogBackup. Used to track the backup format. */
     @VisibleForTesting
-    static final int VERSION = 1007;
+    static final int VERSION = 1009;
     /** Version indicating that there exists no previous backup entry. */
     @VisibleForTesting
     static final int VERSION_NO_PREVIOUS_STATE = 0;
@@ -117,6 +121,11 @@
 
     static final int END_OEM_DATA_MARKER = 0x60061E;
 
+    static final String TELEPHONY_PHONE_ACCOUNT_HANDLE_COMPONENT_NAME =
+            "com.android.phone/com.android.services.telephony.TelephonyConnectionService";
+
+    @VisibleForTesting
+    protected Map<Integer, String> mSubscriptionInfoMap;
 
     private static final String[] CALL_LOG_PROJECTION = new String[] {
         CallLog.Calls._ID,
@@ -137,21 +146,15 @@
         CallLog.Calls.ADD_FOR_ALL_USERS,
         CallLog.Calls.BLOCK_REASON,
         CallLog.Calls.CALL_SCREENING_APP_NAME,
-        CallLog.Calls.CALL_SCREENING_COMPONENT_NAME
+        CallLog.Calls.CALL_SCREENING_COMPONENT_NAME,
+        CallLog.Calls.MISSED_REASON,
+        CallLog.Calls.IS_PHONE_ACCOUNT_MIGRATION_PENDING
     };
 
     /** ${inheritDoc} */
     @Override
     public void onBackup(ParcelFileDescriptor oldStateDescriptor, BackupDataOutput data,
             ParcelFileDescriptor newStateDescriptor) throws IOException {
-
-        if (shouldPreventBackup(this)) {
-            if (isDebug()) {
-                Log.d(TAG, "Skipping onBackup");
-            }
-            return;
-        }
-
         // Get the list of the previous calls IDs which were backed up.
         DataInputStream dataInput = new DataInputStream(
                 new FileInputStream(oldStateDescriptor.getFileDescriptor()));
@@ -162,6 +165,20 @@
             dataInput.close();
         }
 
+        SubscriptionManager subscriptionManager = getBaseContext().getSystemService(
+                SubscriptionManager.class);
+        if (subscriptionManager != null) {
+            mSubscriptionInfoMap = new HashMap<>();
+            // Use getAllSubscirptionInfoList() to get the mapping between iccId and subId
+            // from the subscription database
+            List<SubscriptionInfo> subscriptionInfos = subscriptionManager
+                    .getAllSubscriptionInfoList();
+            for (SubscriptionInfo subscriptionInfo : subscriptionInfos) {
+                mSubscriptionInfoMap.put(
+                        subscriptionInfo.getSubscriptionId(), subscriptionInfo.getIccId());
+            }
+        }
+
         // Run the actual backup of data
         runBackup(state, data, getAllCallLogEntries());
 
@@ -230,7 +247,8 @@
         }
     }
 
-    private Iterable<Call> getAllCallLogEntries() {
+    @VisibleForTesting
+    Iterable<Call> getAllCallLogEntries() {
         List<Call> calls = new LinkedList<>();
 
         // We use the API here instead of querying ContactsDatabaseHelper directly because
@@ -264,13 +282,16 @@
                     ComponentName.unflattenFromString(call.accountComponentName), call.accountId);
         }
         boolean addForAllUsers = call.addForAllUsers == 1;
+
         // We backup the calllog in the user running this backup agent, so write calls to this user.
         Calls.addCall(null /* CallerInfo */, this, call.number, call.postDialDigits, call.viaNumber,
             call.numberPresentation, call.type, call.features, handle, call.date,
             (int) call.duration, dataUsage, addForAllUsers, null, true /* isRead */,
             call.callBlockReason /*callBlockReason*/,
             call.callScreeningAppName /*callScreeningAppName*/,
-            call.callScreeningComponentName /*callScreeningComponentName*/);
+            call.callScreeningComponentName /*callScreeningComponentName*/,
+            call.missedReason,
+            call.isPhoneAccountMigrationPending);
     }
 
     @VisibleForTesting
@@ -386,6 +407,29 @@
                 readString(dataInput);
                 readInteger(dataInput);
             }
+            if (version >= 1008) {
+                call.missedReason = dataInput.readLong();
+            }
+            if (version >= 1009) {
+                call.isPhoneAccountMigrationPending = dataInput.readInt();
+            }
+            /**
+             * In >=T Android, Telephony PhoneAccountHandle must use SubId as the ID (the unique
+             * identifier). Any version of Telephony call logs that are restored in >=T Android
+             * should set pending migration status as true and migrate to the subId later because
+             * different devices have different mappings between SubId and IccId.
+             *
+             * In <T Android, call log PhoneAccountHandle ID uses IccId, and backup with IccId;
+             * in >=T Android, call log PhoneAccountHandle ID uses SubId, and IccId is decided to
+             * use for backup for the reason mentioned above. Every time a call log is restored,
+             * the on-devie sub Id can be determined based on its IccId. The pending migration
+             * from IccId to SubId will be complete after the PhoneAccountHandle is registrated by
+             * Telecom and before CallLogProvider unhides it.
+             */
+            if (call.accountComponentName != null && call.accountComponentName.equals(
+                    TELEPHONY_PHONE_ACCOUNT_HANDLE_COMPONENT_NAME)) {
+                call.isPhoneAccountMigrationPending = 1;
+            }
             return call;
         } catch (IOException e) {
             Log.e(TAG, "Error reading call data for " + callId, e);
@@ -393,7 +437,26 @@
         }
     }
 
-    private Call readCallFromCursor(Cursor cursor) {
+    /**
+     * We need to use IccId for the PHONE_ACCOUNT_ID and set it as pending in backup when:
+     * 1) the phone account component name is telephony; AND
+     * 2) IS_PHONE_ACCOUNT_MIGRATION_PENDING status is not 1 ("1" means the ID is already IccId).
+     */
+    private boolean shouldConvertSubIdToIccIdForBackup(
+            String accountComponentName, int isPhoneAccountMigrationPending) {
+        if (mSubscriptionInfoMap == null) {
+            Log.e(TAG, "Subscription database is not available.");
+            return false;
+        }
+        if (accountComponentName.equals(TELEPHONY_PHONE_ACCOUNT_HANDLE_COMPONENT_NAME)
+                && isPhoneAccountMigrationPending != 1) {
+            return true;
+        }
+        return false;
+    }
+
+    @VisibleForTesting
+    Call readCallFromCursor(Cursor cursor) {
         Call call = new Call();
         call.id = cursor.getInt(cursor.getColumnIndex(CallLog.Calls._ID));
         call.date = cursor.getLong(cursor.getColumnIndex(CallLog.Calls.DATE));
@@ -419,6 +482,33 @@
             .getString(cursor.getColumnIndex(CallLog.Calls.CALL_SCREENING_APP_NAME));
         call.callScreeningComponentName = cursor
             .getString(cursor.getColumnIndex(CallLog.Calls.CALL_SCREENING_COMPONENT_NAME));
+        call.missedReason = cursor
+            .getInt(cursor.getColumnIndex(CallLog.Calls.MISSED_REASON));
+        call.isPhoneAccountMigrationPending = cursor.getInt(
+                cursor.getColumnIndex(CallLog.Calls.IS_PHONE_ACCOUNT_MIGRATION_PENDING));
+        /*
+         * Starting Android T, the ID of Telephony PhoneAccountHandle need to migrate from IccId
+         * to SubId. Because the mapping between IccId and SubId in different devices is different,
+         * the Backup need to use IccId for the ID and set it as pending migration, and when the
+         * ID is restored, ID need migrated to SubId after the corresponding PhoneAccountHandle
+         * is registrated by Telecom and before CallLogProvider unhides them.
+         */
+        if (shouldConvertSubIdToIccIdForBackup(call.accountComponentName,
+                call.isPhoneAccountMigrationPending)) {
+            Log.i(TAG, "Processing PhoneAccountMigration Backup accountId: " + call.accountId);
+            String iccId = null;
+            try {
+                iccId = mSubscriptionInfoMap.get(Integer.parseInt(call.accountId));
+            } catch (NullPointerException e) {
+                // Ignore, iccId will be null;
+            }
+            if (iccId != null) {
+                Log.i(TAG, "processing PhoneAccountMigration Found Subid during Backup: "
+                        + call.accountId);
+                call.accountId = iccId;
+                call.isPhoneAccountMigrationPending = 1;
+            }
+        }
         return call;
     }
 
@@ -464,6 +554,9 @@
             writeString(data, "");
             writeInteger(data, null);
 
+            data.writeLong(call.missedReason);
+            data.writeInt(call.isPhoneAccountMigrationPending);
+
             data.flush();
 
             output.writeEntityHeader(Integer.toString(call.id), baos.size());
@@ -586,12 +679,6 @@
         }
     }
 
-    static boolean shouldPreventBackup(Context context) {
-        // Check to see that the user is full-data aware before performing calllog backup.
-        return Settings.Secure.getInt(
-                context.getContentResolver(), USER_FULL_DATA_BACKUP_AWARE, 0) == 0;
-    }
-
     private static boolean isDebug() {
         return Log.isLoggable(TAG, Log.DEBUG);
     }
diff --git a/src/com/android/calllogbackup/CallLogChangeReceiver.java b/src/com/android/calllogbackup/CallLogChangeReceiver.java
index faede1f..b9339cc 100644
--- a/src/com/android/calllogbackup/CallLogChangeReceiver.java
+++ b/src/com/android/calllogbackup/CallLogChangeReceiver.java
@@ -37,16 +37,8 @@
     @Override
     public void onReceive(Context context, Intent intent) {
         if (ACTION_CALL_LOG_CHANGE.equals(intent.getAction())) {
-
-            if (CallLogBackupAgent.shouldPreventBackup(context)) {
-                // User is not full-backup-data aware so we skip calllog backup until they are.
-                if (VDBG) {
-                    Log.v(TAG, "Skipping call log backup due to lack of full-data check.");
-                }
-            } else {
-                BackupManager bm = new BackupManager(context);
-                bm.dataChanged();
-            }
+            BackupManager bm = new BackupManager(context);
+            bm.dataChanged();
         }
     }
 
diff --git a/tests/Android.bp b/tests/Android.bp
index a9944dd..db5ac87 100644
--- a/tests/Android.bp
+++ b/tests/Android.bp
@@ -1,6 +1,10 @@
+package {
+    // See: http://go/android-license-faq
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CallLogBackupTests",
-    static_libs: ["mockito-target"],
     libs: [
         "android.test.runner",
         "android.test.base",
@@ -13,4 +17,9 @@
     optimize: {
         enabled: false,
     },
+
+    static_libs: [
+        "mockito-target",
+        "androidx.test.rules",
+    ],
 }
diff --git a/tests/AndroidManifest.xml b/tests/AndroidManifest.xml
index 357df4f..c6fb765 100644
--- a/tests/AndroidManifest.xml
+++ b/tests/AndroidManifest.xml
@@ -29,7 +29,7 @@
     tests on their own then use the command:
     "adb shell am instrument -w com.android.calllogbackup.tests/android.test.InstrumentationTestRunner"
     -->
-    <instrumentation android:name="android.test.InstrumentationTestRunner"
+    <instrumentation android:name="androidx.test.runner.AndroidJUnitRunner"
         android:targetPackage="com.android.calllogbackup"
         android:label="CallLog Backup Tests">
     </instrumentation>
diff --git a/tests/src/com/android/calllogbackup/CallLogBackupAgentTest.java b/tests/src/com/android/calllogbackup/CallLogBackupAgentTest.java
index 4564195..9172330 100644
--- a/tests/src/com/android/calllogbackup/CallLogBackupAgentTest.java
+++ b/tests/src/com/android/calllogbackup/CallLogBackupAgentTest.java
@@ -16,15 +16,19 @@
 
 package com.android.calllogbackup;
 
-import static org.mockito.Mockito.never;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 import static org.mockito.Mockito.eq;
 
 import android.app.backup.BackupDataOutput;
+import android.content.Context;
+import android.database.Cursor;
+import android.provider.CallLog;
 import android.test.AndroidTestCase;
 import android.test.suitebuilder.annotation.SmallTest;
 
+import androidx.test.InstrumentationRegistry;
+
 import com.android.calllogbackup.CallLogBackupAgent.Call;
 import com.android.calllogbackup.CallLogBackupAgent.CallLogBackupState;
 
@@ -37,8 +41,10 @@
 import java.io.DataInput;
 import java.io.DataOutput;
 import java.io.EOFException;
+import java.util.HashMap;
 import java.util.LinkedList;
 import java.util.List;
+import java.util.Map;
 import java.util.TreeSet;
 
 /**
@@ -46,10 +52,15 @@
  */
 @SmallTest
 public class CallLogBackupAgentTest extends AndroidTestCase {
-
+    static final String TELEPHONY_COMPONENT
+            = "com.android.phone/com.android.services.telephony.TelephonyConnectionService";
+    static final String TEST_PHONE_ACCOUNT_HANDLE_SUB_ID = "666";
+    static final int TEST_PHONE_ACCOUNT_HANDLE_SUB_ID_INT = 666;
+    static final String TEST_PHONE_ACCOUNT_HANDLE_ICC_ID = "891004234814455936F";
     @Mock DataInput mDataInput;
     @Mock DataOutput mDataOutput;
     @Mock BackupDataOutput mBackupDataOutput;
+    @Mock Cursor mCursor;
 
     CallLogBackupAgent mCallLogBackupAgent;
 
@@ -63,7 +74,6 @@
         // Since we're testing a system app, AppDataDirGuesser doesn't find our
         // cache dir, so set it explicitly.
         System.setProperty("dexmaker.dexcache", getContext().getCacheDir().toString());
-
         MockitoAnnotations.initMocks(this);
 
         mCallLogBackupAgent = new CallLogBackupAgent();
@@ -74,6 +84,11 @@
         mMockitoHelper.tearDown();
     }
 
+    @Override
+    public Context getTestContext() {
+        return InstrumentationRegistry.getContext();
+    }
+
     public void testReadState_NoCall() throws Exception {
         when(mDataInput.readInt()).thenThrow(new EOFException());
 
@@ -178,6 +193,30 @@
         verify(mBackupDataOutput).writeEntityData((byte[]) Matchers.any(), Matchers.anyInt());
     }
 
+    /*
+        Test PhoneAccountHandle Migration process during back up
+     */
+    public void testReadCallFromCursorForPhoneAccountMigrationBackup() throws Exception {
+        Map<Integer, String> subscriptionInfoMap = new HashMap<>();
+        subscriptionInfoMap.put(TEST_PHONE_ACCOUNT_HANDLE_SUB_ID_INT,
+                TEST_PHONE_ACCOUNT_HANDLE_ICC_ID);
+        mCallLogBackupAgent.mSubscriptionInfoMap = subscriptionInfoMap;
+
+        // Mock telephony component name and expect the Sub ID is converted to Icc ID
+        // and the pending status is 1 when backup
+        mockCursor(mCursor, true);
+        Call call = mCallLogBackupAgent.readCallFromCursor(mCursor);
+        assertEquals(TEST_PHONE_ACCOUNT_HANDLE_ICC_ID, call.accountId);
+        assertEquals(1, call.isPhoneAccountMigrationPending);
+
+        // Mock non-telephony component name and expect the Sub ID not converted to Icc ID
+        // and pending status is 0 when backup.
+        mockCursor(mCursor, false);
+        call = mCallLogBackupAgent.readCallFromCursor(mCursor);
+        assertEquals(TEST_PHONE_ACCOUNT_HANDLE_SUB_ID, call.accountId);
+        assertEquals(0, call.isPhoneAccountMigrationPending);
+    }
+
     public void testRunBackup_MultipleCall() throws Exception {
         CallLogBackupState state = new CallLogBackupState();
         state.version = CallLogBackupAgent.VERSION;
@@ -216,6 +255,136 @@
                 writeEntityData((byte[]) Matchers.any(), Matchers.anyInt());
     }
 
+    private static void mockCursor(Cursor cursor, boolean isTelephonyComponentName) {
+        when(cursor.moveToNext()).thenReturn(true).thenReturn(false);
+
+        int CALLS_ID_COLUMN_INDEX = 1;
+        int CALL_ID = 9;
+        when(cursor.getColumnIndex(CallLog.Calls._ID)).thenReturn(CALLS_ID_COLUMN_INDEX);
+        when(cursor.getInt(CALLS_ID_COLUMN_INDEX)).thenReturn(CALL_ID);
+
+        int CALLS_DATE_COLUMN_INDEX = 2;
+        long CALL_DATE = 20991231;
+        when(cursor.getColumnIndex(CallLog.Calls.DATE)).thenReturn(CALLS_DATE_COLUMN_INDEX);
+        when(cursor.getLong(CALLS_DATE_COLUMN_INDEX)).thenReturn(CALL_DATE);
+
+        int CALLS_DURATION_COLUMN_INDEX = 3;
+        long CALL_DURATION = 987654321;
+        when(cursor.getColumnIndex(CallLog.Calls.DURATION)).thenReturn(
+                CALLS_DURATION_COLUMN_INDEX);
+        when(cursor.getLong(CALLS_DURATION_COLUMN_INDEX)).thenReturn(CALL_DURATION);
+
+        int CALLS_NUMBER_COLUMN_INDEX = 4;
+        String CALL_NUMBER = "6316056461";
+        when(cursor.getColumnIndex(CallLog.Calls.NUMBER)).thenReturn(
+                CALLS_NUMBER_COLUMN_INDEX);
+        when(cursor.getString(CALLS_NUMBER_COLUMN_INDEX)).thenReturn(CALL_NUMBER);
+
+        int CALLS_POST_DIAL_DIGITS_COLUMN_INDEX = 5;
+        String CALL_POST_DIAL_DIGITS = "54321";
+        when(cursor.getColumnIndex(CallLog.Calls.POST_DIAL_DIGITS)).thenReturn(
+                CALLS_POST_DIAL_DIGITS_COLUMN_INDEX);
+        when(cursor.getString(CALLS_POST_DIAL_DIGITS_COLUMN_INDEX)).thenReturn(
+                CALL_POST_DIAL_DIGITS);
+
+        int CALLS_VIA_NUMBER_COLUMN_INDEX = 6;
+        String CALL_VIA_NUMBER = "via_number";
+        when(cursor.getColumnIndex(CallLog.Calls.VIA_NUMBER)).thenReturn(
+                CALLS_VIA_NUMBER_COLUMN_INDEX);
+        when(cursor.getString(CALLS_VIA_NUMBER_COLUMN_INDEX)).thenReturn(
+                CALL_VIA_NUMBER);
+
+        int CALLS_TYPE_COLUMN_INDEX = 7;
+        int CALL_TYPE = CallLog.Calls.OUTGOING_TYPE;
+        when(cursor.getColumnIndex(CallLog.Calls.TYPE)).thenReturn(CALLS_TYPE_COLUMN_INDEX);
+        when(cursor.getInt(CALLS_TYPE_COLUMN_INDEX)).thenReturn(CALL_TYPE);
+
+        int CALLS_NUMBER_PRESENTATION_COLUMN_INDEX = 8;
+        int CALL_NUMBER_PRESENTATION = CallLog.Calls.PRESENTATION_ALLOWED;
+        when(cursor.getColumnIndex(CallLog.Calls.NUMBER_PRESENTATION)).thenReturn(
+                CALLS_NUMBER_PRESENTATION_COLUMN_INDEX);
+        when(cursor.getInt(CALLS_NUMBER_PRESENTATION_COLUMN_INDEX)).thenReturn(
+                CALL_NUMBER_PRESENTATION);
+
+        int CALLS_ACCOUNT_COMPONENT_NAME_COLUMN_INDEX = 9;
+        String CALL_ACCOUNT_COMPONENT_NAME = "NON_TELEPHONY_COMPONENT_NAME";
+        if (isTelephonyComponentName) {
+            CALL_ACCOUNT_COMPONENT_NAME = TELEPHONY_COMPONENT;
+        }
+        when(cursor.getColumnIndex(CallLog.Calls.PHONE_ACCOUNT_COMPONENT_NAME)).thenReturn(
+                CALLS_ACCOUNT_COMPONENT_NAME_COLUMN_INDEX);
+        when(cursor.getString(CALLS_ACCOUNT_COMPONENT_NAME_COLUMN_INDEX)).thenReturn(
+                CALL_ACCOUNT_COMPONENT_NAME);
+
+        int CALLS_ACCOUNT_ID_COLUMN_INDEX = 10;
+        String CALL_ACCOUNT_ID = TEST_PHONE_ACCOUNT_HANDLE_SUB_ID;
+        when(cursor.getColumnIndex(CallLog.Calls.PHONE_ACCOUNT_ID)).thenReturn(
+                CALLS_ACCOUNT_ID_COLUMN_INDEX);
+        when(cursor.getString(CALLS_ACCOUNT_ID_COLUMN_INDEX)).thenReturn(
+                CALL_ACCOUNT_ID);
+
+        int CALLS_ACCOUNT_ADDRESS_COLUMN_INDEX = 11;
+        String CALL_ACCOUNT_ADDRESS = "CALL_ACCOUNT_ADDRESS";
+        when(cursor.getColumnIndex(CallLog.Calls.PHONE_ACCOUNT_ADDRESS)).thenReturn(
+                CALLS_ACCOUNT_ADDRESS_COLUMN_INDEX);
+        when(cursor.getString(CALLS_ACCOUNT_ADDRESS_COLUMN_INDEX)).thenReturn(
+                CALL_ACCOUNT_ADDRESS);
+
+        int CALLS_DATA_USAGE_COLUMN_INDEX = 12;
+        long CALL_DATA_USAGE = 987654321;
+        when(cursor.getColumnIndex(CallLog.Calls.DATA_USAGE)).thenReturn(
+                CALLS_DATA_USAGE_COLUMN_INDEX);
+        when(cursor.getLong(CALLS_DATA_USAGE_COLUMN_INDEX)).thenReturn(CALL_DATA_USAGE);
+
+        int CALLS_FEATURES_COLUMN_INDEX = 13;
+        int CALL_FEATURES = 777;
+        when(cursor.getColumnIndex(CallLog.Calls.FEATURES)).thenReturn(
+                CALLS_FEATURES_COLUMN_INDEX);
+        when(cursor.getInt(CALLS_FEATURES_COLUMN_INDEX)).thenReturn(CALL_FEATURES);
+
+        int CALLS_ADD_FOR_ALL_USERS_COLUMN_INDEX = 14;
+        int CALL_ADD_FOR_ALL_USERS = 1;
+        when(cursor.getColumnIndex(CallLog.Calls.ADD_FOR_ALL_USERS)).thenReturn(
+                CALLS_ADD_FOR_ALL_USERS_COLUMN_INDEX);
+        when(cursor.getInt(CALLS_ADD_FOR_ALL_USERS_COLUMN_INDEX)).thenReturn(
+                CALL_ADD_FOR_ALL_USERS);
+
+        int CALLS_BLOCK_REASON_COLUMN_INDEX = 15;
+        int CALL_BLOCK_REASON = CallLog.Calls.BLOCK_REASON_NOT_BLOCKED;
+        when(cursor.getColumnIndex(CallLog.Calls.BLOCK_REASON)).thenReturn(
+                CALLS_BLOCK_REASON_COLUMN_INDEX);
+        when(cursor.getInt(CALLS_BLOCK_REASON_COLUMN_INDEX)).thenReturn(
+                CALL_BLOCK_REASON);
+
+        int CALLS_CALL_SCREENING_APP_NAME_COLUMN_INDEX = 16;
+        String CALL_CALL_SCREENING_APP_NAME = "CALL_CALL_SCREENING_APP_NAME";
+        when(cursor.getColumnIndex(CallLog.Calls.CALL_SCREENING_APP_NAME)).thenReturn(
+                CALLS_CALL_SCREENING_APP_NAME_COLUMN_INDEX);
+        when(cursor.getString(CALLS_CALL_SCREENING_APP_NAME_COLUMN_INDEX)).thenReturn(
+                CALL_CALL_SCREENING_APP_NAME);
+
+        int CALLS_CALL_SCREENING_COMPONENT_NAME_COLUMN_INDEX = 17;
+        String CALL_CALL_SCREENING_COMPONENT_NAME = "CALL_CALL_SCREENING_COMPONENT_NAME";
+        when(cursor.getColumnIndex(CallLog.Calls.CALL_SCREENING_COMPONENT_NAME)).thenReturn(
+                CALLS_CALL_SCREENING_COMPONENT_NAME_COLUMN_INDEX);
+        when(cursor.getString(CALLS_CALL_SCREENING_COMPONENT_NAME_COLUMN_INDEX)).thenReturn(
+                CALL_CALL_SCREENING_COMPONENT_NAME);
+
+        int CALLS_MISSED_REASON_COLUMN_INDEX = 18;
+        String CALL_MISSED_REASON = "CALL_MISSED_REASON";
+        when(cursor.getColumnIndex(CallLog.Calls.MISSED_REASON)).thenReturn(
+                CALLS_MISSED_REASON_COLUMN_INDEX);
+        when(cursor.getString(CALLS_MISSED_REASON_COLUMN_INDEX)).thenReturn(
+                CALL_MISSED_REASON);
+
+        int CALLS_IS_PHONE_ACCOUNT_MIGRATION_PENDING_COLUMN_INDEX = 19;
+        int CALL_IS_PHONE_ACCOUNT_MIGRATION_PENDING = 0;
+        when(cursor.getColumnIndex(CallLog.Calls.IS_PHONE_ACCOUNT_MIGRATION_PENDING)).thenReturn(
+                CALLS_IS_PHONE_ACCOUNT_MIGRATION_PENDING_COLUMN_INDEX);
+        when(cursor.getInt(CALLS_IS_PHONE_ACCOUNT_MIGRATION_PENDING_COLUMN_INDEX)).thenReturn(
+                CALL_IS_PHONE_ACCOUNT_MIGRATION_PENDING);
+    }
+
     private static Call makeCall(int id, long date, long duration, String number) {
         Call c = new Call();
         c.id = id;