contacts: re-sync SIM list after ADN writes until reads converge (#841)
- Commit
954631fbccf8384db4d99eb9518eeb6a8ed64eab- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-05 18:54 UTC (1 month ago)
- Parents
632bf0f
Symptom: moving a contact phone->SIM or creating a SIM contact intermittently vanished - invisible in this app and in Google Contacts' import - until the SIM was removed and reinserted, at which point every missing contact reappeared. The writes always succeeded on the card; reinsertion only forced a fresh ADN read. Root cause: the platform ICC provider serves ADN reads from a cache that converges asynchronously after a write (OEM/modem dependent, hence intermittent). The app re-read immediately after writing, picked up the stale cache, and then never re-read: its ContentObserver watches ContactsContract only, ADN writes never touch that authority, and the IccProvider does not reliably notify its own URIs either. Fix (SIM refresh/observer path only): - SimContactsDataSource.notifyChange()s the written ADN URI plus the base URI after every successful insert/update/delete. - ContactViewModel registers a ContentObserver on content://icc/adn (descendants included) feeding the existing debounced sync, and SIM save/transfer paths schedule one coalesced convergence re-sync 2s after a successful write. User-visible effect: SIM moves and new SIM contacts appear in the list within ~2s even when the provider cache lags, instead of staying invisible until SIM reinsert. Verification: :contacts:compileDevKotlin --rerun-tasks BUILD SUCCESSFUL; new symbols confirmed in compiled classes via javap (scheduleSimConvergenceSync, SIM_CONVERGENCE_DELAY_MILLIS, notifySimChanged, simObserver). Needs on-device testing with a physical SIM: move phone->SIM and create-SIM-contact, confirm appearance without reinsert.
Diff
contacts/src/main/java/com/vayunmathur/contacts/data/SimContacts.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/data/SimContacts.kt b/contacts/src/main/java/com/vayunmathur/contacts/data/SimContacts.ktindex bf55c71674..e6ac13d2bc 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/data/SimContacts.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/data/SimContacts.kt@@ -63,6 +63,9 @@ object SimContactsDataSource { private const val TAG = "SimContacts" private const val BASE_URI = "content://icc/adn" + /** Base ADN URI observers register on; the base for per-subId URIs. */+ internal const val SIM_ADN_BASE_URI: String = BASE_URI+ // Broad catch is deliberate: OEM ICC providers throw undocumented // RuntimeExceptions (not just SecurityException) on emulators and // devices without a physical SIM.@@ -248,6 +251,7 @@ object SimContactsDataSource { } } val inserted = context.contentResolver.insert(uri, values)+ if (inserted != null) notifySimChanged(context, uri) inserted != null } catch (e: SecurityException) { Log.error(TAG, "SecurityException inserting SIM contact", e)@@ -294,7 +298,9 @@ object SimContactsDataSource { // email would report success without changing anything. put("newEmails", email.orEmpty()) }- context.contentResolver.update(uri, values, null, null) > 0+ val updated = context.contentResolver.update(uri, values, null, null) > 0+ if (updated) notifySimChanged(context, uri)+ updated } catch (e: SecurityException) { Log.error(TAG, "SecurityException updating SIM contact", e) false@@ -353,7 +359,10 @@ object SimContactsDataSource { for (where in variants) { try { val count = context.contentResolver.delete(uri, where, null)- if (count > 0) return true+ if (count > 0) {+ notifySimChanged(context, uri)+ return true+ } } catch (_: Exception) { } } // Last resort: query then delete by encoding? Some providers expect content://icc/adn/#@@ -368,6 +377,22 @@ object SimContactsDataSource { */ private fun String.asIccLiteral(): String = "'$this'" + /**+ * Broadcasts our own ADN write to any observer of the SIM provider. The+ * platform IccProvider does not reliably notify these URIs itself, and the+ * app's contacts observer watches ContactsContract only, so without this a+ * successful write can sit invisible until the next unrelated re-sync.+ * Notifying both the written URI and the base URI covers subId-scoped and+ * base-URI observers. Best effort: notification must never fail a write.+ */+ private fun notifySimChanged(context: Context, uri: Uri) {+ try {+ context.contentResolver.notifyChange(uri, null)+ val base = Uri.parse(BASE_URI)+ if (uri != base) context.contentResolver.notifyChange(base, null)+ } catch (_: Exception) { }+ }+ fun hasSim(context: Context): Boolean { return try { getActiveSubscriptionIds(context).isNotEmpty()
contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModel.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModel.kt b/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModel.ktindex 3db5f3749a..ed188d3104 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModel.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModel.kt@@ -261,6 +261,22 @@ class ContactViewModel(application: Application) : AndroidViewModel(application) override fun onChange(selfChange: Boolean) { syncTrigger.tryEmit(Unit) } } + // Fires on SIM ADN (content://icc/adn) changes: our own SIM writes notify+ // these URIs (see SimContactsDataSource), and some OEM IccProviders notify+ // them on external/modem-side updates too. The ContactsContract observer+ // above never fires for ADN writes, so without this the refreshed SIM list+ // after a write depends solely on the immediate re-read converging. Feeds+ // the same debounced syncTrigger; kept as a field so onCleared() can+ // unregister it.+ private val simObserver = object : android.database.ContentObserver(+ android.os.Handler(android.os.Looper.getMainLooper())+ ) {+ override fun onChange(selfChange: Boolean) { syncTrigger.tryEmit(Unit) }+ }++ private fun simAdnBaseUri(): android.net.Uri =+ android.net.Uri.parse(SimContactsDataSource.SIM_ADN_BASE_URI)+ // Fires on SIM insert/remove/swap. The provider observer above never fires for // those (no provider write happens), so without this the SIM list only refreshes // when the app is reopened. Feeds the same debounced syncTrigger; kept as a field@@ -280,6 +296,9 @@ class ContactViewModel(application: Application) : AndroidViewModel(application) // account change fires it; debounced so a sync burst causes a single reload. getApplication<Application>().contentResolver .registerContentObserver(ContactsContract.AUTHORITY_URI, true, contactsObserver)+ // notifyForDescendants=true so subId-scoped ADN URIs fire it too.+ getApplication<Application>().contentResolver+ .registerContentObserver(simAdnBaseUri(), true, simObserver) // Broad catch is deliberate: OEM SubscriptionManager implementations throw // undocumented RuntimeExceptions, and a failed listener must not block init. @Suppress("TooGenericExceptionCaught")@@ -303,6 +322,7 @@ class ContactViewModel(application: Application) : AndroidViewModel(application) override fun onCleared() { getApplication<Application>().contentResolver.unregisterContentObserver(contactsObserver)+ getApplication<Application>().contentResolver.unregisterContentObserver(simObserver) // Broad catch is deliberate: must not throw out of onCleared. @Suppress("TooGenericExceptionCaught") try {
contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModelSim.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModelSim.kt b/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModelSim.ktindex 02b02e16b0..ec12a5ce7d 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModelSim.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModelSim.kt@@ -1,11 +1,14 @@ package com.vayunmathur.contacts.util import android.app.Application+import androidx.lifecycle.viewModelScope import com.vayunmathur.library.log.Log import com.vayunmathur.contacts.R import com.vayunmathur.contacts.data.SIM_ACCOUNT_TYPE import com.vayunmathur.contacts.data.SimContactsDataSource import com.vayunmathur.contacts.data.isSimAccountType+import kotlinx.coroutines.delay+import kotlinx.coroutines.launch /** * SIM-backed save path and SIM account labels, kept out of ContactViewModel@@ -29,6 +32,7 @@ internal suspend fun ContactViewModel.persistSimContact( val ok = SimContactsDataSource.insertSimContact(getApplication(), name, number, email, subId) if (!ok) Log.error("ContactViewModel", "Failed to insert SIM contact") syncFromSystem()+ if (ok) scheduleSimConvergenceSync() return ok } @@ -92,6 +96,7 @@ internal suspend fun ContactViewModel.updateExistingSimContact( val updated = SimContactsDataSource.updateSimContact(app, oldSc, name, number, email, subId) if (updated) { syncFromSystem()+ scheduleSimConvergenceSync() return true } }@@ -99,6 +104,25 @@ internal suspend fun ContactViewModel.updateExistingSimContact( return null } +/**+ * Re-reads the SIM list once the ADN provider's read cache has had time to+ * converge on our write. Intermittently the immediate post-write+ * [syncFromSystem] reads stale provider data (the contact then appears only+ * after a SIM reinsert, see #841): the provider serves writes from a cache+ * that converges asynchronously, and nothing re-reads afterwards. The delayed+ * re-sync is coalesced through the debounced sync path, so bursts of SIM+ * writes cause at most one extra read.+ */+internal fun ContactViewModel.scheduleSimConvergenceSync() {+ viewModelScope.launch {+ delay(SIM_CONVERGENCE_DELAY_MILLIS)+ syncFromSystem()+ }+}++/** Delay before the SIM convergence re-sync; hoisted so tests can reference it. */+internal const val SIM_CONVERGENCE_DELAY_MILLIS = 2_000L+ internal suspend fun ContactViewModel.persistProviderContact( contact: com.vayunmathur.contacts.data.Contact ): Boolean {
contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModelTransfer.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModelTransfer.kt b/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModelTransfer.ktindex 97fd2a9295..39e92cdad4 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModelTransfer.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModelTransfer.kt@@ -167,6 +167,7 @@ private suspend fun ContactViewModel.copyProviderToSim( val email = contact.details.emails.firstOrNull()?.address?.trim()?.takeIf { it.isNotEmpty() } if (name.isBlank() && number.isBlank()) return InsertOutcome(false, false) val ok = SimContactsDataSource.insertSimContact(app, name, number, email, subId)+ if (ok) scheduleSimConvergenceSync() return InsertOutcome(ok, contact.details.groups.isNotEmpty() && ok) }