Query aggregated People Directories

Client apps, such as system dialers and contact managers, can query the People Provider to fetch unified reachability records and route users directly into communication flows.

To query aggregated People Directories and interact with their records, complete the following tasks:

  1. Declare required permissions.
  2. Discover installed People Directories.
  3. Query person and group identities using structured builders.
  4. Observe background data changes using ContentObserver.
  5. Initiate communication interactions using PendingIntent.

Declare required permissions

To query the People Provider, your app must have permission to manage system contacts. In your AndroidManifest.xml file, declare the MANAGE_CONTACTS permission inside the <manifest> element:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.dialer">
    <uses-permission android:name="android.permission.MANAGE_CONTACTS" />
</manifest>

MANAGE_CONTACTS is a special permission. At runtime, check whether your app has access by calling AppOpsManager.checkOpNoThrow with AppOpsManager.OPSTR_MANAGE_CONTACTS. If checkOpNoThrow returns AppOpsManager.MODE_DEFAULT, fall back to Context.checkSelfPermission.

If your app doesn't have the permission, launch the Settings.ACTION_MANAGE_CONTACTS intent to open the settings page where the user can grant access. Because a matching activity might not exist on all devices, catch ActivityNotFoundException when calling startActivity. The following example checks for MANAGE_CONTACTS and opens the settings page if your app doesn't have access:

import android.Manifest
import android.app.Activity
import android.app.AppOpsManager
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Process
import android.provider.Settings

fun hasManageContactsPermission(context: Context): Boolean {
    val appOpsManager = context.getSystemService(AppOpsManager::class.java) ?: return false
    return when (
        appOpsManager.checkOpNoThrow(
            AppOpsManager.OPSTR_MANAGE_CONTACTS,
            Process.myUid(),
            context.packageName
        )
    ) {
        AppOpsManager.MODE_ALLOWED -> true
        AppOpsManager.MODE_DEFAULT ->
            context.checkSelfPermission(Manifest.permission.MANAGE_CONTACTS) ==
                PackageManager.PERMISSION_GRANTED
        else -> false
    }
}

fun requestManageContactsPermission(activity: Activity) {
    if (!hasManageContactsPermission(activity)) {
        try {
            activity.startActivity(Intent(Settings.ACTION_MANAGE_CONTACTS))
        } catch (e: ActivityNotFoundException) {
            // Handle the case where no activity can handle the settings intent
        }
    }
}

Discover installed People Directories

You can discover which calling and messaging apps have registered a People Directory on the device by querying the system:

import android.content.Context
import android.provider.PeopleContract

fun discoverInstalledDirectories(context: Context): List<DirectoryInfo> {
    val directories = mutableListOf<DirectoryInfo>()
    val projection = arrayOf(
        PeopleContract.Directory.PACKAGE_NAME,
        PeopleContract.Directory.DIRECTORY_AUTHORITY
    )
    context.contentResolver.query(
        PeopleContract.Directory.CONTENT_URI,
        projection,
        null,
        null
    )?.use { cursor ->
        val packageIdx = cursor.getColumnIndexOrThrow(PeopleContract.Directory.PACKAGE_NAME)
        val authorityIdx = cursor.getColumnIndexOrThrow(PeopleContract.Directory.DIRECTORY_AUTHORITY)
        while (cursor.moveToNext()) {
            directories.add(
                DirectoryInfo(
                    packageName = cursor.getString(packageIdx),
                    authority = cursor.getString(authorityIdx)
                )
            )
        }
    }
    return directories
}

data class DirectoryInfo(val packageName: String, val authority: String)

Query person and group identities using structured builders

The People Provider doesn't support SQL selection strings (where clauses). Calling ContentResolver.query with traditional selection or selectionArgs parameters on the People Provider throws an UnsupportedOperationException. Instead, construct a query arguments Bundle using PeopleContract.Persons.Query.Builder, and pass structured query bundles using query(Uri, String[], Bundle, CancellationSignal). Querying group identities follows the same pattern using PeopleContract.Groups.Query.Builder and PeopleContract.Groups.CONTENT_URI.

The following example queries person records by phone number:

import android.content.Context
import android.database.Cursor
import android.provider.PeopleContract

fun queryPersonByPhone(
    context: Context,
    targetPackage: String,
    normalizedPhoneNumber: String
): Cursor? {
    // 1. Build the structured query bundle
    // normalizedPhoneNumber is in E.164 format
    val queryArgs = PeopleContract.Persons.Query.Builder()
        .addPhoneQuery(targetPackage, listOf(normalizedPhoneNumber))
        .build()
    // 2. Execute the query
    return context.contentResolver.query(
        PeopleContract.Persons.CONTENT_URI,
        null, // Default projection returns all standard columns
        queryArgs,
        null
    )
}

Observe background database synchronization using ContentObserver

When a query runs, the People Provider immediately returns available records from its internal database while scheduling tasks to synchronize missing or updated records from the remote directory. Depending on the trigger and device state, these synchronization tasks might not run immediately; the system can schedule them to run during optimal device states, such as when the device is idle and charging.

To receive updated records after synchronization completes, register a ContentObserver on the query-specific notification URI returned in the cursor extras under PeopleContract.EXTRA_NOTIFICATION_URI. Unregister the observer using ContentResolver.unregisterContentObserver when you no longer need updates:

import android.content.Context
import android.database.ContentObserver
import android.database.Cursor
import android.net.Uri
import android.os.Handler
import android.os.Looper
import android.provider.PeopleContract

fun observeAndQuery(
    context: Context,
    targetPackage: String,
    normalizedPhoneNumber: String
): ContentObserver? {
    val cursor = queryPersonByPhone(context, targetPackage, normalizedPhoneNumber) ?: return null
    // 1. Extract the query-specific notification URI from cursor extras
    val notificationUri: Uri? = cursor.extras?.getParcelable(
        PeopleContract.EXTRA_NOTIFICATION_URI,
        Uri::class.java
    )
    // 2. Process initial results from the People Provider internal database
    displayResults(cursor)
    // 3. Register ContentObserver to handle deferred JobScheduler synchronization completions
    if (notificationUri != null) {
        val observer = object : ContentObserver(Handler(Looper.getMainLooper())) {
            override fun onChange(selfChange: Boolean, uri: Uri?) {
                super.onChange(selfChange, uri)
                // Background synchronization updated the internal database; re-query to fetch fresh records
                val freshCursor = queryPersonByPhone(context, targetPackage, normalizedPhoneNumber)
                displayResults(freshCursor)
            }
        }
        context.contentResolver.registerContentObserver(notificationUri, false, observer)
        return observer
    }
    return null
}

fun displayResults(cursor: Cursor?) {
    cursor?.use {
        val nameIdx = it.getColumnIndexOrThrow(PeopleContract.Persons.DISPLAY_NAME)
        val capIdx = it.getColumnIndexOrThrow(PeopleContract.Persons.CAPABILITY)
        while (it.moveToNext()) {
            val name = it.getString(nameIdx)
            val capability = it.getInt(capIdx)
            val supportsVoice = (capability and PeopleContract.Capability.VOICE_REACHABILITY) != 0
            val supportsVideo = (capability and PeopleContract.Capability.VIDEO_REACHABILITY) != 0
            // Update UI components
        }
    }
}

Initiate communication interactions

To start a voice call, video call, or chat message without requiring direct component visibility or private permissions to the target directory app, obtain a system-minted PendingIntent.

  1. In your app code, build a structured target query Bundle targeting a single directory identity.
  2. Request the system-minted PendingIntent by calling PeopleContract.createPeopleInteractionRequest.
  3. Send the PendingIntent using PendingIntent.send.
import android.content.Context
import android.provider.PeopleContract

fun startVoipCall(
    context: Context,
    targetPackage: String,
    normalizedPhoneNumber: String
) {
    // 1. Build a target query bundle targeting a single directory
    // normalizedPhoneNumber is in E.164 format
    val queryArgs = PeopleContract.Persons.Query.Builder()
        .addPhoneQuery(targetPackage, listOf(normalizedPhoneNumber))
        .build()
    // 2. Request the system-minted PendingIntent
    val pendingIntent = PeopleContract.createPeopleInteractionRequest(
        context.contentResolver,
        PeopleContract.Intents.PEOPLE_INTERACTION_TYPE_VOICE,
        queryArgs
    )
    // 3. Send the PendingIntent
    pendingIntent?.send()
}

Additional resources