AutoDroid Documentation

repository·newbranch·Indexed 19 days ago

https://github.com/mobilellm/autodroid

AutoDroid is a research system built on the DroidBot framework that enables Large Language Models (LLMs) to automate intelligent tasks on smartphones. It includes tools for APK parsing via the App class, support for various input policies (e.g., Greedy DFS/BFS), distributed master/worker architecture, and the DroidTask dataset for mapping tasks to UI states.

Tokens
3.3K
Snippets
13
Records
15
Agent score
67%

What's inside AutoDroid

  1. Understand the DroidTask dataset structure

    newbranch

    The DroidTask dataset is organized by application folders (e.g., applauncher, calendar). Each application folder contains:

    • states/: A folder containing captured application states:
      • Screenshot [n].png: Sequential images of the UI.
      • View hierarchy [n].json: JSON files detailing the UI structure.
    • task[i].yaml: YAML files containing ground truth data for specific tasks.
    • utg.yaml: A file recording data from random user exploration.

    Mapping Tasks to States: To associate a task with a specific visual state:

    1. Open a task[i].yaml file and find the state_str identifier.
    2. Match that state_str with the state_str inside a View hierarchy [k].json file.
    3. Use the index k from the view hierarchy filename to find the corresponding Screenshot [k].png.
  2. Run AutoDroid task automation

    newbranch

    To start an automation task, use the droidbot command. You must have an Android device or emulator connected to your host machine via adb and have configured your GPT API key in tools.py by replacing os.environ['GPT_URL'] with your key.

    Command Arguments:

    • -a <path/to/.apk>: Path to the application APK file.
    • -o <output/of/app>: Directory where the output will be saved.
    • -task <your task>: The specific task description to execute.
    • -keep_env: Flag to keep the environment.
    • -keep_app: Flag to keep the application.
    droidbot -a <path/to/.apk> -o <output/of/app> -task <your task> -keep_env -keep_app
  3. Install AutoDroid

    newbranch

    AutoDroid is built on the DroidBot framework. To install it, ensure you have Python, Java, and the Android SDK installed. You must also add the platform_tools directory from your Android SDK to your system PATH.

    Follow these steps to install via pip:

    1. Clone the repository.
    2. Install the package in editable mode.
    git clone git@github.com:MobileLLM/AutoDroid.git
    cd AutoDroid/
    nip install -e .
  4. Run DroidBot in distributed mode

    newbranch

    DroidBot supports a distributed architecture consisting of a master and worker nodes. Use the -distributed flag to select the mode:

    • -distributed master: Starts a DroidMaster instance. This requires providing the RPC address for workers if applicable, though the CLI primarily initializes the master role.
    • -distributed worker: Starts a DroidBot instance acting as a worker, connecting to a DroidMaster via the -master argument.

    When running as a master, you can also provide QEMU specific configurations like -qemu_hda (the QEMU hda image) and -qemu_no_graphic (to run without a GUI).

    # Example: Start a worker node connecting to a master at a specific address
    python droidbot/start.py -a app.apk -distributed worker -master 127.0.0.1:5000
  5. Get package name and main activity

    newbranch

    The App class provides methods to access core Android identity information:

    • get_package_name(): Returns the application's package name.
    • get_main_activity(): Returns the main activity name. If it cannot be found in the manifest, it attempts to return a value from dumpsys_main_activity (if available).
    package = app.get_package_name()
    main_activity = app.get_main_activity()
  6. Initialize an App instance

    newbranch

    The App class is used to represent an Android application by parsing its APK file. Upon initialization, it extracts metadata such as the package name, app name, main activity, permissions, and activities using androguard. It also calculates file hashes (MD5, SHA-1, SHA-256) and identifies possible broadcast intents.

    Parameters:

    • app_path (str): The local file path to the APK file.
    • output_dir (str, optional): A directory where output files will be stored. If the directory does not exist, it will be created.
    from droidbot.app import App
    
    # Initialize with an APK path
    app = App(app_path="/path/to/your/app.apk", output_dir="./output")
    
    print(f"App Name: {app.app_name}")
    print(f"Package: {app.package_name}")
  7. Configure DroidBot input policies

    newbranch

    The -policy argument determines how DroidBot generates test inputs. The available policies are:

    • POLICY_NONE: No events are sent; requires manual interaction.
    • POLICY_MONKEY: Uses adb shell monkey to send events.
    • POLICY_NAIVE_DFS: Explores the UI using a naive depth-first strategy.
    • POLICY_GREEDY_DFS: Explores the UI using a greedy depth-first strategy.
    • POLICY_NAIVE_BFS: Explores the UI using a naive breadth-first strategy.
    • POLICY_GREEDY_BFS: Explores the UI using a greedy breadth-first strategy.
    # Example: Use greedy depth-first search for UI exploration
    python droidbot/start.py -a app.apk -policy greedy_dfs
  8. Reference: start.py CLI arguments

    newbranch

    The following arguments are available when running start.py via the command line:

    -d, --device_serial       The serial number of target device (use `adb devices` to find)
    -a, --apk_path            The file path to target APK (Required)
    -o, --output_dir          directory of output
    -task, --task             the task to execute, in natural language (Default: "mingle around")
    -script, --script_path    Use a script to customize input for certain states.
    -count, --count            Number of events to generate in total.
    -interval, --interval      Interval in seconds between each two events.
    -timeout, --timeout        Timeout in seconds, -1 means unlimited.
    -debug, --debug            Run in debug mode (dump debug messages).
    -keep_app, --keep_app      Keep the app on the device after testing.
    -keep_env, --keep_env      Keep the test environment (eg. minicap and accessibility service) after testing.
    -grant_perm, --grant_perm  Grant all permissions while installing. Useful for Android 6.0+.
    -is_emulator, --is_emulator Declare the target device to be an emulator.
    -accessibility_auto, --enable_accessibility_hard Enable the accessibility service automatically.
    -ignore_ad, --ignore_ad    Ignore Ad views by checking resource_id.
  9. Reference: DroidBot CLI arguments

    newbranch

    The following command-line arguments are available for configuring a DroidBot session:

    FlagDestinationDescription
    -ddevice_serialThe serial number of the target device (from adb devices).
    -aapk_pathRequired. The file path to the target APK.
    -ooutput_dirDirectory where test outputs are saved. Required if using -cv mode.
    -policyinput_policyPolicy for input generation (e.g., monkey, greedy_dfs, greedy_bfs).
    -distributeddistributedMode: master or worker.
    -mastermasterDroidMaster's RPC address (used by workers).
    -qemu_hdaqemu_hdaThe QEMU's hda image.
    -qemu_no_graphicqemu_no_graphicRun QEMU with -nograpihc parameter.
    -scriptscript_pathPath to a script to customize input for certain states.
    -countcountTotal number of events to generate (integer).
    -intervalintervalSeconds between events (integer).
    -timeouttimeoutTimeout in seconds (-1 for unlimited).
    -cvcv_modeUse OpenCV instead of UIAutomator to identify UI components.
    -debugdebug_modeRun in debug mode (dump debug messages).
    -randomrandom_inputAdd randomness to input events.
    -keep_appkeep_appKeep the app on the device after testing.
    -keep_envkeep_envKeep the test environment (minicap, etc.) after testing.
    -use_method_profilingprofiling_methodRecord method trace (full or sampling rate).
    -grant_permgrant_permGrant all permissions during installation.
    -is_emulatoris_emulatorTreat the target device as an emulator.
    -accessibility_autoenable_accessibility_hardEnable accessibility service automatically.
    -humanoidhumanoidConnect to a Humanoid service (addr:port).
    -ignore_adignore_adIgnore Ad views by checking resource_id.
    -replay_outputreplay_outputDirectory of the DroidBot output to be replayed.
  10. Run DroidBot via CLI

    newbranch

    Use the start.py script to initiate DroidBot testing on an Android application. The script requires an APK path and allows you to specify a target device, a natural language task, and various execution parameters like event counts, intervals, and timeouts.

    Required Arguments:

    • -a / --apk_path: The file path to the target APK.

    Common Optional Arguments:

    • -d / --device_serial: The serial number of the target device (find via adb devices).
    • -task / --task: The task to execute, provided in natural language (e.g., "mingle around").
    • -o / --output_dir: Directory where test outputs will be saved.
    • -count / --count: Total number of events to generate.
    • -interval / --interval: Interval in seconds between events.
    • -timeout / --timeout: Timeout in seconds (-1 for unlimited).
    • -is_emulator / --is_emulator: Flag to treat the device as an emulator.
    • -grant_perm / --grant_perm: Automatically grant all permissions during installation (recommended for Android 6.0+).
    • -debug / --debug: Enable debug mode to dump debug messages.
    python start.py -a /path/to/your/app.apk -d emulator-5554 -task "open the settings and change the brightness"
  11. Retrieve possible broadcast intents

    newbranch

    The get_possible_broadcasts() method scans the APK's manifest for registered receivers and their intent filters. It returns a set of Intent objects representing the actions and categories that the application is capable of receiving via broadcasts.

    broadcasts = app.get_possible_broadcasts()
    for intent in broadcasts:
        print(f"Possible broadcast: {intent}")