> ## Documentation Index
> Fetch the complete documentation index at: https://build.thamani.app/llms.txt
> Use this file to discover all available pages before exploring further.

# Reading Messages

> A guide on how to read native android messages

<Card title="Maverick Mambo" icon="https://mintcdn.com/halo-c614fc4d/n1cCDjQImiwl-ZA3/images/authors/mambo.png?fit=max&auto=format&n=n1cCDjQImiwl-ZA3&q=85&s=08273d91c4d009986a2472edd13b0aa4" horizontal width="1000" height="1000" data-path="images/authors/mambo.png">
  Pathfinder @ Thamani
</Card>

<img className="block" src="https://mintcdn.com/halo-c614fc4d/VumhQQ2LC93rk3N_/images/messages.svg?fit=max&auto=format&n=VumhQQ2LC93rk3N_&q=85&s=31f293ccc90124663ebda59fda4c9540" alt="Hero Light" width="2064" height="1104" data-path="images/messages.svg" />

Accessing user messages is a sensitive matter that requires a strong commitment to privacy and ethical responsibility.

## Why?

As engineers, we must anticipate the questions users may have when we request sensitive permissions, such as:

* Why do you need to read my messages?
* How will my data be used?
* Will you access any sensitive information?

It's our responsibility to address these concerns before requesting access. Before prompting users for sensitive permissions, we should critically evaluate whether the access is truly necessary. Consider:

* Are we building a messaging application where reading messages is essential for core functionality?
* Is there a legitimate, user-focused reason to access this data?

If, after thoughtful consideration, we determine that reading user messages is required, the next step is to approach this need transparently and securely, ensuring we respect user privacy at every stage.

## How?

<Steps>
  <Step title="Update Manifest">
    Add the `telephony` feature and required permissions to your app’s `AndroidManifest.xml`:

    ```xml theme={null}
    <uses-feature
        android:name="android.hardware.telephony"
        android:required="true"
        tools:ignore="UnnecessaryRequiredFeature" />

    <uses-permission android:name="android.permission.READ_SMS" />
    ```

    <Warning>Only set `required="true"` if your app cannot function without this feature</Warning>

    <Note>
      If you omit the telephony feature, you’ll encounter errors like: <br />
      `Permission exists without corresponding hardware ... tag.`
    </Note>
  </Step>

  <Step title="Request Permission">
    There are multiple ways to request permissions in Android. Below are two common approaches.

    <Tabs>
      <Tab title="Custom">
        This method uses Android’s built-in APIs:

        ```kotlin theme={null}
        // create permission reference
        val permission = android.Manifest.permission.READ_SMS

        // get activity & context
        val activity: ComponentActivity = getActivity()
        val context: Context = getContext()

        // check if permission is granted
        val isGranted = context.checkSelfPermission(permission) == android.content.pm.PackageManager.PERMISSION_GRANTED
        if (isGranted) return

        // if it is not granted, check if it can show permission dialog
        val canRequest = ActivityCompat.shouldShowRequestPermissionRationale(this, permission)
        if (canRequest.not()) {
            // navigate the user to settings to enable permission manually
            return
        }

        // create launcher and launch permission
        with(activity){
            val launcher: ActivityResultLauncher<String> =
                registerForActivityResult(
                    ActivityResultContracts.RequestPermission()
                ) { result ->
                    // check if result is true and continue
                    // if result is not true, the permission was not granted
                }
            launcher.launch(permission)
        }
        ```

        <Note>The `launcher` can only be created from the context of a `ComponentActivity`</Note>
      </Tab>

      <Tab title="Accompanist">
        Accompanist provides a Compose-friendly API for handling permissions.

        * locate your `build.gradle.kts` and add `accompanist-permission` dependency

        ```kotlin theme={null}
        implementation("com.google.accompanist:accompanist-permissions:0.34.0")
        ```

        * navigate to your desired `composable` and check for permission

        ```kotlin theme={null}
        // get permission state
        val permissionState = rememberPermissionState(android.Manifest.permission.READ_SMS)

        // check if permission isGranted
        val isGranted = permissionState.status.isGranted

        // if permission is granted launch permission request
        if(isGranted.not()) permissionState.launchPermissionRequest()
        ```

        <Note>Unlike the previous example this library doesn't handle cases where the user has clicked not to show the permission again</Note>
        With that we have a way of requesting and accepting permission
      </Tab>
    </Tabs>
  </Step>

  <Step title="Read Messages">
    Once permissions are granted, you can access SMS data:

    ```kotlin theme={null}
    // get context
    val context: Context = getContext()

    // get content resolver from context
    val contentResolver: ContentResolver = context.contentResolver

    // get cursor for
    val cursor =
        context.contentResolver.query("content://sms/inbox".toUri(), null, null, null, null)

    // use the cursor to read contents of the column
    cursor?.use {
        while(it.moveToNext()){
            val date = it.getLongOrNull("date") // get message date
            val body = it.getStringOrNull("body") // get message body
        }
    }
    ```
  </Step>
</Steps>

## Conclusion

Reading user messages should never be taken lightly. Use this capability only when it is indispensable to your app's functionality.
Always follow these guidelines:

* Clearly explain to users why the permission is needed.
* Handle sensitive data responsibly, respecting user privacy at all times.
* Stay updated on Android’s permission policies to maintain compliance.

> With great power comes great responsibility. Build trust with your users by prioritizing their privacy and offering a transparent experience.

Now, you’re equipped to responsibly read device messages in your Android application.
