Questa lezione spiega come utilizzare Intent
per inserire un nuovo contatto o
modificare i dati di un contatto. Anziché accedere direttamente al provider di contatti, un
Intent
avvia l'app dei contatti, che esegue l'app
Activity
appropriata. Per le azioni di modifica descritte in questa lezione,
se invii dati estesi in Intent
, i dati vengono inseriti nell'interfaccia utente
dell'Activity
avviato.
L'utilizzo di un Intent
per inserire o aggiornare un singolo contatto è il modo preferito per modificare il provider di contatti, per i seguenti motivi:
- Ti consente di risparmiare il tempo e l'impegno necessari per sviluppare l'interfaccia utente e il codice.
- Evita di introdurre errori causati da modifiche che non seguono le regole del provider di contatti.
- Riduce il numero di autorizzazioni che devi richiedere. La tua app non ha bisogno dell'autorizzazione per scrivere nel provider di contatti perché delega le modifiche all'app dei contatti, che dispone già di questa autorizzazione.
Inserisci un nuovo contatto utilizzando un intent
Spesso vuoi consentire all'utente di inserire un nuovo contatto quando la tua app riceve nuovi dati. Ad esempio, un'app di recensioni di ristoranti può consentire agli utenti di aggiungere il ristorante come contatto mentre lo recensiscono. Per farlo utilizzando un intent, crealo utilizzando quanti dati hai a disposizione, quindi invialo all'app Contatti.
Se inserisci un contatto tramite l'app Contatti, viene inserito un nuovo contatto non elaborato nella tabella ContactsContract.RawContacts
del provider di contatti. Se necessario, l'app dei contatti chiede agli utenti il tipo di account e l'account da utilizzare per la creazione del contatto non elaborato. Inoltre, l'app Contatti avvisa gli utenti se il contatto non elaborato esiste già. Gli utenti hanno quindi la possibilità di annullare l'inserimento, nel qual caso non verrà creato alcun contatto. Per scoprire di più sui contatti non elaborati, consulta la guida all'API Contacts Provider.
Creare un intent
Per iniziare, crea un nuovo oggetto Intent
con l'azione
Intents.Insert.ACTION
.
Imposta il tipo MIME su RawContacts.CONTENT_TYPE
. Ecco alcuni esempi:
Kotlin
... // Creates a new Intent to insert a contact val intent = Intent(ContactsContract.Intents.Insert.ACTION).apply { // Sets the MIME type to match the Contacts Provider type = ContactsContract.RawContacts.CONTENT_TYPE }
Java
... // Creates a new Intent to insert a contact Intent intent = new Intent(ContactsContract.Intents.Insert.ACTION); // Sets the MIME type to match the Contacts Provider intent.setType(ContactsContract.RawContacts.CONTENT_TYPE);
Se disponi già dei dettagli del contatto, ad esempio un numero di telefono o un indirizzo email, puoi
inserirli nell'intent come dati estesi. Per una coppia chiave-valore, utilizza la costante appropriata di
Intents.Insert
. L'app dei contatti
visualizza i dati nella schermata di inserimento, consentendo agli utenti di apportare ulteriori modifiche e aggiunte.
Kotlin
private var emailAddress: EditText? = null private var phoneNumber: EditText? = null ... /* Assumes EditText fields in your UI contain an email address * and a phone number. * */ emailAddress = findViewById(R.id.email) phoneNumber = findViewById(R.id.phone) ... /* * Inserts new data into the Intent. This data is passed to the * contacts app's Insert screen */ intent.apply { // Inserts an email address putExtra(ContactsContract.Intents.Insert.EMAIL, emailAddress?.text) /* * In this example, sets the email type to be a work email. * You can set other email types as necessary. */ putExtra( ContactsContract.Intents.Insert.EMAIL_TYPE, ContactsContract.CommonDataKinds.Email.TYPE_WORK ) // Inserts a phone number putExtra(ContactsContract.Intents.Insert.PHONE, phoneNumber?.text) /* * In this example, sets the phone type to be a work phone. * You can set other phone types as necessary. */ putExtra( ContactsContract.Intents.Insert.PHONE_TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_WORK ) }
Java
private EditText emailAddress = null; private EditText phoneNumber = null; ... /* Assumes EditText fields in your UI contain an email address * and a phone number. * */ emailAddress = (EditText) findViewById(R.id.email); phoneNumber = (EditText) findViewById(R.id.phone); ... /* * Inserts new data into the Intent. This data is passed to the * contacts app's Insert screen */ // Inserts an email address intent.putExtra(ContactsContract.Intents.Insert.EMAIL, emailAddress.getText()) /* * In this example, sets the email type to be a work email. * You can set other email types as necessary. */ .putExtra(ContactsContract.Intents.Insert.EMAIL_TYPE, ContactsContract.CommonDataKinds.Email.TYPE_WORK) // Inserts a phone number .putExtra(ContactsContract.Intents.Insert.PHONE, phoneNumber.getText()) /* * In this example, sets the phone type to be a work phone. * You can set other phone types as necessary. */ .putExtra(ContactsContract.Intents.Insert.PHONE_TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_WORK);
Dopo aver creato il Intent
, invialo chiamando
startActivity()
.
Kotlin
/* Sends the Intent */ startActivity(intent)
Java
/* Sends the Intent */ startActivity(intent);
Questa chiamata apre una schermata nell'app Contatti che consente agli utenti di inserire un nuovo contatto. Il tipo di account e il nome dell'account del contatto sono elencati nella parte superiore dello schermo. Dopo che gli utenti hanno inserito i dati e fatto clic su Fine, viene visualizzato l'elenco contatti dell'app Contatti. Gli utenti tornano alla tua app facendo clic su Indietro.
Modificare un contatto esistente utilizzando un intent
La modifica di un contatto esistente utilizzando un Intent
è utile se l'utente
ha già scelto un contatto di interesse. Ad esempio, un'app che trova i contatti che hanno un indirizzo postale, ma non il codice postale, potrebbe offrire agli utenti la possibilità di cercare il codice e aggiungerlo al contatto.
Per modificare un contatto esistente utilizzando un intent, utilizza una procedura simile all'inserimento di un contatto. Crea un intent come descritto nella sezione
Inserire un nuovo contatto utilizzando un intent, ma aggiungi
Contacts.CONTENT_LOOKUP_URI
del contatto e il tipo MIME
Contacts.CONTENT_ITEM_TYPE
all'intent. Se vuoi modificare il contatto con i dettagli già in tuo possesso, puoi inserirli nei dati estesi dell'intent. Tieni presente che alcune colonne dei nomi non possono essere modificate utilizzando un intent. Queste colonne sono elencate nella sezione di riepilogo del riferimento dell'API per la classe ContactsContract.Contacts
nell'intestazione "Aggiorna".
Infine, invia l'intent. In risposta, l'app Contatti mostra una schermata di modifica. Quando l'utente termina la modifica e salva le modifiche, l'app Contatti mostra un elenco di contatti. Quando l'utente fa clic su Indietro, viene visualizzata la tua app.
Crea l'intent
Per modificare un contatto, chiama Intent(action)
per
creare un intent con l'azione ACTION_EDIT
. Richiama setDataAndType()
per impostare il valore dei dati per l'intent sul valore Contacts.CONTENT_LOOKUP_URI
del contatto e il tipo MIME sul tipo MIME Contacts.CONTENT_ITEM_TYPE
. Poiché una chiamata a setType()
sovrascrive il valore dei dati attuale per Intent
, devi impostare i dati e il tipo MIME contemporaneamente.
Per ottenere Contacts.CONTENT_LOOKUP_URI
di un contatto, chiama
Contacts.getLookupUri(id, lookupkey)
con i valori
Contacts._ID
e
Contacts.LOOKUP_KEY
del contatto come
argomenti.
Nota: il valore LOOKUP_KEY
di un contatto è l'identificatore che devi utilizzare per recuperare un contatto. Rimane costante, anche se il provider modifica l'ID riga del contatto per gestire le operazioni interne.
Il seguente snippet mostra come creare un intent:
Kotlin
// The Cursor that contains the Contact row var mCursor: Cursor? = null // The index of the lookup key column in the cursor var lookupKeyIndex: Int = 0 // The index of the contact's _ID value var idIndex: Int = 0 // The lookup key from the Cursor var currentLookupKey: String? = null // The _ID value from the Cursor var currentId: Long = 0 // A content URI pointing to the contact var selectedContactUri: Uri? = null ... /* * Once the user has selected a contact to edit, * this gets the contact's lookup key and _ID values from the * cursor and creates the necessary URI. */ mCursor?.apply { // Gets the lookup key column index lookupKeyIndex = getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY) // Gets the lookup key value currentLookupKey = getString(lookupKeyIndex) // Gets the _ID column index idIndex = getColumnIndex(ContactsContract.Contacts._ID) currentId = getLong(idIndex) selectedContactUri = ContactsContract.Contacts.getLookupUri(currentId, mCurrentLookupKey) } // Creates a new Intent to edit a contact val editIntent = Intent(Intent.ACTION_EDIT).apply { /* * Sets the contact URI to edit, and the data type that the * Intent must match */ setDataAndType(selectedContactUri, ContactsContract.Contacts.CONTENT_ITEM_TYPE) }
Java
// The Cursor that contains the Contact row public Cursor mCursor; // The index of the lookup key column in the cursor public int lookupKeyIndex; // The index of the contact's _ID value public int idIndex; // The lookup key from the Cursor public String currentLookupKey; // The _ID value from the Cursor public long currentId; // A content URI pointing to the contact Uri selectedContactUri; ... /* * Once the user has selected a contact to edit, * this gets the contact's lookup key and _ID values from the * cursor and creates the necessary URI. */ // Gets the lookup key column index lookupKeyIndex = mCursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY); // Gets the lookup key value currentLookupKey = mCursor.getString(lookupKeyIndex); // Gets the _ID column index idIndex = mCursor.getColumnIndex(ContactsContract.Contacts._ID); currentId = mCursor.getLong(idIndex); selectedContactUri = Contacts.getLookupUri(currentId, mCurrentLookupKey); ... // Creates a new Intent to edit a contact Intent editIntent = new Intent(Intent.ACTION_EDIT); /* * Sets the contact URI to edit, and the data type that the * Intent must match */ editIntent.setDataAndType(selectedContactUri, ContactsContract.Contacts.CONTENT_ITEM_TYPE);
Aggiungi il flag di navigazione
In Android 4.0 (API versione 14) e versioni successive, un problema nell'app Contatti causa una navigazione errata. Quando l'app invia un intent di modifica all'app Contatti e gli utenti modificano e salvano un contatto, quando fanno clic su Indietro viene visualizzata la schermata dell'elenco dei contatti. Per tornare alla tua app, devono fare clic su Recenti e scegliere l'app.
Per risolvere questo problema in Android 4.0.3 (versione API 15) e versioni successive, aggiungi la chiave dati estesa finishActivityOnSaveCompleted
all'intent con un valore pari a true
.
Le versioni di Android precedenti ad Android 4.0 accettano questa chiave, che però non ha alcun effetto. Per impostare i dati estesi:
Kotlin
// Sets the special extended data for navigation editIntent.putExtra("finishActivityOnSaveCompleted", true)
Java
// Sets the special extended data for navigation editIntent.putExtra("finishActivityOnSaveCompleted", true);
Aggiungere altri dati estesi
Per aggiungere altri dati estesi a Intent
, chiama
putExtra()
come preferisci.
Puoi aggiungere dati estesi per i campi dei contatti comuni utilizzando le coppie chiave-valore specificate in
Intents.Insert
. Ricorda che alcune colonne della tabella ContactsContract.Contacts
non possono essere modificate.
Queste colonne sono elencate nella sezione di riepilogo del riferimento API per la classe ContactsContract.Contacts
sotto l'intestazione "Aggiorna".
Invia l'intent
Infine, comunica l'intent che hai creato. Ecco alcuni esempi:
Kotlin
// Sends the Intent startActivity(editIntent)
Java
// Sends the Intent startActivity(editIntent);
Consenti agli utenti di inserire o modificare utilizzando un intent
Puoi consentire agli utenti di scegliere se inserire un contatto o modificarne uno esistente inviando
un Intent
con l'azione
ACTION_INSERT_OR_EDIT
. Ad esempio, un'app client di posta potrebbe consentire agli utenti di aggiungere un indirizzo email in arrivo a un nuovo contatto o di aggiungerlo come indirizzo aggiuntivo per un contatto esistente. Imposta il tipo MIME per questo intent su Contacts.CONTENT_ITEM_TYPE
, ma non impostare l'URI dei dati.
Quando invii questo intent, l'app Contatti mostra un elenco di contatti.
Gli utenti possono inserire un nuovo contatto o selezionare un contatto esistente e modificarlo.
Eventuali campi di dati estesi che aggiungi all'intent completano la schermata visualizzata. Puoi utilizzare qualsiasi coppia chiave-valore specificata in Intents.Insert
. Il seguente snippet di codice mostra come creare e inviare l'intent:
Kotlin
// Creates a new Intent to insert or edit a contact val intentInsertEdit = Intent(Intent.ACTION_INSERT_OR_EDIT).apply { // Sets the MIME type type = ContactsContract.Contacts.CONTENT_ITEM_TYPE } // Add code here to insert extended data, if desired // Sends the Intent with an request ID startActivity(intentInsertEdit)
Java
// Creates a new Intent to insert or edit a contact Intent intentInsertEdit = new Intent(Intent.ACTION_INSERT_OR_EDIT); // Sets the MIME type intentInsertEdit.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE); // Add code here to insert extended data, if desired ... // Sends the Intent with an request ID startActivity(intentInsertEdit);