---
title: "Build with Gradle"
description: "Compile your Android app on a cloud Gradle sandbox from any machine, with no local Android SDK, JDK, or keystore."
sidebar:
  order: 2
---

The CLI syncs your source to a Gradle sandbox, runs the project's own Gradle wrapper remotely, and streams the log back. Install the APK on a [cloud emulator](/android/run-emulator), or [sign an AAB and publish it to Google Play](/android/sign-and-publish).

The CLI covers the whole surface. The TypeScript SDK provisions and builds too, but its builds pass signing material explicitly because the [escrowed release key](/android/sign-and-publish#sign-with-the-organizations-upload-key) (`--sign`) is CLI-only:

| Surface | CLI | TypeScript | Python | Go |
|---|---|---|---|---|
| Provision a Gradle sandbox | ✓ | ✓ | via REST | via REST |
| Sync source and run Gradle | ✓ | ✓ | not in SDK | not in SDK |
| Escrowed release signing (`--sign`) | ✓ | pass the material yourself | not in SDK | not in SDK |

The [SDK capability matrix](/reference/sdk#sdk-capability-matrix) covers every other surface.

## Build a project

One command does everything. It creates a Gradle sandbox (or reuses the one remembered for your git worktree), syncs the current directory, and runs `assembleDebug` with the project's Gradle wrapper:

```bash
lim gradle build .
```

Pick other tasks with `--task`; repeat it for several:

```bash
lim gradle build . --task :app:assembleRelease
```

Bare React Native repositories usually need nothing extra: the sandbox finds `android/` on its own. If the Gradle root is nested and auto-discovery is ambiguous, point at it with `--project-path`:

```bash
lim gradle build . --project-path android
```

The sync skips paths your `.gitignore` files exclude. Repeat `--ignore '<regex>'` to skip more paths, and `--include '<regex>'` to force-sync paths that a built-in rule or `.gitignore` would exclude. `--env KEY=VALUE` passes an environment variable to the build, and `--basis-cache-dir` sets where the client keeps its sync cache.

To create the sandbox yourself, for example with labels or a jurisdiction, create it first; the build then uses it:

```bash CLI
lim gradle create --jurisdiction eu --label env=dev --display-name ci-builder
lim gradle build . --task :app:assembleRelease
```

```ts TypeScript
import Limrun from '@limrun/api';

const lim = new Limrun({ apiKey: process.env['LIM_API_KEY'] });

const instance = await lim.gradleInstances.create({
  wait: true,
  reuseIfExists: true,
  metadata: { labels: { session: 'ci-build' } },
});

const gradle = await lim.gradleInstances.createClient({ instance });
await gradle.sync('.');

const build = gradle.gradlebuild({ tasks: [':app:assembleRelease'] });
build.stdout.on('data', (line) => console.log(line));
const { exitCode } = await build;
```

Without `--inactivity-timeout`, a Gradle sandbox is deleted after 10 minutes of inactivity. In TypeScript, each step is explicit: create the instance, open a client, sync, then build.

For long builds, return as soon as the build is accepted with `--detach`, read the log later with `lim gradle logs`, or receive the result on a webhook. [Build logs and webhooks](/ci/build-logs-and-webhooks) covers all three, including the webhook payload's `applicationId`, `versionName`, and `versionCode`.

### Attach or detach an emulator

Prefer attaching the emulator to your Gradle sandbox when iterating on an app. After the first transfer, rebuilds reuse the previous APK and send a binary patch when it is smaller than the full APK. Small rebuilds can be much faster than uploading the full APK to Asset Storage and downloading it to the emulator each time.

Attach an existing emulator to install the latest retained APK and future successful APK builds:

```bash
lim gradle attach-emulator <android-instance-id> --id <gradle-instance-id>
```

To stop automatic installation, detach it:

```bash
lim gradle detach-emulator --id <gradle-instance-id>
```

In TypeScript, use `await gradle.attachEmulator(androidInstance)` and `await gradle.detachEmulator()`. With HTTP, send `DELETE {gradle status.apiUrl}/emulator` using the sandbox's bearer token. Detach cancels an active APK transfer and returns `attached: false`. Repeated requests succeed. Both instances, installed apps, and retained APKs remain available.

### React Native and Expo projects

Expo managed-workflow projects have no `android/` directory. The sandbox detects them, installs dependencies, and runs `expo prebuild` before Gradle. These flags tune that pipeline. Setting any of them forces the Expo pipeline on, and the build fails when no Expo app is detected:

- `--expo-no-clean`: pass `--no-clean` to Expo prebuild to update the existing `android/` directory without deleting it first. Prebuild still skips an unchanged generated project or a complete client-synced native project.
- `--expo-app-dir <path>`: the app directory inside a monorepo, relative to the synced root.
- `--abi <abi>`: which Android ABIs to build (`armeabi-v7a`, `arm64-v8a`, `x86`, `x86_64`, or `all`, which keeps the project's own configuration). Repeatable. Without it, Expo-pipeline builds target `x86_64`, the ABI Limrun Android instances run natively (`arm64-v8a` also works through translation; see [Supported ABIs](/android/run-emulator#supported-abis)). Release and bundle tasks keep the project's own ABI configuration.

```bash
lim gradle build ./my-monorepo --expo-app-dir apps/mobile
```

## Select tools

The sandbox image includes these mise-managed tools:

| Tool | Included compatibility lines | Default |
|---|---|---|
| Node.js (with npm and npx) | 22, 24 | 22 |
| pnpm | 9, 10.13.1, newer 10.x, 11, 12 | 10.13.1 |
| Yarn | 1, 4 | 1 |
| Bun | 1 (stable) | 1 |
| Java | Temurin 17, 21, 25 | Temurin 17 |
| bundletool | 1 | 1 |
| ripgrep (`rg`) | 15 | 15 |

pnpm defaults to 10.13.1. To use the newer bundled 10.x release, set `pnpm = "10"` in a project mise file or run `lim gradle use pnpm@10`.

Builds use your project's Gradle wrapper and AGP version. The image includes Android SDK platforms 36, 36.1, 37.0, and 37.2, with warmed dependencies for AGP 8.13.2 and 9.4.1. Other versions may require downloads. Android SDK, NDK, and CMake packages stay managed by `sdkmanager`.

Select tool versions, install missing ones, and inspect the result:

```bash
lim gradle use node@24 java@temurin-17 pnpm@10.13.1
lim gradle tools install
lim gradle tools
```

What each command does:

- `lim gradle use` selects tools in an existing sandbox after the project has synced. Mise installs a requested version if needed. `--cwd apps/mobile` targets a nested project and `--id` chooses the sandbox.
- `lim gradle tools install` syncs the project and runs `mise install` in the sandbox. `--no-sync` installs the current selections without syncing, `--cwd apps/mobile` targets a nested project, and `--id` chooses an existing sandbox. It never creates or replaces an instance.
- `lim gradle tools` inspects an existing sandbox without syncing or creating an instance. `--sync` uploads local changes first, and `--cwd apps/mobile` inspects a nested project. Both forms need an existing sandbox; `--id` chooses one.

Limrun imports `[tools]` declarations from synced project mise files. Those declarations override package-manager detection and image defaults. npm, pnpm, Yarn, and Bun requests keep their exact version. Other numeric project requests keep their major version; Ruby, Python, Go, Flutter, Dart, and pre-1.0 tools keep `major.minor`. Limrun can update patch and minor releases within those lines on its own, and `latest` opts out of a fixed line.

Each build or run resolves its mise environment once. The first sandbox operation that reads a project mise file runs `mise install` before exporting that environment; this happens once per sandbox. Without a project mise file, commands use the image defaults. Later changes need an explicit `lim gradle tools install`, and so does a failed or cancelled first install, which also stops that operation.

To pin an exact release, run `lim gradle run -- mise use --pin node@24.5.0`. Later operations respect that override, and `lim gradle use node@24` replaces it with a Node 24 selection.

The selected Node is exposed as `NODE_BINARY`, and mise sets `JAVA_HOME`. Sandbox paths such as `HOME`, `PATH`, and the Android SDK locations stay managed.

The sandbox home is `/home/limrun`. Synced projects live under `~/workspaces`, Gradle caches under `~/.gradle`, and Android SDK packages under `~/Android/Sdk`. Added SDK packages and tools stay in the home for later builds on the same instance. Put your own executables in `~/.local/bin`, which is included in `PATH`. Files synced with `--additional-file` to a remote path starting with `~/` land in this same home.

## Private dependency credentials

Use `--additional-file localPath=remotePath` on `lim gradle build`,
`lim gradle sync`, or `lim gradle run` to copy existing credential files
without adding them to the repository:

```bash
lim gradle build . \
  --additional-file "$HOME/.npmrc=~/.npmrc" \
  --additional-file "$HOME/.netrc=~/.netrc"
```

The local `$HOME` expands in your shell. A remote destination starting with
`~/` targets the sandbox home used by builds and tool commands. Other remote
paths are relative to the workspace; use `.npmrc` to place project-specific
npm configuration at the project root.

Repeat the flag for multiple files and on subsequent syncs, since omitting a
previously synced file removes it. Files in the sandbox home are shared by
projects on that instance.

For private-package 401s, check that the required registry configuration
and credentials reached the remote build. If `.npmrc` references an environment
variable such as `${NPM_TOKEN}`, also pass `--env NPM_TOKEN="$NPM_TOKEN"`.
Use file paths, keep credential contents out of logs and commits, and preserve
restrictive local permissions such as `chmod 600` before syncing.

## Run commands

`lim gradle run` syncs the current directory, then runs a one-shot shell command after `--` in the remote workspace with the selected tools. Pass environment variables with `--env`, which `lim gradle build` accepts too:

```bash CLI
lim gradle run -- node --version
lim gradle run --env APP_ENV=staging -- npm run generate
lim gradle build . --env APP_ENV=staging
```

```ts TypeScript
const gradle = await lim.gradleInstances.createClient({ instance });
await gradle.sync('.');
const install = await gradle.run('mise install', { cwd: 'apps/mobile' });
if (install.exitCode !== 0) throw new Error('Tool installation failed');
const result = await gradle.gradlebuild({ env: ['APP_ENV=staging'] });
```

In TypeScript, sync the project first, then call `run` to install tools or run a command. `run` accepts `cwd`, `env`, and `timeoutSeconds` and returns the same streamed process interface as `gradlebuild`.

If a build or command returns HTTP `409` because sync is running, wait for sync to succeed and retry.

CLI options:

- `--no-sync` uses the existing remote workspace instead of syncing first.
- The optional positional directory (`lim gradle run apps/api -- make generate`) is relative to the synced workspace.
- `--timeout` accepts 1 through 21600 seconds and defaults to 3600.
- `--additional-file localPath=remotePath` adds a file from outside the source tree, such as `"$HOME/.netrc=~/.netrc"`; remote `~/` paths target the sandbox home, and other paths are relative to the workspace. Repeat it for several files.

Commands stream their output.

:::note
Commands and builds share one slot per sandbox: starting a new command or build cancels the one that is running.
:::

## Keep builds warm

Reuse the same sandbox for later builds. It keeps dependency caches, compiled outputs, and temporary files until the instance is deleted. The image includes common Gradle distributions and warmed SDK and AGP dependencies. JavaScript packages download when the project first needs them.

`lim gradle build` runs Gradle with `--no-daemon`, so its build JVM exits after each build. Repeat builds start a fresh JVM and reuse the instance's disk caches and compiled outputs. Gradle commands through `lim gradle run` keep their own daemon settings.

`lim gradle build` enables Gradle task-output caching by default. Set `org.gradle.caching=false` in your project's `gradle.properties` to disable it, including for Expo's generated Android project. CMake builds use a C/C++ compiler cache unless the project overrides its compiler launcher. These caches can reuse eligible compilation outputs after a clean build.

To bypass the compiler cache for a build, pass `CCACHE_DISABLE`:

```bash
lim gradle build . --env CCACHE_DISABLE=1
```

This leaves Gradle's task-output cache enabled; disable it separately with the property above. Gradle commands invoked through `lim gradle run` keep their own cache settings.

Tools you install yourself last for the sandbox's lifetime. A new sandbox starts from the image again and does not inherit your installed tools. To carry dependencies and build outputs into the next sandbox, use a [disk snapshot](/android/snapshots). A sandbox the CLI creates uses the same Git-derived project key as Xcode, unless the key is longer than 248 characters or starts with `shared/` or `users/`, which Gradle reserves; then the CLI creates the sandbox without a snapshot.

Dependencies reinstall only when the installed tool versions change. A selected tool that failed to install doesn't trigger reinstalls or block unrelated commands after the first attempt.

## Active/Warm pricing

A Gradle sandbox costs **1 credit a minute while active** and **0.2 credits a minute while warm**. Active time covers builds, commands, source syncs, cache restores and saves, and other requests that change the workspace. Warm time is the rest of the sandbox's lifetime, while it waits for the next request. Emulators are billed separately.

Charges round up to whole credits per instance. Custom billing agreements may differ. If a sandbox leaves no usable activity data, its whole lifetime bills at 0.5 credits a minute.

To stop paying for warm time, delete the sandbox when you finish, or let the [inactivity timeout](#build-a-project) delete it.

## Upload the build artifact

There are two ways to get the artifact out of the sandbox.

**Upload to Asset Storage.** The artifact lives in Limrun's managed storage, and later creates can install it by name. See [Asset Storage](/platform/asset-storage).

```bash CLI
lim gradle build . --upload myapp.apk
lim android create --install-asset=myapp.apk
```

```ts TypeScript
const upload = { target: 'name/myapp.apk' };
const instance = await lim.gradleInstances.create({
  wait: true,
  spec: {
    role: {
      permissions: [
        'asset:name/myapp.apk:create',
        'asset:name/myapp.apk:upload',
        'asset:name/myapp.apk:update',
      ],
    },
  },
});
const gradle = await lim.gradleInstances.createClient({ instance });
await gradle.sync('.');
const { exitCode } = await gradle.gradlebuild({ upload });
```

The uploaded asset expires 14 days after the last upload by default. Each build upload pushes the expiry out again, so actively rebuilt assets stay alive. Pass `--upload-ttl` with a Go duration (`ttl` in the SDK) to change the window: `720h` works, `1d` is not valid Go syntax. Assets uploaded with `lim asset push` are unaffected; they never expire unless given a `--ttl`.

The CLI adds the upload grants when creating the instance. In SDK code, include your own permission strings alongside the upload grants in `spec.role.permissions`. An explicitly selected existing instance must already hold the grants; see [delegated permissions](/access/instance-roles).

Named uploads do not return a download URL. Fetch one separately with `lim asset list --name <asset-name> --download-url` using a credential with `read` permission. Anyone with the signed URL can download the artifact until the signature expires.

**Upload to your own bucket.** Pass a presigned S3, GCS, or R2 URL and the sandbox PUTs the artifact straight to it, without a round trip through the machine that started the build:

```bash CLI
lim gradle build . --signed-upload-url '<presigned-url>'
```

```ts TypeScript
const build = gradle.gradlebuild({ upload: { signedUploadUrl: '<presigned-url>' } });
```

CLI only: `--signed-upload-url` defaults to the `LIM_SIGNED_UPLOAD_URL` environment variable.

To build on every push from a Linux runner, see [GitHub Actions recipes](/ci/github-actions).

## Download a file from remote builder

Use `pull-file` to save a file from an existing builder to your machine:

```bash
lim gradle pull-file /tmp/app.zip ./app.zip --id <instance-id>
```

The remote path can be absolute or relative to the synced project root. Omit the destination to save under the same filename in your current directory.

Wait for the file to finish writing, archive directories first, and download before deleting the instance. Never use logs to transfer files.

## Troubleshooting

| Symptom or message | Cause | Fix |
|---|---|---|
| The build can't find the Gradle root | Auto-discovery found more than one candidate, or the root is nested. | Pass `--project-path <dir>`, for example `--project-path android`. |
| `--expo-app-dir`, `--expo-no-clean`, or `--abi` fails with no Expo app detected | Each flag forces the Expo pipeline on. | Remove the flag for native projects, or point `--expo-app-dir` at the Expo app. |
| A new tool selection has no effect | The first `mise install` already ran for this sandbox. | Run `lim gradle tools install`. |
| The first build fails installing a tool it never uses | A project mise file lists tools beyond the build, such as a monorepo's root `mise.toml`. | Add a `mise.limrun.toml` next to it with only the tools the build needs. Limrun reads it instead of that directory's other mise files; only `[tools]` applies. |
| A running build stops with status `CANCELLED` | Another build or `lim gradle run` started on the same sandbox. | Run one operation at a time per sandbox, or use separate sandboxes. |
| `--upload-ttl 1d` is rejected | `1d` is not a Go duration. | Use hours, for example `24h`. |
| The download URL returns an error after a while | Signed download URLs expire after an hour. | Run `lim asset list --name <asset-name> --download-url` for a fresh one. |

## Next steps

**[Sign and publish](/android/sign-and-publish)**

Sign a release AAB with your organization's upload key and publish it to Google Play.

**[Run an emulator](/android/run-emulator)**

Install the APK the build uploaded and drive the device.

**[Build logs and webhooks](/ci/build-logs-and-webhooks)**

Detach from long builds, read logs later, and receive the result on a webhook.

**[GitHub Actions recipes](/ci/github-actions)**

Build and sign on a plain Linux runner.
