Contacts, Reborn!
Looking for the easiest way to get full-access to the breadth of Contacts in Android without having to deal with the Contacts Provider and cursors? Well, look no further =)
Whether you just need to get all or some Contacts for a small part of your app (written in Kotlin or Java), or you are looking to create your own full-fledged Contacts app with the same capabilities as the native Android Contacts app, this library has you covered!
Documentation and how-to guides are all available and linked in the repository. You can browse the Howto pages or visit the GitHub Pages. Both contain the same info but the GitHub pages are not guaranteed to be up-to-date. The GitHub wiki hosts the project roadmap. It contains all planned work and release schedules, which are organized using issues, milestones, and projects.
You can also learn more about this library through the articles I wrote about it =)
- Android Contacts, Reborn
- I spent 3 years writing an Android Contacts API in Kotlin with Java interop. What Iβve learnedβ¦
Note: This repo was open-sourced on October 4, 2021. It was private prior to that.
The core library supports;
- All of the kinds of Data in the Contacts Provider; address, email, event, group membership, IM, name, nickname, note, organization, phone, photo, relation, SIP address, and website.
- Custom data integration.
- Broad queries and advanced queries of Contacts and RawContacts from zero or more Accounts. Include only desired fields in the results (e.g. name and phone number) to conserve CPU and memory. Specify matching criteria in an SQL WHERE clause fashion using Kotlin infix functions. Order by contact table columns. Limit and offset functions.
- Insert one or more RawContacts with an associated Account, causing automatic insertion of a new Contact subject to automatic aggregation by the Contacts Provider.
- Update one or more Contacts, RawContacts, and Data.
- Delete one or more Contacts, RawContacts, and Data.
- Query, insert, update, and delete Profile (device owner) Contact, RawContact, and Data.
- Query, insert, update, and delete Groups per Account.
- Query, insert update, and delete specific kinds of Data.
- Query, insert, update, and delete custom Data.
- Query for Accounts in the system or RawContacts table.
- Query for just RawContacts.
- Associate local RawContacts (no Account) to an Account.
- Join/merge/link and separate/unmerge/unlink two or more Contacts.
- Get and set Contact and RawContact Options. starred (favorite), custom ringtone, send to voicemail.
- Get, set, and remove Contacts/RawContact photo and thumbnail.
- Get, set, and clear default (primary) Contact Data (e.g. default/primary phone number, email, etc).
- Miscellaneous convenience functions.
- Contact data is synced automatically across devices.
There are also extensions that add functionality to every core function;
Also included are some pre-baked goodies to be used as is or just for reference;
- Gender custom Data.
- Handle name custom Data.
- Rudimentary contacts-integrated UI components.
- Debug functions to aid in development
There are also more features that are on the way!
- Blocked phone numbers.
- SIM card query, insert, update, and delete.
- Read/write from/to .VCF file.
- Social media custom data (WhatsApp, Twitter, Facebook, etc).
Installation
First, include JitPack in the repositories list,
repositories {
maven { url "https://jitpack.io" }
}
To import all modules,
dependencies {
implementation 'com.github.vestrel00:contacts-android:0.1.8'
}
To import specific modules,
dependencies {
implementation 'com.github.vestrel00.contacts-android:core:0.1.8'
}
Notice that when importing specific modules/subprojects, the first ":" comes after "contacts-android".
SNAPSHOTs of branches are also available,
dependencies {
implementation 'com.github.vestrel00:contacts-android:main-SNAPSHOT'
}
This library is a multi-module project published with JitPack;
Quick Start
To retrieve all contacts containing all available contact data,
val contacts = Contacts(context).query().find()
To simply search for Contacts, yielding the exact same results as the native Contacts app,
val contacts = Contacts(context)
.broadQuery()
.whereAnyContactDataPartiallyMatches(searchText)
.find()
Note that for queries, you will need to add the
android.permission.READ_CONTACTS
permission to your app's AndroidManifest. Additionally, the user will have to have given your app that permission at runtime (starting with Android Marshmallow). Without permissions being granted, query functions will return empty results. To make permission handling much easier, Kotlin coroutine extensions are available in thepermissions
module.
That's it! BUT, THAT IS BORING! Let's take a look at something more advancedβ¦
To retrieve the first 5 contacts (including only the contact id, display name, and phone numbers in the results) ordered by display name in descending order, matching ALL of these rules;
- a first name starting with "leo"
- has emails from gmail or hotmail
- lives in the US
- has been born prior to making this query
- is favorited (starred)
- has a nickname of "DarEdEvil" (case sensitive)
- works for Facebook
- has a note
- belongs to the account of "[email protected]" or "[email protected]"
val contacts = Contacts(context)
.query()
.where(
(Fields.Name.GivenName startsWith "leo") and
((Fields.Email.Address endsWith "gmail.com") or (Fields.Email.Address endsWith "hotmail.com")) and
(Fields.Address.Country equalToIgnoreCase "us") and
((Fields.Event.Date lessThan Date().toWhereString()) and (Fields.Event.Type equalTo Event.Type.BIRTHDAY)) and
(Fields.Contact.Options.Starred equalTo true) and
(Fields.Nickname.Name equalTo "DarEdEvil") and
(Fields.Organization.Company `in` listOf("facebook", "FB")) and
(Fields.Note.Note.isNotNullOrEmpty())
)
.accounts(
Account("[email protected]", "com.google"),
Account("[email protected]", "com.myspace"),
)
.include(Fields.Contact.Id, Fields.Contact.DisplayNamePrimary, Fields.Phone.Number, Fields.Phone.NormalizedNumber)
.orderBy(ContactsFields.DisplayNamePrimary.desc())
.offset(0)
.limit(5)
.find()
For more info, read How do I get a list of contacts in the simplest way? and How do I get a list of contacts in a more advanced way?
Imagine what this would look like if you use ContactsContract directly. Now, you don't have to! The above snippet is in Kotlin but, like I mentioned, all of the core APIs are usable in Java too (though it won't look as pretty).
Once you have the contacts, you now have access to all of their data!
val contact: Contact
Log.d(
"Contact",
"""
ID: ${contact.id}
Display name: ${contact.displayNamePrimary}
Display name alt: ${contact.displayNameAlt}
Photo Uri: ${contact.photoUri}
Thumbnail Uri: ${contact.photoThumbnailUri}
Last updated: ${contact.lastUpdatedTimestamp}
Starred?: ${contact.options?.starred}
Send to voicemail?: ${contact.options?.sendToVoicemail}
Ringtone: ${contact.options?.customRingtone}
Aggregate data from all RawContacts of the contact
-----------------------------------
Addresses: ${contact.addressList()}
Emails: ${contact.emailList()}
Events: ${contact.eventList()}
Group memberships: ${contact.groupMembershipList()}
IMs: ${contact.imList()}
Names: ${contact.nameList()}
Nicknames: ${contact.nicknameList()}
Notes: ${contact.noteList()}
Organizations: ${contact.organizationList()}
Phones: ${contact.phoneList()}
Relations: ${contact.relationList()}
SipAddresses: ${contact.sipAddressList()}
Websites: ${contact.websiteList()}
-----------------------------------
""".trimIndent()
// There are also aggregate data functions that return a sequence instead of a list.
)
Each Contact may have more than one of the following data if the Contact is made up of 2 or more RawContacts; name, nickname, note, organization, sip address.
For more info, read How do I learn more about the API entities?
Setup
There is no setup required. It's up to you how you want to create and retain instances of the contacts.core.Contacts(context)
API. For more info, read How do I setup the Contacts API?
It is also useful to read How do I learn more about the API entities?
More than enough APIs that will allow you to build your own contacts app!
This library is capable of doing more than just querying contacts. Actually, you can build your own full-fledged contacts app with it!
Let's take a look at a few other APIs this library provides...
To get the first 20 gmail emails ordered by email address in descending order,
val emails = Contacts(context)
.data()
.query()
.emails()
.where(Fields.Email.Address endsWith "gmail.com")
.orderBy(Fields.Email.Address.desc(ignoreCase = true))
.offset(0)
.limit(20)
.find()
It's not just for emails. It's for all data kinds (including custom data).
For more info, read How do I get a list of specific data kinds?
To CREATE/INSERT a contact with a name of "John Doe" who works at Amazon with a work email of "[email protected]" (in Kotlin),
val insertResult = Contacts(context)
.insert()
.rawContacts(MutableRawContact().apply {
name = MutableName().apply {
givenName = "John"
familyName = "Doe"
}
organization = MutableOrganization().apply {
company = "Amazon"
title = "Superstar"
}
emails.add(MutableEmail().apply {
address = "[email protected]"
type = Email.Type.WORK
})
})
.commit()
Or alternatively, in a more Kotlinized style,
val insertResult = Contacts(context)
.insert()
.rawContact {
setName {
givenName = "John"
familyName = "Doe"
}
setOrganization {
company = "Amazon"
title = "Superstar"
}
addEmail {
address = "[email protected]"
type = Email.Type.WORK
}
}
.commit()
For more info, read How do I create/insert contacts?
If John Doe switches jobs and heads over to Microsoft, we can UPDATE his data,
Contacts(context)
.update()
.contacts(johnDoe.toMutableContact().apply {
setOrganization {
company = "Microsoft"
title = "Newb"
}
emails().first().apply {
address = "[email protected]"
}
})
.commit()
For more info, read How do I update contacts?
If we no longer like John Doe, we can DELETE him from our life,
Contacts(context)
.delete()
.contacts(johnDoe)
.commit()
For more info, read How do I delete contacts?
Note that for insert, update, and delete functions, you will need to add the
android.permission.WRITE_CONTACTS
andandroid.permission.GET_ACCOUNTS
permissions to your app's AndroidManifest. Additionally, the user will have to have given your app that permission at runtime (starting with Android Marshmallow). Without permissions being granted, these functions will do nothing and return a failed result. To make permission handling much easier, Kotlin coroutine extensions are available in thepermissions
module.
Threading and permissions
This library provides Kotlin coroutine extensions in the permissions
module for all API functions to handle permissions and async
module for executing work in background threads.
launch {
val contacts = Contacts(context)
.queryWithPermission()
...
.findWithContext()
val deferredResult = Contacts(context)
.insert()
...
.commitAsync()
val result = deferredResult.await()
}
For more info, read How do I use the permissions module to simplify permission handling using coroutines? and How do I use the async module to simplify executing work outside of the UI thread using coroutines?
So, if we call the above function and we don't yet have permission. The user will be prompted to give the appropriate permissions before the query proceeds. Then, the work is done in the coroutine context of choice (default is Dispatchers.IO). If the user does not give permission, the query will return no results.
Extensions for Kotlin Flow and RxJava are also in the v1 roadmap, which includes APIs for listening to Contacts database changes.
Full in-code documentation and Howto guides and samples
The above examples barely scratches the surface of what this library provides. For more in-depth Howtos, visit the howto directory. For a sample app reference, take a look at and run the sample
module.
All APIs in the library are optimized!
Some other APIs or util functions out there typically perform one internal database query per contact returned. They do this to fetch the data per contact. This means that if there are 1,000 matching contacts, then an extra 1,000 internal database queries are performed! This is not cool!
To address this issue, the query APIs provided in the Contacts, Reborn library, perform only at least two and at most six or seven internal database queries no matter how many contacts are matched! Even if there are 100,000 contacts matched, the library will only perform two to seven internal database queries (depending on your query parameters).
Of course, if you don't want to fetch all hundreds of thousands of contacts, the query APIs support pagination with limit
and offset
functions
Cancellations are also supported! To cancel a query amid execution,
.find { returnTrueIfQueryShouldBeCancelled() }
The find function optionally takes in a function that, if it returns true, will cancel query processing as soon as possible. The function is called numerous times during query processing to check if processing should stop or continue. This gives you the option to cancel the query.
This is useful when used in multi-threaded environments. One scenario where this would be frequently used is when performing queries as the user types a search text. You are able to cancel the current query when the user enters new text.
For example, to automatically cancel the query inside a Kotlin coroutine when the coroutine is cancelled,
launch {
withContext(coroutineContext) {
val contacts = query.find { !isActive }
}
// Or, using the coroutine extensions in the async module...
val contacts = query.findWithContext()
}
All core APIs are framework-agnostic and works well with Java and Kotlin
The API does not and will not force you to use any frameworks (e.g. RxJava or Coroutines/Flow)! All core functions of the API live in the core
module, which you can import to your project all by itself. Don't believe me? Take a look at the dependencies in the core/build.gradle
:D
So, feel free to use the core API however you want with whatever libraries or frameworks you want, such as Reactive, Coroutines/Flow, AsyncTask (hope not), WorkManager, and whatever permissions handling APIs you want to use.
All other modules in this library are optional and are just there for your convenience or for reference.
I also made sure that all core functions and entities are interoperable with Java 7+. So, if you were wondering why Iβm using a semi-builder pattern instead of using named arguments with default values, that is why. Iβve also made some other intentional decisions about API design to ensure the best possible experience for both Kotlin and Java consumers without sacrificing Kotlin language standards. It is Kotlin-first, Java-second (with love and care).
Modules other than the core module are not guaranteed to be compatible with Java.
Requirements
- Min SDK 19+
- Java 7+
Proguard
If you use Proguard and the async
and/or permissions
, you may need to add rules for Coroutines.
License
Copyright 2021 Contacts Contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Support
This is a newly open sourced library with only one contributor so far (me). Donβt expect much support in the beginning. I am only able to work on this (and respond to issues) outside of work hours. This means late nights, weekends, and maybe holidays.
As time passes, hopefully this library gets more and more contributors. At some point, I hope to gain contributors that have become experts on this library to help me support the community by maintaining it and making admin-level decisions.
In any case, create issues for any bugs found and I'll get to it when I get the chance depending on severity of the issue.