Add license keys to an Android app

To license an Android app outside Google Play, add com.licers:licers to Gradle, build a LicenseClient with your public key and .android(applicationContext), and call validate(key) off the main thread. It binds the key to the phone and verifies the server’s Ed25519 signature.

Updated by the Licers team

Set it up

  1. Create a free account and add a product.
  2. Copy your public key and product id from the Integration page. The public key is safe to ship inside your app.
  3. Issue a key: set how many devices it may use, when it expires, and any entitlements.
  4. Add the code below. On the first check the device is bound to the key; past the device limit a new machine is refused.
app/build.gradle.kts
dependencies {    implementation("com.licers:licers:1.0.0")}// Android only, in AndroidManifest.xml:// <uses-permission android:name="android.permission.INTERNET" />
LicenseCheck.kt
import android.content.Contextimport com.licers.LicenseClientimport com.licers.LicenseExceptionimport com.licers.NetworkExceptionimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.withContext // Build it once (for example in your Application class) and reuse it.fun licenseClient(context: Context): LicenseClient =    LicenseClient.builder("YOUR_PUBLIC_KEY")   // safe to ship inside your app        .productId("YOUR_PRODUCT_ID")   // your product: refuses keys for your other products        .appVersion("2.4.1")          // shows in Analytics -> App versions        .android(context)             // device id and model        .build() suspend fun checkLicense(client: LicenseClient, key: String): Boolean = withContext(Dispatchers.IO) {    try {        val result = client.validate(key)        if (!result.valid) {            // Expired, revoked, device limit reached... the server says which.            println("Not licensed: ${result.error}")            return@withContext false        }        println("Licensed. Expires: ${result.expiresAt ?: "never"}")        true    } catch (e: NetworkException) {        // Offline, or the server is down. That is not "unlicensed": try again,        // or allow a few days since the last good check.        println("Could not reach the license server. Please try again.")        false    } catch (e: LicenseException) {        // A forged or replayed answer, or a key for another of your products.        println("License check failed: ${e.message}")        false    }}

Details that matter on Android

  • Calls are blocking network requests. Use Dispatchers.IO, an executor or WorkManager. On the main thread the SDK throws an exception that says so.
  • No ProGuard or R8 rules are needed.
  • It works from Java too, and on a desktop JVM: leave out .android(...) and the device id comes from the operating system.

Handle every outcome

Catch NetworkException (allow a grace period) separately from SignatureException (refuse).

What happenedWhat your app should do
The key is expired, revoked, blocked or over its device limitShow the message the server sent. You can reword every one of them on the Custom Messages page.
The answer has a bad signature or an old nonceRefuse. Somebody is faking the server.
The server cannot be reached, or returns a 5xx errorRetry, or allow a grace period since the last good check. Being offline is not the same as being unlicensed.

Seats, credits, variables and offline files

Entitlements. Switch features on per key: true/false, numbers or text. They come from the signed answer.

Entitlements.kt
import android.content.Contextimport com.licers.LicenseClientimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.withContext // Build it once (for example in your Application class) and reuse it.fun licenseClient(context: Context): LicenseClient =    LicenseClient.builder("YOUR_PUBLIC_KEY")   // safe to ship inside your app        .productId("YOUR_PRODUCT_ID")   // your product: refuses keys for your other products        .appVersion("2.4.1")          // shows in Analytics -> App versions        .android(context)             // device id and model        .build() suspend fun readEntitlements(client: LicenseClient, key: String) = withContext(Dispatchers.IO) {    val result = client.validate(key)    if (!result.valid) {        println("Not licensed: ${result.error}")        return@withContext    }     // Entitlements of this key, for example {"pro": true, "seats": 5, "tier": "gold"}.    // They are read from the signed copy, so nobody can edit them on the way.    if (result.hasFeature("pro")) println("Pro features unlocked")     val seats = result.feature("seats") as? Long ?: 1L          // whole numbers are Long    val tier = result.feature("tier") as? String ?: "basic"    println("Seats: $seats Tier: $tier All: ${result.features}")}

Offline file. Check a signed .lic file with no internet at all, for air-gapped machines. Signature, product, expiry, device and operating system are all checked on the computer.

OfflineCheck.kt
import android.content.Contextimport com.licers.AndroidDeviceimport com.licers.Hwidimport com.licers.InvalidLicenseExceptionimport com.licers.OfflineLicenseimport com.licers.SignatureExceptionimport java.io.File fun checkOffline(context: Context): Boolean {    AndroidDevice.init(context)   // needed once for the device id (not on desktop)     // 1. Show this to the customer. They send it to you, and you create the file    //    for that device: License keys -> ... -> Offline license file.    println("Device id: ${Hwid.get()}")     // 2. Save the file they receive in your app's folder. No network is used here.    val path = File(context.filesDir, "license.lic").path    return try {        val lic = OfflineLicense.verify(            "YOUR_PUBLIC_KEY", path,            expectedProductId = "YOUR_PRODUCT_ID",   // your product        )        // 3. Use it. It never returns an invalid license: it throws instead.        val features = lic["features"] as? Map<*, *> ?: emptyMap<String, Any?>()        println("Licensed to: ${lic["customer"]} Expires (unix time): ${lic["expires_at"] ?: "never"}")        if (features["pro"] == true) println("Pro features unlocked")        true    } catch (e: SignatureException) {        println("The license file is missing, damaged or was edited.")        false    } catch (e: InvalidLicenseException) {        println("License file refused: ${e.message}")   // expired, other device, OS or product        false    }}

Usage credits. Meter what the customer does: “100 exports”, “5,000 AI calls a month”. Spending is all or nothing.

UsageCredits.kt
import android.content.Contextimport com.licers.LicenseClientimport com.licers.UsageExceededExceptionimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.withContext // Build it once (for example in your Application class) and reuse it.fun licenseClient(context: Context): LicenseClient =    LicenseClient.builder("YOUR_PUBLIC_KEY")   // safe to ship inside your app        .productId("YOUR_PRODUCT_ID")   // your product: refuses keys for your other products        .appVersion("2.4.1")          // shows in Analytics -> App versions        .android(context)             // device id and model        .build() suspend fun spendCredit(client: LicenseClient, key: String) = withContext(Dispatchers.IO) {    val result = client.validate(key)   // first: this activates the device on the key    if (!result.valid) {        println("Not licensed: ${result.error}")        return@withContext    }     println("Left: ${client.getUsage(key).remaining}")   // reads only; null = no limit     try {        val usage = client.recordUsage(key, 1)          // spend 1 credit, all or nothing        println("Done. ${usage.remaining} credits left")    } catch (e: UsageExceededException) {        println("Out of credits. Refill: ${e.usage["resets_at"] ?: "buy more"}")    }}

Remote variables. Values you change in the dashboard without shipping an update: a link, a message, a switch.

RemoteVariables.kt
import android.content.Contextimport com.licers.LicenseClientimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.withContext // Build it once (for example in your Application class) and reuse it.fun licenseClient(context: Context): LicenseClient =    LicenseClient.builder("YOUR_PUBLIC_KEY")   // safe to ship inside your app        .productId("YOUR_PRODUCT_ID")   // your product: refuses keys for your other products        .appVersion("2.4.1")          // shows in Analytics -> App versions        .android(context)             // device id and model        .build() suspend fun readVariables(client: LicenseClient, key: String) = withContext(Dispatchers.IO) {    val result = client.validate(key)   // first: this activates the device on the key    if (!result.valid) {        println("Not licensed: ${result.error}")        return@withContext    }     // Values you set on the Remote Variables page. Signed, and only for valid keys.    val url: String? = client.getVariable(key, "download_url")      // null when it isn't set    val theme = client.getVariable(key, "theme", "dark")            // or your own default    val everything: Map<String, String> = client.getVariables(key)  // all this key may see     println("$url $theme $everything")}

Floating seats. Let only N people run the app at the same time, on any computers.

FloatingSeat.kt
import android.content.Contextimport com.licers.LicenseClientimport com.licers.SeatLostListenerimport com.licers.SeatUnavailableExceptionimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.withContext // Build it once (for example in your Application class) and reuse it.fun licenseClient(context: Context): LicenseClient =    LicenseClient.builder("YOUR_PUBLIC_KEY")   // safe to ship inside your app        .productId("YOUR_PRODUCT_ID")   // your product: refuses keys for your other products        .appVersion("2.4.1")          // shows in Analytics -> App versions        .android(context)             // device id and model        .build() suspend fun runWithSeat(client: LicenseClient, key: String) = withContext(Dispatchers.IO) {    try {        // Takes a seat and keeps it with heartbeats on a background thread.        val seat = client.startSession(key, onLost = SeatLostListener { reason ->            println("Seat lost: $reason")   // save the user's work        })        println("Seat taken: ${seat.seatsUsed} of ${seat.seatsMax}")         seat.use {            // ... your app runs here. Call this at safe points (before a save,            // between jobs). It throws once the seat is gone.            it.ensureActive()        }   // closing it frees the seat (or call seat.stop(), fine from onDestroy)    } catch (e: SeatUnavailableException) {        println("No seat: ${e.message}")    }}

Updates. Tell the customer about a new version. Only a valid, active key is given the download link.

UpdateCheck.kt
import android.content.Contextimport com.licers.LicenseClientimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.withContext // Build it once (for example in your Application class) and reuse it.fun licenseClient(context: Context): LicenseClient =    LicenseClient.builder("YOUR_PUBLIC_KEY")   // safe to ship inside your app        .productId("YOUR_PRODUCT_ID")   // your product: refuses keys for your other products        .appVersion("2.4.1")          // shows in Analytics -> App versions        .android(context)             // device id and model        .build() suspend fun checkForUpdate(client: LicenseClient, key: String) = withContext(Dispatchers.IO) {    val update = client.checkUpdate(key, "2.4.1", "stable")   // or "beta"     if (update.updateAvailable) {        println("New version: ${update.version}")        println("What's new: ${update.notes}")        // The answer is signed, but downloadUrl and notes are not: check the URL is        // on your own host, and verify the file against a hash you publish.        println("Download: ${update.downloadUrl}")    } else {        println("You have the latest version.")    }}

Questions and answers

Is this a replacement for Google Play licensing?

It is for apps you sell yourself: direct APK downloads, enterprise and kiosk apps, or other stores. Follow Google Play’s payment rules for apps you publish there.

Does it need any permission besides internet?

No. Only android.permission.INTERNET.

What happens after a factory reset?

The phone may look like a new device. The customer frees the old one in the portal, or you reset devices on the key.

What does it cost?

Nothing today. Every feature is free and unlimited: products, keys, devices, validations, offline files and floating seats. See pricing.