contacts: explain and avoid On-Device saves refused by Android 16 (#916)
- Commit
ed175f20282c6e111bc2257e941d7c76b447e21e- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-12 04:40 UTC (24 days ago)
- Parents
21cbeba
Symptom: on stock Pixels (Android 16), creating a contact with
"On-Device" picked as the account failed with a bare "Save failed".
Saving to a sync account such as Nextcloud via DAVx5 kept working.
Root cause: from Android 16 (BAKLAVA), for apps targeting it (we target
37), ContactsProvider enforces compat change
RESTRICT_CONTACTS_CREATION_IN_ACCOUNTS. When the device's default
account for new contacts is a cloud account (Google on Pixels),
AccountResolver throws IllegalArgumentException("Cannot add contacts to
local or SIM accounts when default account is set to cloud") for any
new raw contact in the device-local (NULL) account, the OEM-customised
local account, or a SIM account registered with the provider.
Contact.save caught it with every other IllegalArgumentException and
returned false, so the editor showed its generic error. DAVx5 accounts
are not eligible as the default and are not local, so they pass.
What changed:
- data/NewContactAccountPolicy.kt (pure): DefaultAccountSource
abstraction, NewContactRestriction (which accounts are refused while
the default is cloud), SaveOutcome, and a matcher for the provider's
refusal (walks the cause chain, IllegalArgumentException only).
- data/SystemDefaultAccountSource.kt: platform source. On API 36+ reads
RawContacts.DefaultAccount.getDefaultAccountForNewContacts, plus
RawContacts.getLocalAccountName/Type and SimContacts.getSimAccounts
to know the exact accounts the provider refuses. Every call is
SDK-guarded and runCatching'd: OEM builds may not implement them, and
a failure reads as "no restriction".
- ContactViewModel keeps the restriction as state (refreshed on each
account load and before a new draft is seeded) and adds the cloud
default to the account list so it is pickable even when empty.
- New drafts default to the cloud account instead of On-Device when
the last-used account would be refused; any other last-used account
(DAVx5, the app's own local accounts, SIM) is kept.
- Account chooser (editor), vCard import picker and move-to-account
dialog list refused accounts disabled with "Unavailable while your
default contacts account is <account>. Change it in system Contacts
settings." The import screen no longer auto-selects a refused account.
- Contact.saveWithOutcome reports REJECTED_CLOUD_DEFAULT for this
error; save() keeps its Boolean contract. The editor save, vCard
import (stops at the first refusal and stays on screen) and
move-to-account map it to a message naming the default account and
how to change it, instead of "Save failed"/"Move failed".
- The assistant "add contact" intent asked for no account and wrote
the NULL account, so it hit the same refusal; it now uses the cloud
default when one is set.
Not changed: the app's SIM targets write the card via content://icc/adn,
outside ContactsProvider, so the restriction does not reach them and
they stay enabled (only provider-registered SIM accounts are disabled).
Group creation inserts groups without account columns, which the
provider already resolves to the default account, so it cannot hit
this error.
Alternatives rejected:
- Omitting the account columns so the insert goes through: Android
would silently put the contact in the cloud account, the opposite of
what the user chose.
- Matching only the message text in the UI: the outcome is classified
once in Contact.saveWithOutcome so every write path shares it.
User-visible effect: on Android 16 devices whose default contacts
account is a cloud account, On-Device (and provider SIM accounts) show
as unavailable with the reason, new contacts start in the default cloud
account, and a refused save/import/move explains why and what to do.
Other devices and default-account states behave as before.
Verified (toolchain container, gbuild.sh): :contacts:compileDevKotlin,
:contacts:testDevUnitTest (new NewContactAccountPolicyTest: cloud
default disables device/provider-SIM targets, leaves cloud, DAVx5, app
SIM and app local accounts enabled, non-cloud defaults change nothing,
refusal maps and other errors do not; new CloudDefaultAccountPass2Test:
refusal yields REJECTED_CLOUD_DEFAULT, cloud default seeds new drafts
with the cloud account and lists it, a refused editor save returns the
clear message, a local default keeps On-Device), :contacts:lint (no new
findings) and :contacts:detekt (no new findings; the 19 errors it
reports all predate this change and sit in code it does not modify).
Not yet verified on a device.Diff
contacts/src/main/java/com/vayunmathur/contacts/data/Contact.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/data/Contact.kt b/contacts/src/main/java/com/vayunmathur/contacts/data/Contact.ktindex 919df07a3b..4a688cac80 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/data/Contact.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/data/Contact.kt@@ -331,7 +331,15 @@ data class Contact( get() = details.notes.firstOrNull() ?: Note(0, "") /** Returns false if the provider rejected the batch; never throws. */- fun save(context: Context, newDetails: ContactDetails, oldDetails: ContactDetails): Boolean {+ fun save(context: Context, newDetails: ContactDetails, oldDetails: ContactDetails): Boolean =+ saveWithOutcome(context, newDetails, oldDetails) == SaveOutcome.SAVED++ /**+ * Like [save], but tells a provider refusal of the target account apart from other+ * failures: on Android 16+ a new contact in the device or a provider SIM account is+ * rejected while the default account is a cloud account (see [NewContactRestriction]).+ */+ fun saveWithOutcome(context: Context, newDetails: ContactDetails, oldDetails: ContactDetails): SaveOutcome { val ops = ArrayList<ContentProviderOperation>() if (id == 0L) { ops += ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)@@ -355,19 +363,23 @@ data class Contact( } return try { context.contentResolver.applyBatch(ContactsContract.AUTHORITY, ops)- true+ SaveOutcome.SAVED } catch (e: android.content.OperationApplicationException) { Log.error("Contact", "Error saving contact", e)- false+ SaveOutcome.FAILED } catch (e: android.os.RemoteException) { Log.error("Contact", "Error saving contact", e)- false+ SaveOutcome.FAILED } catch (e: SecurityException) { Log.error("Contact", "Error saving contact", e)- false+ SaveOutcome.FAILED } catch (e: IllegalArgumentException) { Log.error("Contact", "Error saving contact", e)- false+ if (NewContactAccountPolicy.isCloudDefaultRejection(e)) {+ SaveOutcome.REJECTED_CLOUD_DEFAULT+ } else {+ SaveOutcome.FAILED+ } } }
contacts/src/main/java/com/vayunmathur/contacts/data/NewContactAccountPolicy.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/data/NewContactAccountPolicy.kt b/contacts/src/main/java/com/vayunmathur/contacts/data/NewContactAccountPolicy.ktnew file mode 100644index 0000000000..804a2da642--- /dev/null+++ b/contacts/src/main/java/com/vayunmathur/contacts/data/NewContactAccountPolicy.kt@@ -0,0 +1,97 @@+package com.vayunmathur.contacts.data++/**+ * An account as the contacts provider names it. Blank [name] and [type] is the+ * device-local NULL account (shown as "On-Device").+ */+data class ProviderAccount(val name: String, val type: String)++/** Mirrors `ContactsContract.RawContacts.DefaultAccount.DefaultAccountAndState` states. */+enum class DefaultAccountKind { NOT_SET, LOCAL, SIM, CLOUD }++/** The system's default account for new contacts. [account] is set for SIM and CLOUD. */+data class DefaultAccountSnapshot(val kind: DefaultAccountKind, val account: ProviderAccount?)++/**+ * Where the provider's account facts come from. The platform implementation is+ * [SystemDefaultAccountSource]; tests substitute a fake.+ */+interface DefaultAccountSource {+ /** Null before Android 16, or when the query failed (OEM builds may differ). */+ fun defaultAccountForNewContacts(): DefaultAccountSnapshot?++ /**+ * The device's customised local account (`RawContacts.getLocalAccountName/Type`),+ * or null when the device uses the NULL account for local contacts.+ */+ fun customLocalAccount(): ProviderAccount?++ /** SIM accounts registered with the contacts provider (`SimContacts.getSimAccounts`). */+ fun providerSimAccounts(): List<ProviderAccount>+}++/**+ * Accounts the provider refuses new contacts for while the default account is the+ * cloud account [cloudAccount] (Android 16+, compat change+ * RESTRICT_CONTACTS_CREATION_IN_ACCOUNTS): the device-local account and the SIM+ * accounts registered with the provider.+ *+ * The app's own SIM targets ([SIM_ACCOUNT_TYPE]) are not blocked: they write the card+ * through `content://icc/adn`, not the contacts provider, so the restriction does not+ * reach them. Accounts of [LOCAL_ACCOUNT_TYPE] are ordinary named accounts to the+ * provider and are not blocked either.+ */+data class NewContactRestriction(+ val cloudAccount: ProviderAccount,+ val blockedAccounts: Set<ProviderAccount> = emptySet(),+) {+ /** True when the provider would reject a new contact in the account ([name], [type]). */+ fun blocks(name: String?, type: String?): Boolean {+ val n = name.orEmpty()+ val t = type.orEmpty()+ if (n.isBlank() && t.isBlank()) return true+ return ProviderAccount(n, t) in blockedAccounts+ }+}++/** Result of [Contact.saveWithOutcome]. */+enum class SaveOutcome { SAVED, FAILED, REJECTED_CLOUD_DEFAULT }++/**+ * Decides which accounts can take new contacts under the system default account+ * (Android 16+, #916) and recognises the provider's refusal.+ */+object NewContactAccountPolicy {++ /** Start of the provider's message (ContactsProvider AccountResolver). */+ const val CLOUD_DEFAULT_REJECTION = "Cannot add contacts to local or SIM accounts"++ /** Bound on the cause chain walked by [isCloudDefaultRejection]. */+ private const val MAX_CAUSE_DEPTH = 8++ /**+ * The restriction in force, or null when new contacts may go anywhere: the+ * default account is unknown (pre-Android 16 or query failure), not set, local,+ * or SIM.+ */+ fun resolve(source: DefaultAccountSource): NewContactRestriction? {+ val snapshot = source.defaultAccountForNewContacts() ?: return null+ if (snapshot.kind != DefaultAccountKind.CLOUD) return null+ val cloud = snapshot.account?.takeIf { it.name.isNotBlank() && it.type.isNotBlank() }+ ?: return null+ val blocked = buildSet {+ source.customLocalAccount()?.let(::add)+ addAll(source.providerSimAccounts())+ }+ return NewContactRestriction(cloud, blocked)+ }++ /**+ * True when [error], or one of its causes, is the provider rejecting a new contact+ * in a device or SIM account because the default account is a cloud account.+ */+ fun isCloudDefaultRejection(error: Throwable): Boolean =+ generateSequence(error) { it.cause }+ .take(MAX_CAUSE_DEPTH)+ .any { it is IllegalArgumentException && it.message?.contains(CLOUD_DEFAULT_REJECTION) == true }+}
contacts/src/main/java/com/vayunmathur/contacts/data/SystemDefaultAccountSource.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/data/SystemDefaultAccountSource.kt b/contacts/src/main/java/com/vayunmathur/contacts/data/SystemDefaultAccountSource.ktnew file mode 100644index 0000000000..466c370a5f--- /dev/null+++ b/contacts/src/main/java/com/vayunmathur/contacts/data/SystemDefaultAccountSource.kt@@ -0,0 +1,56 @@+package com.vayunmathur.contacts.data++import android.content.Context+import android.os.Build+import android.provider.ContactsContract+import com.vayunmathur.library.log.Log++/**+ * [DefaultAccountSource] over the platform contacts APIs. Every call is SDK-guarded and+ * wrapped in runCatching: OEM contacts providers may not implement the Android 16+ * default-account methods, and a failed query must read as "no restriction" rather+ * than break the editor.+ */+class SystemDefaultAccountSource(context: Context) : DefaultAccountSource {++ private val appContext = context.applicationContext++ override fun defaultAccountForNewContacts(): DefaultAccountSnapshot? {+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.BAKLAVA) return null+ return runCatching { queryDefaultAccount() }+ .onFailure { Log.error(TAG, "Default account query failed", it) }+ .getOrNull()+ }++ @androidx.annotation.RequiresApi(Build.VERSION_CODES.BAKLAVA)+ private fun queryDefaultAccount(): DefaultAccountSnapshot {+ val state = ContactsContract.RawContacts.DefaultAccount+ .getDefaultAccountForNewContacts(appContext.contentResolver)+ val kind = when (state.state) {+ DefaultAccountAndState.DEFAULT_ACCOUNT_STATE_CLOUD -> DefaultAccountKind.CLOUD+ DefaultAccountAndState.DEFAULT_ACCOUNT_STATE_SIM -> DefaultAccountKind.SIM+ DefaultAccountAndState.DEFAULT_ACCOUNT_STATE_LOCAL -> DefaultAccountKind.LOCAL+ else -> DefaultAccountKind.NOT_SET+ }+ val account = state.account?.let { ProviderAccount(it.name.orEmpty(), it.type.orEmpty()) }+ return DefaultAccountSnapshot(kind, account)+ }++ override fun customLocalAccount(): ProviderAccount? = runCatching {+ val name = ContactsContract.RawContacts.getLocalAccountName(appContext)+ val type = ContactsContract.RawContacts.getLocalAccountType(appContext)+ if (name.isNullOrBlank() || type.isNullOrBlank()) null else ProviderAccount(name, type)+ }.onFailure { Log.error(TAG, "Local account query failed", it) }.getOrNull()++ override fun providerSimAccounts(): List<ProviderAccount> = runCatching {+ ContactsContract.SimContacts.getSimAccounts(appContext.contentResolver)+ .map { ProviderAccount(it.accountName.orEmpty(), it.accountType.orEmpty()) }+ }.onFailure { Log.error(TAG, "SIM account query failed", it) }.getOrDefault(emptyList())++ private companion object {+ const val TAG = "DefaultAccount"+ }+}++private typealias DefaultAccountAndState =+ ContactsContract.RawContacts.DefaultAccount.DefaultAccountAndState
contacts/src/main/java/com/vayunmathur/contacts/intents/InsertIntent.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/intents/InsertIntent.kt b/contacts/src/main/java/com/vayunmathur/contacts/intents/InsertIntent.ktindex 18c584a2c2..93788ebf5e 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/intents/InsertIntent.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/intents/InsertIntent.kt@@ -5,10 +5,12 @@ import com.vayunmathur.contacts.data.CDKPhone import com.vayunmathur.contacts.data.Contact import com.vayunmathur.contacts.data.ContactDetails import com.vayunmathur.contacts.data.Name+import com.vayunmathur.contacts.data.NewContactAccountPolicy import com.vayunmathur.contacts.data.Nickname import com.vayunmathur.contacts.data.Note import com.vayunmathur.contacts.data.Organization import com.vayunmathur.contacts.data.PhoneNumber+import com.vayunmathur.contacts.data.SystemDefaultAccountSource import com.vayunmathur.library.intents.contacts.ContactData import com.vayunmathur.library.util.AssistantIntent import kotlinx.serialization.InternalSerializationApi@@ -27,7 +29,10 @@ class InsertIntent: AssistantIntent<ContactData, Unit>(serializer<ContactData>() notes = listOf(Note(0, "")), nicknames = listOf(Nickname(0, "", CDKNickname.TYPE_DEFAULT)) )- val contact = Contact(0L, null, null, false, details)+ // No account was asked for, so use the system default: on Android 16+ a cloud+ // default makes the provider refuse the device-local account (#916).+ val cloud = NewContactAccountPolicy.resolve(SystemDefaultAccountSource(this))?.cloudAccount+ val contact = Contact(0L, cloud?.type, cloud?.name, false, details) contact.save(this, contact.details, ContactDetails.empty()) } }
contacts/src/main/java/com/vayunmathur/contacts/ui/AccountSelectorDropdown.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/ui/AccountSelectorDropdown.kt b/contacts/src/main/java/com/vayunmathur/contacts/ui/AccountSelectorDropdown.ktnew file mode 100644index 0000000000..7ec52209b5--- /dev/null+++ b/contacts/src/main/java/com/vayunmathur/contacts/ui/AccountSelectorDropdown.kt@@ -0,0 +1,68 @@+package com.vayunmathur.contacts.ui++import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import com.vayunmathur.contacts.R+import com.vayunmathur.contacts.data.NewContactRestriction+import com.vayunmathur.contacts.util.ContactAccount+import com.vayunmathur.library.ui.DropdownMenu+import com.vayunmathur.library.ui.DropdownMenuItem+import com.vayunmathur.library.ui.IconArrowDropDown+import com.vayunmathur.library.ui.ListItem+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text++/**+ * Destination picker for the vCard import screen. Accounts [restriction] blocks+ * (Android 16+ with a cloud default account, #916) are listed disabled with the reason.+ */+@Composable+fun AccountSelectorDropdown(+ accounts: List<ContactAccount>,+ selectedAccount: ContactAccount?,+ modifier: Modifier = Modifier,+ restriction: NewContactRestriction? = null,+ onSelect: (ContactAccount) -> Unit,+) {+ var showDropdown by remember { mutableStateOf(false) }+ val onDevice = stringResource(R.string.on_device)+ val blockedReason = restriction?.let {+ stringResource(R.string.account_unavailable_cloud_default, it.cloudAccount.name)+ }++ Box(modifier) {+ ListItem(+ content = { Text(selectedAccount?.name?.ifEmpty { onDevice } ?: stringResource(R.string.select_account)) },+ trailingContent = { IconArrowDropDown() },+ modifier = Modifier.clickable { showDropdown = true },+ )+ DropdownMenu(expanded = showDropdown, onDismissRequest = { showDropdown = false }) {+ accounts.forEach { account ->+ val blocked = restriction?.blocks(account.name, account.type) == true+ DropdownMenuItem(+ text = {+ Column {+ Text(account.name.ifEmpty { onDevice })+ if (blocked && blockedReason != null) {+ Text(blockedReason, style = MaterialTheme.typography.bodySmall)+ }+ }+ },+ onClick = {+ onSelect(account)+ showDropdown = false+ },+ enabled = !blocked,+ )+ }+ }+ }+}
contacts/src/main/java/com/vayunmathur/contacts/ui/EditContactAccountSection.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/ui/EditContactAccountSection.kt b/contacts/src/main/java/com/vayunmathur/contacts/ui/EditContactAccountSection.ktindex ee56e64e04..71b1a5f8c6 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/ui/EditContactAccountSection.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/ui/EditContactAccountSection.kt@@ -11,6 +11,7 @@ import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import com.vayunmathur.contacts.R+import com.vayunmathur.contacts.data.NewContactRestriction import com.vayunmathur.contacts.util.ContactAccount import com.vayunmathur.contacts.util.ContactViewModel import com.vayunmathur.library.ui.DropdownMenu@@ -30,19 +31,25 @@ fun EditContactAccountSection( draft: ContactViewModel.ContactDraft, accounts: List<ContactAccount>, simLabels: Map<String, String> = emptyMap(),+ restriction: NewContactRestriction? = null, onAccountChange: (String, String) -> Unit, ) {- AccountChooser(draft.accountName, draft.accountType, accounts, simLabels) { name, type ->+ AccountChooser(draft.accountName, draft.accountType, accounts, simLabels, restriction) { name, type -> onAccountChange(name, type) } } +/**+ * Accounts [restriction] blocks (Android 16+ with a cloud default account, #916) are listed+ * disabled with the reason, since the provider would refuse a new contact there.+ */ @Composable internal fun AccountChooser( accountName: String, accountType: String, accounts: List<ContactAccount>, simLabels: Map<String, String> = emptyMap(),+ restriction: NewContactRestriction? = null, onAccountChange: (String, String) -> Unit ) { var expanded by remember { mutableStateOf(false) }@@ -54,6 +61,10 @@ internal fun AccountChooser( accountName.isNotEmpty() -> accountName else -> onDevice }+ val blockedReason = restriction?.let {+ stringResource(R.string.account_unavailable_cloud_default, it.cloudAccount.name)+ }+ val currentBlocked = restriction?.blocks(accountName, accountType) == true Box(Modifier.fillMaxWidth()) { OutlinedTextField( value = displayValue,@@ -62,6 +73,10 @@ internal fun AccountChooser( label = { Text(stringResource(R.string.account)) }, singleLine = true, modifier = Modifier.fillMaxWidth(),+ isError = currentBlocked,+ supportingText = if (currentBlocked && blockedReason != null) {+ { Text(blockedReason) }+ } else null, trailingIcon = { IconButton(onClick = { expanded = true }) { IconArrowDropDown()@@ -70,6 +85,7 @@ internal fun AccountChooser( ) DropdownMenu(expanded, { expanded = false }) { if (accounts.none { it.name.isBlank() && it.type.isBlank() }) {+ val blocked = restriction?.blocks("", "") == true SelectableDropdownMenuItem( selected = accountName.isEmpty() && accountType.isEmpty(), onClick = {@@ -77,18 +93,27 @@ internal fun AccountChooser( expanded = false }, text = { Text(onDevice) },+ enabled = !blocked,+ supportingText = if (blocked && blockedReason != null) {+ { Text(blockedReason) }+ } else null, selectedLeadingIcon = { com.vayunmathur.library.ui.IconCheck() }, ) } accounts.forEach { account -> val key = "${account.type}|${account.name}" val label = simLabels[key] ?: account.name.ifEmpty { onDevice }+ val blocked = restriction?.blocks(account.name, account.type) == true SelectableDropdownMenuItem( selected = currentKey == key, onClick = { onAccountChange(account.name, account.type) expanded = false },+ enabled = !blocked,+ supportingText = if (blocked && blockedReason != null) {+ { Text(blockedReason) }+ } else null, text = { Text(when { simLabels.containsKey(key) -> label account.type.isBlank() -> label
contacts/src/main/java/com/vayunmathur/contacts/ui/EditContactPage.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/ui/EditContactPage.kt b/contacts/src/main/java/com/vayunmathur/contacts/ui/EditContactPage.ktindex a19fde2a1a..68a4d41655 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/ui/EditContactPage.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/ui/EditContactPage.kt@@ -42,6 +42,7 @@ import com.vayunmathur.contacts.data.SIM_ACCOUNT_TYPE import com.vayunmathur.contacts.util.ContactViewModel import com.vayunmathur.contacts.util.initEditDraft import com.vayunmathur.contacts.util.loadLastSelectedAccount+import com.vayunmathur.contacts.util.refreshNewContactRestriction import com.vayunmathur.contacts.util.saveEditDraft import com.vayunmathur.contacts.util.setLastSelectedAccount import com.vayunmathur.contacts.util.updateEditDraft@@ -65,6 +66,9 @@ fun EditContactPage(backStack: NavBackStack<Route>, viewModel: ContactViewModel, // this runs falls back to on-device despite the stored choice. if (isNewContact) { viewModel.loadLastSelectedAccount()+ // Android 16+: a cloud default account refuses new device contacts, so the+ // draft must not be seeded with On-Device (#916).+ viewModel.refreshNewContactRestriction() } viewModel.initEditDraft( contactId = contactId,@@ -74,6 +78,7 @@ fun EditContactPage(backStack: NavBackStack<Route>, viewModel: ContactViewModel, val draft by viewModel.editDraft.collectAsStateWithLifecycle() val accounts by viewModel.accounts.collectAsStateWithLifecycle() val simLabels by viewModel.simAccountLabels.collectAsStateWithLifecycle()+ val restriction by viewModel.newContactRestriction.collectAsStateWithLifecycle() val pickMedia = rememberLauncherForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri -> if (uri != null) {@@ -139,7 +144,7 @@ fun EditContactPage(backStack: NavBackStack<Route>, viewModel: ContactViewModel, // Account chooser for new contacts (SIM accounts appear here as normal accounts) if (isNewContact) {- EditContactAccountSection(currentDraft, accounts, simLabels) { name, type ->+ EditContactAccountSection(currentDraft, accounts, simLabels, restriction) { name, type -> viewModel.updateEditDraft { it.copy(accountName = name, accountType = type) } viewModel.setLastSelectedAccount(name, type) }
contacts/src/main/java/com/vayunmathur/contacts/ui/ImportVcfScreen.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/ui/ImportVcfScreen.kt b/contacts/src/main/java/com/vayunmathur/contacts/ui/ImportVcfScreen.ktindex f978db154a..4f0e435670 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/ui/ImportVcfScreen.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/ui/ImportVcfScreen.kt@@ -28,19 +28,16 @@ import com.vayunmathur.library.ui.AppScaffold import com.vayunmathur.library.ui.Card import com.vayunmathur.library.ui.CardDefaults import com.vayunmathur.library.ui.CircularProgressIndicator-import com.vayunmathur.library.ui.DropdownMenu-import com.vayunmathur.library.ui.DropdownMenuItem import com.vayunmathur.library.ui.EmptyState import com.vayunmathur.library.ui.ExperimentalMaterial3Api import com.vayunmathur.library.ui.FloatingActionButton-import com.vayunmathur.library.ui.IconArrowDropDown import com.vayunmathur.library.ui.IconSave-import com.vayunmathur.library.ui.ListItem import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.OutlinedTextField import com.vayunmathur.library.ui.RadioButton import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.library.ui.rememberMessenger import com.vayunmathur.library.ui.isCompactHeight import com.vayunmathur.library.ui.isExpandedWidth import androidx.compose.ui.Alignment@@ -74,7 +71,9 @@ fun ImportVcfScreen( val uriList = remember(uris) { uris.map { it.toUri() } } val parsedContacts by viewModel.parsedVcfContacts.collectAsStateWithLifecycle() val accounts by viewModel.accounts.collectAsStateWithLifecycle()+ val restriction by viewModel.newContactRestriction.collectAsStateWithLifecycle() val scope = rememberCoroutineScope()+ val messenger = rememberMessenger() var importMode by remember { mutableStateOf(ImportMode.Existing) } var selectedAccount by remember { mutableStateOf<ContactAccount?>(null) }@@ -91,16 +90,25 @@ fun ImportVcfScreen( onDispose { viewModel.clearParsedVcf() } } - // Auto-select first account- LaunchedEffect(accounts) {- if (selectedAccount == null) {- selectedAccount = accounts.firstOrNull()+ // Auto-select the first account that can take new contacts (Android 16+ refuses the+ // device account while the default account is a cloud account, #916).+ LaunchedEffect(accounts, restriction) {+ val current = selectedAccount+ if (current == null || restriction?.blocks(current.name, current.type) == true) {+ selectedAccount = accounts.firstOrNull { restriction?.blocks(it.name, it.type) != true } } }+ // A refused import stays on this screen with the reason so another account can be picked.+ val onImportDone: (String?) -> Unit = { error ->+ isImporting = false+ if (error != null) messenger.show(error) else backStack.pop()+ } val contacts = parsedContacts+ val selectedBlocked = selectedAccount?.let { restriction?.blocks(it.name, it.type) } == true val canImport = when (importMode) {- ImportMode.Existing -> selectedAccount != null && contacts?.isNotEmpty() == true && !isImporting+ ImportMode.Existing -> selectedAccount != null && !selectedBlocked &&+ contacts?.isNotEmpty() == true && !isImporting ImportMode.New -> newAccountName.isNotBlank() && contacts?.isNotEmpty() == true && !isImporting } @@ -116,10 +124,7 @@ fun ImportVcfScreen( when (importMode) { ImportMode.Existing -> { val account = selectedAccount ?: return@launch- viewModel.importVcfContacts(cnts, account.name, account.type) {- isImporting = false- backStack.pop()- }+ viewModel.importVcfContacts(cnts, account.name, account.type, onImportDone) } ImportMode.New -> { // Create account, then import@@ -127,10 +132,9 @@ fun ImportVcfScreen( name = newAccountName, type = "com.vayunmathur.contacts.local", onComplete = {- viewModel.importVcfContacts(cnts, newAccountName, "com.vayunmathur.contacts.local") {- isImporting = false- backStack.pop()- }+ viewModel.importVcfContacts(+ cnts, newAccountName, "com.vayunmathur.contacts.local", onImportDone+ ) } ) }@@ -243,6 +247,7 @@ fun ImportVcfScreen( AccountSelectorDropdown( accounts = accounts, selectedAccount = selectedAccount,+ restriction = restriction, onSelect = { selectedAccount = it }, modifier = Modifier.fillMaxWidth() )@@ -279,35 +284,6 @@ fun ImportVcfScreen( } } -@Composable-fun AccountSelectorDropdown(- accounts: List<ContactAccount>,- selectedAccount: ContactAccount?,- modifier: Modifier = Modifier,- onSelect: (ContactAccount) -> Unit,-) {- var showDropdown by remember { mutableStateOf(false) }-- Box(modifier) {- ListItem(- content = { Text(selectedAccount?.name?.ifEmpty { stringResource(R.string.on_device) } ?: stringResource(R.string.select_account)) },- trailingContent = { IconArrowDropDown() },- modifier = Modifier.clickable { showDropdown = true },- )- DropdownMenu(expanded = showDropdown, onDismissRequest = { showDropdown = false }) {- accounts.forEach { account ->- DropdownMenuItem(- text = { Text(account.name.ifEmpty { stringResource(R.string.on_device) }) },- onClick = {- onSelect(account)- showDropdown = false- },- )- }- }- }-}- @Composable fun ContactCard(contact: Contact) { Card(
contacts/src/main/java/com/vayunmathur/contacts/ui/dialogs/MoveDialogHost.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/ui/dialogs/MoveDialogHost.kt b/contacts/src/main/java/com/vayunmathur/contacts/ui/dialogs/MoveDialogHost.ktindex 8b368701ac..a0d98386b6 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/ui/dialogs/MoveDialogHost.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/ui/dialogs/MoveDialogHost.kt@@ -34,6 +34,7 @@ fun MoveDialogHost( val accounts by viewModel.accounts.collectAsStateWithLifecycle() val simLabels by viewModel.simAccountLabels.collectAsStateWithLifecycle() val contacts by viewModel.contacts.collectAsStateWithLifecycle()+ val restriction by viewModel.newContactRestriction.collectAsStateWithLifecycle() val toMove = remember(contacts, contactIds) { contacts.filter { it.id in contactIds }@@ -58,12 +59,15 @@ fun MoveDialogHost( simLabels = simLabels, selectedAccount = selectedAccount, simLossLabels = simLoss.map { it.localized() },+ restriction = restriction, onSelectAccount = { selectedAccount = it }, onClearSelection = { selectedAccount = null }, onConfirm = { val dest = selectedAccount ?: return@MoveToAccountDialog val ids = toMove.map { it.id }.ifEmpty { contactIds }- viewModel.transferContacts(ids, dest.name, dest.type) { moved, failed, _ ->+ // Set when the provider refused the destination (#916); explains the failure.+ var rejection: String? = null+ viewModel.transferContacts(ids, dest.name, dest.type, onRejected = { rejection = it }) { moved, failed, _ -> // Resources (not composable stringResource): this callback runs // outside composition on the main thread. val message = when {@@ -71,7 +75,7 @@ fun MoveDialogHost( context.resources.getQuantityString(R.plurals.move_success, moved, moved) moved > 0 -> context.getString(R.string.move_partial_failure, moved, failed)- else -> context.getString(R.string.move_failed)+ else -> rejection ?: context.getString(R.string.move_failed) } messenger.show(message) if (moved > 0) onTransferred()
contacts/src/main/java/com/vayunmathur/contacts/ui/dialogs/MoveToAccountDialog.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/ui/dialogs/MoveToAccountDialog.kt b/contacts/src/main/java/com/vayunmathur/contacts/ui/dialogs/MoveToAccountDialog.ktindex e18d4beecd..d393b538e1 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/ui/dialogs/MoveToAccountDialog.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/ui/dialogs/MoveToAccountDialog.kt@@ -13,6 +13,7 @@ import androidx.compose.ui.res.pluralStringResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.vayunmathur.contacts.R+import com.vayunmathur.contacts.data.NewContactRestriction import com.vayunmathur.contacts.data.isSimAccountType import com.vayunmathur.contacts.util.ContactAccount import com.vayunmathur.library.ui.AlertDialog@@ -26,8 +27,9 @@ import com.vayunmathur.library.ui.R as UiR /** * Stateless move-to-account dialog: account picker first, then a SIM data-loss * warning when the destination is a SIM account that would drop fields.- * Same-account destinations are shown disabled. Dropped-field labels come from- * [simLossLabels], resolved by the caller from strings.+ * Same-account destinations are shown disabled, as are destinations [restriction]+ * blocks (Android 16+ with a cloud default account, #916), with the reason. Dropped-field+ * labels come from [simLossLabels], resolved by the caller from strings. */ @Composable fun MoveToAccountDialog(@@ -37,6 +39,7 @@ fun MoveToAccountDialog( simLabels: Map<String, String> = emptyMap(), selectedAccount: ContactAccount?, simLossLabels: List<String> = emptyList(),+ restriction: NewContactRestriction? = null, onSelectAccount: (ContactAccount) -> Unit, onClearSelection: () -> Unit, onConfirm: () -> Unit,@@ -71,6 +74,10 @@ fun MoveToAccountDialog( ) return }+ val blockedReason = restriction?.let {+ stringResource(R.string.account_unavailable_cloud_default, it.cloudAccount.name)+ }+ fun isBlocked(account: ContactAccount) = restriction?.blocks(account.name, account.type) == true AlertDialog( onDismissRequest = onDismiss, title = { Text(stringResource(R.string.move_to_account)) },@@ -83,11 +90,13 @@ fun MoveToAccountDialog( ) LazyColumn(Modifier.fillMaxWidth()) { items(accounts, key = { "${it.type}|${it.name}" }) { account ->+ val blocked = isBlocked(account) DestinationRow( account = account, simLabels = simLabels, selected = destination == account,- enabled = account !in sourceAccounts,+ enabled = account !in sourceAccounts && !blocked,+ disabledReason = blockedReason.takeIf { blocked }, onClick = { onSelectAccount(account) }, ) }@@ -96,7 +105,7 @@ fun MoveToAccountDialog( }, confirmButton = { TextButton(- enabled = destination != null && destination !in sourceAccounts,+ enabled = destination != null && destination !in sourceAccounts && !isBlocked(destination), onClick = onConfirm, ) { Text(stringResource(R.string.move))@@ -116,12 +125,14 @@ private fun DestinationRow( simLabels: Map<String, String>, selected: Boolean, enabled: Boolean,+ disabledReason: String?, onClick: () -> Unit, ) { val key = "${account.type}|${account.name}" val onDevice = stringResource(R.string.on_device) val label = simLabels[key] ?: account.name.ifEmpty { onDevice } val supporting = when {+ disabledReason != null -> disabledReason simLabels.containsKey(key) -> null account.type.isNotBlank() -> account.type else -> null
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 ed188d3104..5fbd51bc74 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModel.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModel.kt@@ -25,10 +25,12 @@ import com.vayunmathur.contacts.data.ContactDetail import com.vayunmathur.contacts.data.ContactDetails import com.vayunmathur.contacts.data.ContactGroup import com.vayunmathur.contacts.data.ContactPrefill+import com.vayunmathur.contacts.data.DefaultAccountSource import com.vayunmathur.contacts.data.Email import com.vayunmathur.contacts.data.Event import com.vayunmathur.contacts.data.GroupMembership import com.vayunmathur.contacts.data.Name+import com.vayunmathur.contacts.data.NewContactRestriction import com.vayunmathur.contacts.data.Nickname import com.vayunmathur.contacts.data.Note import com.vayunmathur.contacts.data.Organization@@ -36,9 +38,11 @@ import com.vayunmathur.contacts.data.PhoneNumber import com.vayunmathur.contacts.data.Photo import com.vayunmathur.contacts.data.PrefillValue import com.vayunmathur.contacts.data.SIM_ACCOUNT_TYPE+import com.vayunmathur.contacts.data.SaveOutcome import com.vayunmathur.contacts.data.LOCAL_ACCOUNT_TYPE import com.vayunmathur.contacts.data.SimContact import com.vayunmathur.contacts.data.SimContactsDataSource+import com.vayunmathur.contacts.data.SystemDefaultAccountSource import com.vayunmathur.contacts.data.isSimAccountType import com.vayunmathur.contacts.data.isDefaultLocalAccount import com.vayunmathur.contacts.data.isLocalAccountType@@ -84,7 +88,13 @@ private const val SUBSCRIBE_TIMEOUT = 5_000L /** Debounce for coalesced system-contact change notifications. */ private const val SYNC_DEBOUNCE_MILLIS = 300L -class ContactViewModel(application: Application) : AndroidViewModel(application), ContactsActions {+class ContactViewModel internal constructor(+ application: Application,+ /** Where the provider's default-account facts come from (#916); tests pass a fake. */+ internal val defaultAccountSource: DefaultAccountSource,+) : AndroidViewModel(application), ContactsActions {++ constructor(application: Application) : this(application, SystemDefaultAccountSource(application)) internal val dataStore = DataStoreUtils.getInstance(application) @@ -220,6 +230,11 @@ class ContactViewModel(application: Application) : AndroidViewModel(application) internal val lastSelectedAccountState = MutableStateFlow<ContactAccount?>(null) + // Android 16+: accounts that cannot take new contacts while the system default+ // account is a cloud account (#916). null = no restriction.+ internal val newContactRestrictionState = MutableStateFlow<NewContactRestriction?>(null)+ val newContactRestriction: StateFlow<NewContactRestriction?> = newContactRestrictionState.asStateFlow()+ // Parsed-VCF state for the import screen. null = not yet parsed (or cleared); // empty list = parsed and found nothing; non-empty = parsed contacts ready to import. internal val parsedVcfContactsState = MutableStateFlow<List<Contact>?>(null)@@ -496,12 +511,8 @@ class ContactViewModel(application: Application) : AndroidViewModel(application) } /** Writes [contact] to the SIM or the contacts provider. Returns false if the write failed. */- internal suspend fun persistContact(contact: com.vayunmathur.contacts.data.Contact): Boolean {- if (isSimAccountType(contact.accountType)) {- return persistSimContact(contact)- }- return persistProviderContact(contact)- }+ internal suspend fun persistContact(contact: com.vayunmathur.contacts.data.Contact): Boolean =+ persistContactWithOutcome(contact) == SaveOutcome.SAVED // --------------------------------------------------------------------- // Base64 photo decode cache.
contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModelAccounts.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModelAccounts.kt b/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModelAccounts.ktindex 10b1e95466..7f2fd659c2 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModelAccounts.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModelAccounts.kt@@ -5,8 +5,10 @@ import android.content.ContentProviderOperation import android.provider.ContactsContract import com.vayunmathur.library.log.Log import androidx.lifecycle.viewModelScope+import com.vayunmathur.contacts.R import com.vayunmathur.contacts.data.Contact import com.vayunmathur.contacts.data.LOCAL_ACCOUNT_TYPE+import com.vayunmathur.contacts.data.NewContactAccountPolicy import com.vayunmathur.contacts.data.SIM_ACCOUNT_TYPE import com.vayunmathur.contacts.data.SimContactsDataSource import com.vayunmathur.contacts.data.isDefaultLocalAccount@@ -88,7 +90,50 @@ internal suspend fun ContactViewModel.loadAccountsInternal() { val savedAccounts = loadSavedAccounts() migrateHiddenAccountKeys() refreshSimAccounts(app)- sortAccountsIntoState((accountSet + savedAccounts + simAccountsOf(app)).toList())+ val restriction = NewContactAccountPolicy.resolve(defaultAccountSource)+ newContactRestrictionState.value = restriction+ // The cloud default is where new contacts now go, so offer it even when it holds+ // no contacts yet (it would otherwise be missing from every account picker).+ val cloud = restriction?.cloudAccount?.let { ContactAccount(it.name, it.type) }+ sortAccountsIntoState((accountSet + savedAccounts + simAccountsOf(app) + listOfNotNull(cloud)).toList())+}++/**+ * Re-reads the system default account for new contacts (Android 16+, #916) so the+ * pickers and new drafts reflect a change made in system settings since the last sync.+ */+internal suspend fun ContactViewModel.refreshNewContactRestriction() {+ newContactRestrictionState.value = withContext(Dispatchers.IO) {+ NewContactAccountPolicy.resolve(defaultAccountSource)+ }+}++/**+ * User-facing reason a write was refused because the system default account for new+ * contacts is a cloud account (#916). Refreshes the restriction first, so the pickers+ * grey out the refused accounts and the message names the current default.+ */+internal suspend fun ContactViewModel.cloudDefaultRejectionMessage(): String {+ refreshNewContactRestriction()+ val app = getApplication<Application>()+ val cloud = newContactRestrictionState.value?.cloudAccount?.name+ return if (cloud.isNullOrBlank()) {+ app.getString(R.string.cloud_default_rejected_generic)+ } else {+ app.getString(R.string.cloud_default_rejected, cloud)+ }+}++/**+ * Account a new contact starts in: the last one picked, unless the provider would refuse+ * new contacts there (device or provider SIM account while the system default is a cloud+ * account, #916), in which case the cloud default account.+ */+internal fun ContactViewModel.newContactDefaultAccount(): ContactAccount {+ val last = lastSelectedAccountState.value ?: ContactAccount("", "")+ val restriction = newContactRestrictionState.value ?: return last+ if (!restriction.blocks(last.name, last.type)) return last+ return ContactAccount(restriction.cloudAccount.name, restriction.cloudAccount.type) } private suspend fun ContactViewModel.queryProviderAccounts(
contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModelDraft.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModelDraft.kt b/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModelDraft.ktindex b86c546774..ec7972bb40 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModelDraft.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModelDraft.kt@@ -30,6 +30,7 @@ import com.vayunmathur.contacts.data.Organization import com.vayunmathur.contacts.data.PhoneNumber import com.vayunmathur.contacts.data.Photo import com.vayunmathur.contacts.data.PrefillValue+import com.vayunmathur.contacts.data.SaveOutcome import com.vayunmathur.contacts.data.SimContactsDataSource import com.vayunmathur.contacts.data.isSimAccountType import kotlinx.coroutines.Dispatchers@@ -110,12 +111,13 @@ private fun ContactViewModel.ContactDraft.withListFields( ) // An existing contact keeps its own account even when that is on-device (null); only a new-// contact falls back to the last account picked in the add screen.+// contact falls back to the last account picked in the add screen, or to the cloud default+// when the provider would refuse that account (#916). private fun ContactViewModel.draftAccountName(contact: Contact?): String =- if (contact != null) contact.accountName.orEmpty() else lastSelectedAccountState.value?.name.orEmpty()+ if (contact != null) contact.accountName.orEmpty() else newContactDefaultAccount().name private fun ContactViewModel.draftAccountType(contact: Contact?): String =- if (contact != null) contact.accountType.orEmpty() else lastSelectedAccountState.value?.type.orEmpty()+ if (contact != null) contact.accountType.orEmpty() else newContactDefaultAccount().type private fun ContactViewModel.draftPhoneNumbers( details: ContactDetails?,@@ -304,14 +306,17 @@ fun ContactViewModel.saveEditDraft(onResult: ((Boolean, String?, Long?) -> Unit) } val newContact = buildContactFromDraft(draft) viewModelScope.launch {- val ok = withContext(Dispatchers.IO) { persistContact(newContact) }+ val outcome = withContext(Dispatchers.IO) { persistContactWithOutcome(newContact) }+ val ok = outcome == SaveOutcome.SAVED val savedId = when { !ok -> null isSimAccountType(newContact.accountType) -> findSavedSimContactId(newContact) else -> newContact.id.takeIf { it != 0L } } if (ok) clearEditDraft()- onResult?.invoke(ok, null, savedId)+ // A refused account gets its reason (#916); other failures keep the caller's generic text.+ val error = if (outcome == SaveOutcome.REJECTED_CLOUD_DEFAULT) cloudDefaultRejectionMessage() else null+ onResult?.invoke(ok, error, savedId) } }
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 ec12a5ce7d..279381e638 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModelSim.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModelSim.kt@@ -5,6 +5,7 @@ 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.SaveOutcome import com.vayunmathur.contacts.data.SimContactsDataSource import com.vayunmathur.contacts.data.isSimAccountType import kotlinx.coroutines.delay@@ -123,9 +124,22 @@ internal fun ContactViewModel.scheduleSimConvergenceSync() { /** Delay before the SIM convergence re-sync; hoisted so tests can reference it. */ internal const val SIM_CONVERGENCE_DELAY_MILLIS = 2_000L +/**+ * Writes [contact] to the SIM or the contacts provider, telling a provider refusal of+ * the target account (#916) apart from other failures.+ */+internal suspend fun ContactViewModel.persistContactWithOutcome(+ contact: com.vayunmathur.contacts.data.Contact+): SaveOutcome {+ if (isSimAccountType(contact.accountType)) {+ return if (persistSimContact(contact)) SaveOutcome.SAVED else SaveOutcome.FAILED+ }+ return persistProviderContact(contact)+}+ internal suspend fun ContactViewModel.persistProviderContact( contact: com.vayunmathur.contacts.data.Contact-): Boolean {+): SaveOutcome { val app = getApplication<Application>() val contactId = contact.id val details = contact.details@@ -139,14 +153,14 @@ internal suspend fun ContactViewModel.persistProviderContact( } ?: contacts.value.find { it.id == contactId }?.details ?: allContactsState.value.find { it.id == contactId }?.details ?: com.vayunmathur.contacts.data.ContactDetails.empty()- val ok = contact.save(app, details, oldDetails)- if (ok) {+ val outcome = contact.saveWithOutcome(app, details, oldDetails)+ if (outcome == SaveOutcome.SAVED) { // The provider observer re-syncs on its own debounce, but an edit must be // visible immediately - refresh now so the details page and list update // without waiting for the observer round-trip. syncFromSystem() }- return ok+ return outcome } fun ContactViewModel.simDisplayLabel(account: ContactAccount): String? =
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 39e92cdad4..3933f44d63 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModelTransfer.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModelTransfer.kt@@ -4,6 +4,7 @@ import android.app.Application import androidx.lifecycle.viewModelScope import com.vayunmathur.contacts.data.Contact import com.vayunmathur.contacts.data.ContactDetails+import com.vayunmathur.contacts.data.SaveOutcome import com.vayunmathur.contacts.data.SimContactsDataSource import com.vayunmathur.contacts.data.isSimAccountType import com.vayunmathur.library.log.Log@@ -28,7 +29,13 @@ enum class SimDroppedField { FAVORITE, } -data class TransferResult(val moved: Int, val failed: Int, val groupsDropped: Boolean)+data class TransferResult(+ val moved: Int,+ val failed: Int,+ val groupsDropped: Boolean,+ /** True when the provider refused the destination account (#916). */+ val rejectedByCloudDefault: Boolean = false,+) /** * Pure helper: which fields of [contact] would not survive a move to a SIM@@ -56,19 +63,26 @@ fun computeSimLoss(contact: Contact): List<SimDroppedField> { * MOVEs [contactIds] to ([destName], [destType]): copies each contact into the * destination with fresh data-row ids, then deletes the source only when the * insert succeeded. Sequential so SIM ADN insert ordering is deterministic.- * [onResult] is invoked on the main thread.+ * [onResult] is invoked on the main thread. When the provider refused the destination+ * because the system default account is a cloud account (#916), [onRejected] receives+ * the user-facing reason first. */ fun ContactViewModel.transferContacts( contactIds: List<Long>, destName: String, destType: String,+ onRejected: ((message: String) -> Unit)? = null, onResult: ((moved: Int, failed: Int, groupsDropped: Boolean) -> Unit)? = null, ) { viewModelScope.launch { val result = withContext(Dispatchers.IO) { transferContactsInternal(contactIds, destName, destType) } loadAccounts() loadContacts()- withContext(Dispatchers.Main) { onResult?.invoke(result.moved, result.failed, result.groupsDropped) }+ val rejection = if (result.rejectedByCloudDefault) cloudDefaultRejectionMessage() else null+ withContext(Dispatchers.Main) {+ rejection?.let { onRejected?.invoke(it) }+ onResult?.invoke(result.moved, result.failed, result.groupsDropped)+ } } } @@ -80,6 +94,7 @@ private suspend fun ContactViewModel.transferContactsInternal( var moved = 0 var failed = 0 var groupsDropped = false+ var rejected = false for (id in contactIds) { val outcome = moveContactById(id, destName, destType) if (outcome == null) continue@@ -88,9 +103,10 @@ private suspend fun ContactViewModel.transferContactsInternal( if (outcome.groupsDropped) groupsDropped = true } else { failed+++ if (outcome.rejected) rejected = true } }- return TransferResult(moved, failed, groupsDropped)+ return TransferResult(moved, failed, groupsDropped, rejected) } /** Moves one contact by id. Null when the destination equals the source (skipped, not failed). */@@ -107,7 +123,7 @@ private suspend fun ContactViewModel.moveContactById( private fun isSameAccount(contact: Contact, destName: String, destType: String): Boolean = (contact.accountType.orEmpty() == destType) && (contact.accountName.orEmpty() == destName) -private data class MoveOutcome(val moved: Boolean, val groupsDropped: Boolean)+private data class MoveOutcome(val moved: Boolean, val groupsDropped: Boolean, val rejected: Boolean = false) // Broad catch is deliberate: transfer crosses provider + SIM ADN writes and // must report failure via the outcome rather than crashing the caller.@@ -126,7 +142,7 @@ private suspend fun ContactViewModel.moveOneContact( fromSim && !toSim -> copySimToProvider(contact, destName, destType) else -> copySimToSim(contact, destName) }- if (!inserted.ok) return MoveOutcome(false, false)+ if (!inserted.ok) return MoveOutcome(false, false, inserted.rejected) deleteTransferSource(contact) return MoveOutcome(true, inserted.groupsDropped) } catch (e: Exception) {@@ -135,7 +151,10 @@ private suspend fun ContactViewModel.moveOneContact( } } -private data class InsertOutcome(val ok: Boolean, val groupsDropped: Boolean)+private data class InsertOutcome(val ok: Boolean, val groupsDropped: Boolean, val rejected: Boolean = false)++/** Refusal of the destination account (#916): a retry without groups cannot help. */+private val REJECTED_INSERT = InsertOutcome(ok = false, groupsDropped = false, rejected = true) private suspend fun ContactViewModel.copyProviderToProvider( contact: Contact,@@ -144,8 +163,10 @@ private suspend fun ContactViewModel.copyProviderToProvider( ): InsertOutcome { val app = getApplication<Application>() val withGroups = contact.zeroedCopy(destName, destType)- if (withGroups.save(app, withGroups.details, ContactDetails.empty())) {- return InsertOutcome(true, false)+ when (withGroups.saveWithOutcome(app, withGroups.details, ContactDetails.empty())) {+ SaveOutcome.SAVED -> return InsertOutcome(true, false)+ SaveOutcome.REJECTED_CLOUD_DEFAULT -> return REJECTED_INSERT+ SaveOutcome.FAILED -> Unit } // Fallback: group row ids may not exist for the destination; retry without them. if (withGroups.details.groups.isEmpty()) return InsertOutcome(false, false)@@ -180,7 +201,9 @@ private suspend fun ContactViewModel.copySimToProvider( // Never leak the negative synthetic SIM id into the provider insert. val fresh = contact.zeroedCopy(destName, destType) val withoutGroups = fresh.copy(details = fresh.details.copy(groups = emptyList()))- val ok = withoutGroups.save(app, withoutGroups.details, ContactDetails.empty())+ val outcome = withoutGroups.saveWithOutcome(app, withoutGroups.details, ContactDetails.empty())+ if (outcome == SaveOutcome.REJECTED_CLOUD_DEFAULT) return REJECTED_INSERT+ val ok = outcome == SaveOutcome.SAVED return InsertOutcome(ok, contact.details.groups.isNotEmpty() && ok) }
contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModelVcf.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModelVcf.kt b/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModelVcf.ktindex 95be75cb8b..1c1f5694fb 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModelVcf.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModelVcf.kt@@ -4,6 +4,7 @@ import android.app.Application import androidx.lifecycle.viewModelScope import com.vayunmathur.contacts.data.Contact import com.vayunmathur.contacts.data.ContactDetails+import com.vayunmathur.contacts.data.SaveOutcome import com.vayunmathur.contacts.data.SimContactsDataSource import com.vayunmathur.contacts.data.isSimAccountType import com.vayunmathur.library.log.Log@@ -132,17 +133,18 @@ fun ContactViewModel.clearParsedVcf() { /** * Bulk-imports the previously parsed [contacts] into the account with [accountName] and [accountType].- * Runs off the main thread; invokes [onDone] on the main thread when complete (or on failure).+ * Runs off the main thread; invokes [onDone] on the main thread when complete (or on failure),+ * with a user-facing error when the provider refused the target account (#916), else null. */ fun ContactViewModel.importVcfContacts( contacts: List<Contact>, accountName: String, accountType: String,- onDone: () -> Unit = {},+ onDone: (error: String?) -> Unit = {}, ) { val app = getApplication<Application>() viewModelScope.launch {- withContext(Dispatchers.IO) {+ val rejected = withContext(Dispatchers.IO) { // Broad catch is deliberate: bulk import crosses the contacts // provider, SIM ADN and VCF parsing, and must report failure // via onDone rather than crashing the import screen.@@ -152,15 +154,17 @@ fun ContactViewModel.importVcfContacts( importVcfToSim(app, contacts, accountName) // Refresh unified list withContext(Dispatchers.Main) { loadContacts() }+ false } else { importVcfToProvider(app, contacts, accountName, accountType) } } catch (e: Exception) { Log.error("ContactViewModel", "Error importing contacts", e)+ false } } loadContacts()- onDone()+ onDone(if (rejected) cloudDefaultRejectionMessage() else null) } } @@ -183,17 +187,24 @@ private suspend fun ContactViewModel.importVcfToSim( } } -private fun ContactViewModel.importVcfToProvider(+/**+ * Saves each contact into the account. Returns true when the provider refused the account+ * because the system default is a cloud account (#916); every contact targets the same+ * account, so the first refusal stops the import instead of failing each one in turn.+ */+private fun importVcfToProvider( app: Application, contacts: List<Contact>, accountName: String, accountType: String,-) {- contacts.forEach { contact ->+): Boolean {+ for (contact in contacts) { val toSave = contact.copy( accountName = accountName, accountType = accountType )- toSave.save(app, toSave.details, ContactDetails.empty())+ val outcome = toSave.saveWithOutcome(app, toSave.details, ContactDetails.empty())+ if (outcome == SaveOutcome.REJECTED_CLOUD_DEFAULT) return true }+ return false }
contacts/src/main/res/values/strings.xml
diff --git a/contacts/src/main/res/values/strings.xml b/contacts/src/main/res/values/strings.xmlindex 1d3525c2ca..3791675ea8 100644--- a/contacts/src/main/res/values/strings.xml+++ b/contacts/src/main/res/values/strings.xml@@ -251,6 +251,12 @@ <!-- Storage label on a contact row and in the account picker, naming the SIM slot a contact lives on. %1$d is the 1-based slot number. --> <string name="sim_slot_label">SIM %1$d</string> <string name="save_failed">Save failed</string>+ <!-- Android 16+: the system refuses new contacts in the device (On-Device) or SIM account while the default account for new contacts is a cloud account. Shown in the editor, the import screen and the move dialog when a save is refused. %1$s is the default account, e.g. an email address. -->+ <string name="cloud_default_rejected">Android won\'t add contacts to this account while your default contacts account is <xliff:g id="account" example="[email protected]">%1$s</xliff:g>. Choose another account, or change the default in system Contacts settings.</string>+ <!-- Same as cloud_default_rejected, when the default account's name is unknown -->+ <string name="cloud_default_rejected_generic">Android won\'t add contacts to this account while your default contacts account is a cloud account. Choose another account, or change the default in system Contacts settings.</string>+ <!-- Account pickers: supporting text under a disabled On-Device/SIM account (see cloud_default_rejected). %1$s is the default account, e.g. an email address. -->+ <string name="account_unavailable_cloud_default">Unavailable while your default contacts account is <xliff:g id="account" example="[email protected]">%1$s</xliff:g>. Change it in system Contacts settings.</string> <string name="importing">Importing…</string> <!-- Empty states -->
contacts/src/test/java/com/vayunmathur/contacts/pure/NewContactAccountPolicyTest.kt
diff --git a/contacts/src/test/java/com/vayunmathur/contacts/pure/NewContactAccountPolicyTest.kt b/contacts/src/test/java/com/vayunmathur/contacts/pure/NewContactAccountPolicyTest.ktnew file mode 100644index 0000000000..3784e20ff2--- /dev/null+++ b/contacts/src/test/java/com/vayunmathur/contacts/pure/NewContactAccountPolicyTest.kt@@ -0,0 +1,115 @@+package com.vayunmathur.contacts.pure++import com.vayunmathur.contacts.data.DefaultAccountKind+import com.vayunmathur.contacts.data.DefaultAccountSnapshot+import com.vayunmathur.contacts.data.DefaultAccountSource+import com.vayunmathur.contacts.data.LOCAL_ACCOUNT_TYPE+import com.vayunmathur.contacts.data.NewContactAccountPolicy+import com.vayunmathur.contacts.data.ProviderAccount+import com.vayunmathur.contacts.data.SIM_ACCOUNT_TYPE+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * #916: on Android 16+ the contacts provider refuses new contacts in the device-local+ * and provider SIM accounts while the default account for new contacts is a cloud+ * account. Pins which accounts the policy disables, that any other default state+ * changes nothing, and which provider errors map to the clear message.+ */+class NewContactAccountPolicyTest {++ private class FakeSource(+ private val snapshot: DefaultAccountSnapshot?,+ private val local: ProviderAccount? = null,+ private val sims: List<ProviderAccount> = emptyList(),+ ) : DefaultAccountSource {+ override fun defaultAccountForNewContacts() = snapshot+ override fun customLocalAccount() = local+ override fun providerSimAccounts() = sims+ }++ private val google = ProviderAccount("[email protected]", "com.google")+ private val oemLocal = ProviderAccount("Phone", "com.oem.local")+ private val oemSim = ProviderAccount("SIM1", "com.oem.sim")++ @Test+ fun cloudDefaultBlocksDeviceAndProviderSimTargets() {+ val restriction = NewContactAccountPolicy.resolve(+ FakeSource(DefaultAccountSnapshot(DefaultAccountKind.CLOUD, google), oemLocal, listOf(oemSim))+ )+ assertNotNull(restriction)+ assertEquals(google, restriction.cloudAccount)+ // The NULL device account, however the app spells it.+ assertTrue(restriction.blocks("", ""))+ assertTrue(restriction.blocks(null, null))+ // OEM-customised local account and SIM accounts registered with the provider.+ assertTrue(restriction.blocks(oemLocal.name, oemLocal.type))+ assertTrue(restriction.blocks(oemSim.name, oemSim.type))+ }++ @Test+ fun cloudDefaultLeavesOtherTargetsEnabled() {+ val restriction = NewContactAccountPolicy.resolve(+ FakeSource(DefaultAccountSnapshot(DefaultAccountKind.CLOUD, google), oemLocal, listOf(oemSim))+ )+ assertNotNull(restriction)+ assertFalse(restriction.blocks(google.name, google.type))+ // DAVx5 is not eligible as a default account and keeps working (matches the report).+ assertFalse(restriction.blocks("me@nextcloud", "bitfire.at.davdroid"))+ // The app's SIM targets write the card via content://icc/adn, outside the provider check.+ assertFalse(restriction.blocks("1", SIM_ACCOUNT_TYPE))+ // The app's named local accounts are ordinary accounts to the provider.+ assertFalse(restriction.blocks("Family", LOCAL_ACCOUNT_TYPE))+ }++ @Test+ fun nonCloudDefaultChangesNothing() {+ val states = listOf(+ null,+ DefaultAccountSnapshot(DefaultAccountKind.NOT_SET, null),+ DefaultAccountSnapshot(DefaultAccountKind.LOCAL, null),+ DefaultAccountSnapshot(DefaultAccountKind.SIM, oemSim),+ )+ for (state in states) {+ assertNull(+ NewContactAccountPolicy.resolve(FakeSource(state, oemLocal, listOf(oemSim))),+ "default state $state must not restrict any target",+ )+ }+ }++ @Test+ fun cloudStateWithoutUsableAccountChangesNothing() {+ val blankAccount = DefaultAccountSnapshot(DefaultAccountKind.CLOUD, ProviderAccount("", "com.google"))+ assertNull(NewContactAccountPolicy.resolve(FakeSource(blankAccount)))+ assertNull(NewContactAccountPolicy.resolve(FakeSource(DefaultAccountSnapshot(DefaultAccountKind.CLOUD, null))))+ }++ @Test+ fun providerRejectionMapsToCloudDefaultError() {+ val providerError = IllegalArgumentException(+ "Cannot add contacts to local or SIM accounts when default account is set to cloud"+ )+ assertTrue(NewContactAccountPolicy.isCloudDefaultRejection(providerError))+ assertTrue(NewContactAccountPolicy.isCloudDefaultRejection(IllegalStateException("batch", providerError)))+ }++ @Test+ fun otherProviderErrorsDoNotMap() {+ assertFalse(+ NewContactAccountPolicy.isCloudDefaultRejection(+ IllegalArgumentException("Must specify both or neither of ACCOUNT_NAME and ACCOUNT_TYPE")+ )+ )+ assertFalse(NewContactAccountPolicy.isCloudDefaultRejection(IllegalArgumentException()))+ assertFalse(+ NewContactAccountPolicy.isCloudDefaultRejection(+ SecurityException("Cannot add contacts to local or SIM accounts when default account is set to cloud")+ )+ )+ }+}
contacts/src/test/java/com/vayunmathur/contacts/util/CloudDefaultAccountPass2Test.kt
diff --git a/contacts/src/test/java/com/vayunmathur/contacts/util/CloudDefaultAccountPass2Test.kt b/contacts/src/test/java/com/vayunmathur/contacts/util/CloudDefaultAccountPass2Test.ktnew file mode 100644index 0000000000..20395fa283--- /dev/null+++ b/contacts/src/test/java/com/vayunmathur/contacts/util/CloudDefaultAccountPass2Test.kt@@ -0,0 +1,160 @@+package com.vayunmathur.contacts.util++import android.app.Application+import android.content.ContentProvider+import android.content.ContentProviderOperation+import android.content.ContentProviderResult+import android.content.ContentValues+import android.database.Cursor+import android.net.Uri+import android.provider.ContactsContract+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.contacts.R+import com.vayunmathur.contacts.data.CDKPhone+import com.vayunmathur.contacts.data.Contact+import com.vayunmathur.contacts.data.ContactDetails+import com.vayunmathur.contacts.data.DefaultAccountKind+import com.vayunmathur.contacts.data.DefaultAccountSnapshot+import com.vayunmathur.contacts.data.DefaultAccountSource+import com.vayunmathur.contacts.data.Name+import com.vayunmathur.contacts.data.PhoneNumber+import com.vayunmathur.contacts.data.ProviderAccount+import com.vayunmathur.contacts.data.SaveOutcome+import kotlinx.coroutines.CompletableDeferred+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.test.resetMain+import kotlinx.coroutines.test.setMain+import kotlinx.coroutines.withTimeout+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.shadows.ShadowContentResolver+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * #916: with a cloud default account for new contacts (Android 16+), new drafts default to+ * that account instead of On-Device, and a provider refusal of the device account surfaces+ * as a clear error instead of "Save failed". A non-cloud default changes nothing.+ */+@OptIn(ExperimentalCoroutinesApi::class)+@RunWith(RobolectricTestRunner::class)+class CloudDefaultAccountPass2Test {+ private val app get() = ApplicationProvider.getApplicationContext<Application>()+ private val google = ProviderAccount("[email protected]", "com.google")++ /** Contacts provider that refuses every write the way AccountResolver does under a cloud default. */+ class RejectingProvider : ContentProvider() {+ override fun onCreate(): Boolean = true+ override fun query(+ uri: Uri, projection: Array<out String>?, selection: String?,+ selectionArgs: Array<out String>?, sortOrder: String?,+ ): Cursor? = null++ override fun applyBatch(+ authority: String, operations: ArrayList<ContentProviderOperation>,+ ): Array<ContentProviderResult> = throw rejection()++ override fun insert(uri: Uri, values: ContentValues?): Uri = throw rejection()+ override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int = 0+ override fun update(+ uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<out String>?,+ ): Int = 0++ override fun getType(uri: Uri): String? = null++ private fun rejection() = IllegalArgumentException(+ "Cannot add contacts to local or SIM accounts when default account is set to cloud"+ )+ }++ private class FakeSource(private val snapshot: DefaultAccountSnapshot?) : DefaultAccountSource {+ override fun defaultAccountForNewContacts() = snapshot+ override fun customLocalAccount(): ProviderAccount? = null+ override fun providerSimAccounts(): List<ProviderAccount> = emptyList()+ }++ @BeforeTest+ fun setUp() {+ Dispatchers.setMain(Dispatchers.Unconfined)+ ShadowContentResolver.registerProviderInternal(ContactsContract.AUTHORITY, RejectingProvider())+ }++ @AfterTest+ fun tearDown() {+ Dispatchers.resetMain()+ }++ private fun vm(snapshot: DefaultAccountSnapshot?): ContactViewModel {+ val vm = ContactViewModel(app, FakeSource(snapshot))+ runBlocking { vm.syncFromSystem() }+ return vm+ }++ private fun newDeviceContact() = Contact(+ id = 0L, accountType = null, accountName = null, isFavorite = false,+ details = ContactDetails.empty().copy(+ names = listOf(Name(0, "", "New", "", "Person", "")),+ phoneNumbers = listOf(PhoneNumber(0, "+14155550199", CDKPhone.TYPE_MOBILE)),+ ),+ )++ @Test+ fun saveMapsProviderRefusalToCloudDefaultOutcome() {+ val contact = newDeviceContact()+ assertEquals(+ SaveOutcome.REJECTED_CLOUD_DEFAULT,+ contact.saveWithOutcome(app, contact.details, ContactDetails.empty()),+ )+ assertFalse(contact.save(app, contact.details, ContactDetails.empty()))+ }++ @Test+ fun cloudDefaultSeedsNewDraftWithCloudAccount() {+ val vm = vm(DefaultAccountSnapshot(DefaultAccountKind.CLOUD, google))+ val restriction = assertNotNull(vm.newContactRestriction.value)+ assertTrue(restriction.blocks("", ""))+ // Offered in the pickers even when it holds no contacts yet.+ assertTrue(ContactAccount(google.name, google.type) in vm.accounts.value)++ vm.initEditDraft(null)+ val draft = assertNotNull(vm.editDraft.value)+ assertEquals(google.name, draft.accountName)+ assertEquals(google.type, draft.accountType)+ }++ @Test+ fun refusedEditorSaveExplainsWhy() {+ val vm = vm(DefaultAccountSnapshot(DefaultAccountKind.CLOUD, google))+ vm.initEditDraft(null)+ // The user forces On-Device anyway (e.g. a draft seeded before the default changed).+ vm.updateEditDraft {+ it.copy(+ accountName = "", accountType = "", firstName = "New",+ phoneNumbers = listOf(PhoneNumber(0, "+14155550199", CDKPhone.TYPE_MOBILE)),+ )+ }+ val result = CompletableDeferred<Pair<Boolean, String?>>()+ vm.saveEditDraft { ok, err, _ -> result.complete(ok to err) }+ val (ok, err) = runBlocking { withTimeout(30_000) { result.await() } }+ assertFalse(ok)+ assertEquals(app.getString(R.string.cloud_default_rejected, google.name), err)+ }++ @Test+ fun nonCloudDefaultKeepsOnDeviceDraft() {+ val vm = vm(DefaultAccountSnapshot(DefaultAccountKind.LOCAL, null))+ assertNull(vm.newContactRestriction.value)+ vm.initEditDraft(null)+ val draft = assertNotNull(vm.editDraft.value)+ assertEquals("", draft.accountName)+ assertEquals("", draft.accountType)+ }+}