Create links from an Android app

After this page, a Share button in your Android app creates a Strait link for the current screen and opens the system share sheet.

On this page 5
  1. 1. Add an endpoint to your server
  2. 2. Call it from the app and share
  3. 3. Read the referrer when the link opens the app
  4. Common errors
  5. Next steps
Time
About 15 minutes
You need
A backend you control, a secret key (Dashboard → Settings → Keys)
Works on
Android

Links are created with the secret key, which must never ship in an app. The app asks your server; your server calls POST /v1/links.

1. Add an endpoint to your server

Use the server code from the React Native page (Node), or call the API from any language:

Terminal
curl https://strait.link/v1/links \
  -H "Authorization: Bearer $SECRET_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "slug": "p42-7f3e2c1a", "longUrl": "https://shop.example.com/product/42?ref=user_123", "campaign": "in_app_share" }'

Slugs are unique within your workspace, so your server should add a random part, and reply to the app with the shortUrl.

You should see: a 201 answer with "shortUrl": "https://hilltop.strait.link/p42-7f3e2c1a".

2. Call it from the app and share

Share.kt
import android.app.Activity
import android.content.Intent
import java.net.HttpURLConnection
import java.net.URL
import org.json.JSONObject

fun Activity.shareProduct(productId: String) = Thread {
    val conn = URL("https://api.yourapp.com/share").openConnection() as HttpURLConnection   // your server
    conn.requestMethod = "POST"
    conn.doOutput = true
    conn.setRequestProperty("Content-Type", "application/json")              // add your own auth header
    conn.outputStream.use { it.write(JSONObject().put("productId", productId).toString().toByteArray()) }
    val url = JSONObject(conn.inputStream.bufferedReader().readText()).getString("url")
    runOnUiThread {
        val send = Intent(Intent.ACTION_SEND).setType("text/plain").putExtra(Intent.EXTRA_TEXT, url)
        startActivity(Intent.createChooser(send, "Share"))
    }
}.start()

You should see: the share sheet with a https://hilltop.strait.link/… link. Tap it on another phone: the app opens on that product.

Kotlin
links.onLink { e -> e.params?.get("ref")?.takeIf { e.matched }?.let(::saveReferrer) } // your own code

You should see: ref set to the sharer's id when a friend opens the link, including after installing from Google Play.

Common errors

  • 401 from Strait. Your server sent the publishable key. Creating links needs a secret key.
  • 409. The slug is already used in your workspace. Make the random part longer.
  • NetworkOnMainThreadException. The request ran on the main thread. Keep it in the background thread, as above.

Next steps