General Automation Platform

Quick start · about 15 minutes

Your first script:
find it, then tap it.

You will teach GAP to recognise one thing on the screen — a button — and tap it whenever it shows up. It is the pattern almost every automation is built from: look, decide, act, repeat.

1Before you start

  • GAP installed, with Online at the top of its main screen. If not, follow the setup guide first — it takes about ten minutes.
  • The starter tool's folder on your computer (GeneralAutomationPlatform-Starter). This guide uses the copy of Google's adb the tool downloads into it on its first run, to take a screenshot and copy files. If you have never run the tool, run it once first. If adb already works in your terminal (from Android Studio, say), the tool uses that one and downloads nothing, so type plain adb wherever this page shows a path to it. No computer? See the note in step 3 and step 7.
  • Any image editor that can crop — Paint or Photos on Windows, Preview on a Mac, GIMP anywhere.

The example target is the Start button on the stopwatch in the device's Clock app, because nearly every Android device has one. Any button, icon or label works the same way — swap in your own as you go.

Commands on this page follow the computer you pick.

2Make the folder

A GAP script is just a folder. Make one called find-and-tap inside the starter tool's folder, with an images folder inside it. By the end it holds three things:

find-and-tap/
find-and-tap/
├── index.js          what the script does — step 5
├── index.html        its settings page — step 6
└── images/
    └── target.png    the picture it looks for — steps 3 and 4

The folder's name is the name the script gets in GAP's Library.

3Take a screenshot

On the device, open Clock → Stopwatch so the Start button is showing. Then open a terminal in the starter tool's folder (in File Explorer, click the address bar, type cmd and press Enter) (in Terminal, type cd and a space, drag the folder onto the window, and press Return) (cd into it), and run these two lines:

Terminal

  

That leaves screen.png in the folder: a picture of the whole screen, at exactly the size GAP sees it.

No computer? Take an ordinary screenshot on the device (usually Power + Volume down). It is saved at the screen's full size, which is what you need. Crop it on the device in the next step.

adb says “no devices” or “more than one device”? Run the starter tool once and pick your device, so adb is connected to it. With several, put -s and the address the tool lists right after adb, for example adb -s 127.0.0.1:16384 shell ….

4Crop the target

Open screen.png in your image editor, crop it tightly around the Start button, and save the result as images/target.png in your script folder.

screen.png — crop along the dashed line.
images/target.png — just the button, nothing that changes.
  • Crop, never resize. The picture has to be pixel-for-pixel what GAP sees. Shrinking or zooming it breaks the match.
  • Leave out anything that changes, like the running time beside a button. Only the part that always looks the same.
  • Small but distinctive. A smaller picture matches faster, but it must not also look like something else on the screen.
  • Same device. Pictures taken on one screen size won't line up on another, so capture on the device you'll run on.

5Write index.js

This is the script itself. Save it as find-and-tap/index.js:

index.jsDownload
// Find and tap: looks for images/target.png on the screen and taps it.
// The floating bar's Play button calls start(settings); Stop calls stop().

var running = false;
var run = 0;               // which start() is current, if Play is pressed again

function start(settings = {}) {
  const threshold = settings.threshold ?? 0.85;
  const maxTaps = settings.maxTaps ?? 5;

  // The picture to look for, from this script's own folder.
  const target = openImage(getScriptPath() + '/images/target.png');
  if (target === 0) {
    console.log('images/target.png is missing');
    return;
  }
  const { width, height } = getImageSize(target);

  running = true;
  const me = ++run;
  let taps = 0;
  console.log(`looking for a ${width}x${height} target, threshold ${threshold}`);

  try {
    while (running && me === run && taps < maxTaps) {
      const screen = getScreenshot();
      if (screen === 0) {                          // the engine is not ready
        sleep(1000);
        continue;
      }

      const hit = findImage(screen, target);       // best match: {x, y, score}
      releaseImage(screen);                        // screenshots are native memory

      if (hit.score >= threshold) {
        // x, y is the match's top-left corner, so aim for its middle.
        const x = Math.round(hit.x + width / 2);
        const y = Math.round(hit.y + height / 2);
        tap(x, y, 300);
        taps++;
        console.log(`found (score ${hit.score.toFixed(2)}), ` +
                    `tapped ${x},${y} [${taps}/${maxTaps}]`);
        sleep(1500);                               // let the app react
      } else {
        console.log(`not on screen (best ${hit.score.toFixed(2)})`);
        sleep(1000);
      }
    }
  } finally {
    // Runs however the loop ends, even when Stop cuts it short.
    releaseImage(target);
    if (me === run) running = false;
  }
  console.log('done');
}

// Runs while start() is still looping, so it only has to clear the flag.
function stop() {
  running = false;
}
  • start() and stop() are the two names this script's settings page calls (step 6): Play calls one, Stop and ✕ call the other.
  • getScreenshot() takes a fresh picture of the screen, usually in about a millisecond.
  • findImage() slides your picture over the screen and returns the best spot it found, with a score for how alike they are: 1 is a perfect match.
  • tap(x, y, 300) taps there, then waits 300 ms for the app to react.
  • releaseImage() frees each picture once you're done with it. A long run that skips this runs out of memory.
  • The running flag is how stop() ends the loop. It runs while start() is still going, so all it needs to do is clear the flag. run makes sure only the newest start() keeps looping, if Play is pressed while a run is going.
  • The finally block frees the target picture however the loop ends.

6Write index.html

A script's settings page is an ordinary web page that GAP shows when you press ⚙ on the floating bar. This one lets you change the threshold and the number of taps without editing code. Strictly it is optional, but it is also what connects the floating bar's buttons to start() and stop(), so a script without one cannot be started from Play. Save it as find-and-tap/index.html:

index.htmlDownload
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Find and tap</title>
<style>
  body  { margin: 0; padding: 16px; font: 14px/1.5 sans-serif;
          background: #0d1218; color: #eff2f6; }
  h1    { font-size: 16px; margin: 0 0 16px; }
  label { display: flex; justify-content: space-between; align-items: center;
          margin: 0 0 14px; }
  input { width: 90px; padding: 6px 8px; font: inherit; color: inherit;
          background: #171d25; border: 1px solid #313942; border-radius: 8px; }
</style>
</head>
<body>
<h1>Find and tap</h1>
<label>Match threshold
  <input id="threshold" type="number" min="0.5" max="1" step="0.01"
         value="0.85"></label>
<label>Taps before stopping
  <input id="maxTaps" type="number" min="1" value="5"></label>

<script>
  var KEY = 'find-and-tap-settings';
  var IDS = ['threshold', 'maxTaps'];

  // Put back what was saved last time.
  try {
    var saved = JSON.parse(localStorage.getItem(KEY) || '{}');
    IDS.forEach(function (id) {
      if (id in saved) document.getElementById(id).value = saved[id];
    });
  } catch (e) {}

  // Read the form, remember it, and hand it to start().
  function settings() {
    var s = {};
    IDS.forEach(function (id) {
      s[id] = parseFloat(document.getElementById(id).value);
    });
    try { localStorage.setItem(KEY, JSON.stringify(s)); } catch (e) {}
    return s;
  }

  // GAP calls this when a button on the floating bar is pressed.
  function onEvent(type) {
    if (type === 'OnPlayClick') {
      var code = 'start(' + JSON.stringify(settings()) + ');';
      JavaScriptInterface.runScript(code);
      JavaScriptInterface.showMenu();   // closes this panel, so the app is in view
    }
    if (type === 'OnPauseClick' || type === 'OnCloseClick') {
      JavaScriptInterface.runScript('stop();');
    }
  }
</script>
</body>
</html>
  • GAP calls onEvent() when a run starts or ends: OnPlayClick is Play starting a run, OnPauseClick is Stop (■), despite its name, and OnCloseClick is ✕. Pausing and resuming need nothing from the page: GAP freezes the script itself.
  • JavaScriptInterface.runScript() runs a line of code in index.js — here, start({...}) with the form's values. showMenu() then closes the settings panel, so it isn't covering the app the script taps.
  • localStorage remembers the settings between runs, like on any web page.

7Copy it to the device

GAP finds scripts in Download/GeneralAutomationPlatform/scripts/ on the device. From the same terminal:

Terminal

  

The first line makes sure the scripts folder exists; without it, adb would copy the files loose into scripts/. The device now has Download/GeneralAutomationPlatform/scripts/find-and-tap/index.js. Run the same line again whenever you change a file.

No computer? Use the device's Files app. Put the whole find-and-tap folder inside Download → GeneralAutomationPlatform → scripts.

8Run it

  1. Open GAP. On the Library tab, find-and-tap is listed as a script that is on this device. Not there? Leave the Library and come back to it: GAP looks again each time.
  2. Tap the ▶ circle on its card. The floating bar appears: ▶ Play, ■ Stop, ⚙ settings and ✕ close.
  3. Switch to Clock → Stopwatch. To watch the log as it runs, start the command under these steps in your terminal first.
  4. Press ▶ on the bar. The stopwatch starts by itself. Tap its Pause yourself, and the script starts it again. After five starts, its own first one included, the script stops.

The log shows each look and its score. It goes to Download/GeneralAutomationPlatform/logs/ on the device, and to Android's own log, which this shows live (press Ctrl+C to stop watching):

Terminal

  
Log
looking for a 96x96 target, threshold 0.85
found (score 0.98), tapped 270,812 [1/5]
not on screen (best 0.46)
not on screen (best 0.45)
found (score 0.97), tapped 270,812 [2/5]

That's a working script. Press ▶ again to pause it wherever it is, and ■ to end it.

9Tune and fix

The score is your main tool. A true match usually scores above 0.9. Something merely similar lands around 0.5–0.8. Set the threshold between the two: high enough that the wrong things never pass, low enough that the right one always does.

What you seeWhat to do
The best score never gets above about 0.7The picture doesn't match what GAP sees. Take a new screenshot on this device, crop without resizing, and leave out anything that changes.
It taps things that aren't the targetRaise the threshold in the settings (⚙), or crop a more distinctive picture.
It can't see a target that's on screenSomething is covering it in the script's view. On some devices an open settings panel shows up in screenshots as a black area, and the floating bar can sit on the target too. Close the settings panel, or drag the bar aside.
The log says images/target.png is missingCheck the folder: the images folder sits next to index.js, and holds a file named exactly target.png.
The card says there is no index.jsThe folder has no file named exactly index.js. Check the spelling, and on Windows check it wasn't saved as index.js.txt (turn on File name extensions in File Explorer's View menu to see).
Your changes don't take effectCopy the folder over again, close the floating bar with ✕, and start it again from the Library so GAP loads the new files.

10Where to go next

Everything else builds on the same loop. For a bigger, tested example — tapping a moving target, typing, and dragging a slider on a web page — see the Playground. Here are the calls you'll reach for first; the API reference has all of them. Every one is a global, so you call tap(), not gap.tap().

Looking
getScreenshot()The whole screen as an image.
getScreenshotModify(x, y, w, h, rw, rh, q)Just one region, optionally scaled. Faster when you know where to look. Pass 0, 0 for no resize and 100 for no compression.
findImage(screen, picture)The best match: {x, y, score}, where x, y is the top-left corner.
findImages(screen, picture, minScore, max, noOverlap)Every match above a score, for when there are several.
getColor(x, y)The colour of one pixel: {r, g, b, a}. Handy for "is this light on?".
openImage(path) · saveImage(img, path)Load a picture, or save one. Saving a screenshot is a quick way to see what the script saw.
Acting
tap(x, y, wait, holdMs)Tap, with an optional long press.
swipe(x1, y1, x2, y2, wait)A swipe from one point to another.
tapDown · moveTo · tapUpA drag you control step by step.
typing(text) · keycode('BACK')Type text into the focused field; press Home, Back and other keys.
launchApp(package) · foregroundApp()Open an app, or check which one is in front.
Everything else
sleep(ms)Wait. Pause and Stop take effect even while it's waiting.
console.log(…)Write to the log file in GeneralAutomationPlatform/logs/ and to Android's log (tag gap.script).
getScriptPath()This script's own folder, for its pictures and files.

Ideas for what to try next:

  • Look for several pictures in turn, and act differently on each: a tiny state machine.
  • Use getScreenshotModify to look in just one corner of the screen, and watch the loop speed up.
  • Add a floating-bar.json next to index.js to give the bar your script's colours.
  • Share it: publish a source — one JSON file at a URL that lists your scripts — and anyone who adds it under Sources gets your script and its updates.

Stuck, or built something neat? Come and say so in #gap on Discord.