# Android

> Run the checkup in a native Android app, by opening the checkup's page in a Custom Tab: not verified on devices yet.
>
> Preview: proposed, may change.

There is no native Android SDK. A native Android app runs the checkup by opening YOU(th)'s checkup
page in a Chrome Custom Tab. A Custom Tab cannot talk to your app, so the checkup hands over one
message at its end, encrypted for your app, when the person taps "Return to the app". The settings,
results and errors are those of the [Web SDK](/docs/sdks/web).

> **Not verified yet:** YOU(th) has not verified this setup on devices. Its steps and its error
> codes `DELIVERY_NOT_ALLOWED`, `RETURN_TARGET_NOT_ALLOWED` and `CANCELED` may change. Tell your
> YOU(th) contact before you ship it.

Do not run the checkup in a `WebView` inside your app: it cannot run there.

## What it needs

- **A key and the checkup's address**, as for the [Web SDK](/docs/sdks/web#what-your-page-needs).
- **The return to your app switched on for your organization, and your app's package listed.** Ask
  your YOU(th) contact, and give them your `applicationId`, and the exact address of any fallback
  your return address names. In a Custom Tab the checkup cannot see which app opened it, so your
  organization's list of origins does not limit who uses your key there. Your monthly limits and
  revoking the key do.
- **Chrome 113 or later.** The browser asks the person for the camera and the microphone itself, so
  your app needs neither permission.
- **The `androidx.browser` library.**
- **A plan for Google Play review**, which looks closely at apps that run a checkup: see
  [App Store and Google Play](/docs/sdks/app-stores).

## Set it up

Give the activity that receives the result an address of its own, in `AndroidManifest.xml`.
`singleTask` closes the Custom Tab when the result comes back:

```xml
<queries>
    <intent>
        <action android:name="android.support.customtabs.action.CustomTabsService" />
    </intent>
</queries>

<activity android:name=".CheckupActivity" android:exported="true" android:launchMode="singleTask">
    <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="yourapp" android:host="checkup" android:path="/done" />
    </intent-filter>
</activity>
```

## Start the checkup

Make an RSA key pair for each checkup, and open the checkup with three values in the address's
fragment, after `#`, never in its query: a fragment is not sent to any server.

| Value        | What it is                                                                                    |
| ------------ | --------------------------------------------------------------------------------------------- |
| `init`       | The [settings](/docs/sdks/web/reference#settings) as JSON, with your key                      |
| `return_url` | Where the result goes: an `intent://` address for your package, at most 500 characters        |
| `pk`         | The pair's public key, of 2048 bits or more: base64url of its X.509 SubjectPublicKeyInfo form |

```kotlin
import android.content.Context
import android.net.Uri
import android.util.Base64
import androidx.browser.customtabs.CustomTabsClient
import androidx.browser.customtabs.CustomTabsIntent
import java.security.KeyPair
import java.security.KeyPairGenerator
import org.json.JSONObject

object YouthCheckup {
    /** One pair per checkup, until the person comes back. */
    var keyPair: KeyPair? = null

    /** False when the phone has no Chrome to open the checkup in: offer no checkup then. */
    fun start(context: Context, apiKey: String): Boolean {
        val browser = CustomTabsClient.getPackageName(context, listOf("com.android.chrome"), true)
            ?: return false
        val pair = KeyPairGenerator.getInstance("RSA").apply { initialize(2048) }.generateKeyPair()
        keyPair = pair
        val pk = Base64.encodeToString(
            pair.public.encoded,
            Base64.URL_SAFE or Base64.NO_WRAP or Base64.NO_PADDING,
        )
        val init = JSONObject().put("apiKey", apiKey)
        val returnUrl =
            "intent://checkup/done#Intent;scheme=yourapp;package=${context.packageName};end"
        val url = "https://sdk.youth-platform.io/embed.html" +
            "#init=" + Uri.encode(init.toString()) +
            "&return_url=" + Uri.encode(returnUrl) +
            "&pk=" + Uri.encode(pk)

        val tab = CustomTabsIntent.Builder().build()
        tab.intent.setPackage(browser)
        tab.launchUrl(context, Uri.parse(url))
        return true
    }
}
```

This sample keeps the pair in memory. Android can stop your app while the tab is open, and the
result then cannot be read, although the checkup was counted. Keep the private key where it
survives that, such as encrypted storage, and delete it once you have read the result.

The return address must be `intent://…#Intent;scheme=…;package=…;end`, with a lower-case scheme, a
package your organization has listed, and nothing else but an optional `https`
`S.browser_fallback_url` that is listed too. A plain `yourapp://` address and an `https` link are
refused. When the address is refused, the checkup shows an error and sends your app nothing.

## Receive the result

Your activity is opened with `yourapp://checkup/done?message=…`. The message is a JSON envelope:

| Field               | What it holds                                                                 |
| ------------------- | ----------------------------------------------------------------------------- |
| `algorithm`         | Always `RSA-OAEP-SHA256+A256GCM`; refuse anything else                        |
| `encrypted_key`     | An AES-256 key, encrypted with your public key (RSA-OAEP, SHA-256); base64    |
| `iv`                | The AES-GCM nonce, 12 bytes; base64                                           |
| `encrypted_payload` | The message, encrypted with that key, with the 16-byte tag at its end; base64 |

```kotlin
import android.util.Base64
import java.security.PrivateKey
import java.security.spec.MGF1ParameterSpec
import javax.crypto.Cipher
import javax.crypto.spec.GCMParameterSpec
import javax.crypto.spec.OAEPParameterSpec
import javax.crypto.spec.PSource
import javax.crypto.spec.SecretKeySpec
import org.json.JSONObject

fun decryptMessage(envelope: String, privateKey: PrivateKey): JSONObject {
    val box = JSONObject(envelope)
    require(box.getString("algorithm") == "RSA-OAEP-SHA256+A256GCM") { "Unknown algorithm" }
    val decode = { name: String -> Base64.decode(box.getString(name), Base64.DEFAULT) }

    val rsa = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding")
    // Name MGF1's hash: Android's default there is SHA-1, and decryption would fail.
    rsa.init(
        Cipher.DECRYPT_MODE,
        privateKey,
        OAEPParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT),
    )
    val aesKey = SecretKeySpec(rsa.doFinal(decode("encrypted_key")), "AES")

    val aes = Cipher.getInstance("AES/GCM/NoPadding")
    aes.init(Cipher.DECRYPT_MODE, aesKey, GCMParameterSpec(128, decode("iv")))
    return JSONObject(String(aes.doFinal(decode("encrypted_payload")), Charsets.UTF_8))
}
```

Read `intent.data?.getQueryParameter("message")` in `onCreate` and `onNewIntent`, decrypt it with
the pair's private key, and delete the pair. Treat a message that does not decrypt as no message. What comes out is one
[message](/docs/sdks/web/reference#messages): the final `result`, with the
[biomarkers](/docs/sdks/results), or the final `error`. No `progress` is sent, and each tab runs one
checkup.

- **The person closed the tab** when your activity resumes without a message: treat it as a cancel.
- **An error during a measurement** lets the person try again in the tab; your app receives only how
  it ended. A reloaded page ends with `CANCELED`.
- **Anyone can open your activity's address**, with any text: accept only a message that decrypts
  with the pair you made for this checkup.

## Keep it safe

- Anything built into an app can be read out of it, and no origin limits a key in a Custom Tab.
  Fetch the key from your server rather than building it in, and never log the address you open.
- The results are health data: do not log them. Use a new key pair for every checkup.
