### Invoke DynamicSystemClient.start with image details
Source: https://source.android.com/docs/core/ota/dynamic-system-updates
Example of how to invoke the `start` method on a `DynamicSystemClient` instance, providing the URL and size of the system image to be installed.
```java
DynamicSystemClient aot = new DynamicSystemClient(...)
aot.start(
...URL of the selected image…,
...uncompressed size of the selected image…);
```
--------------------------------
### Manifest and Build Configuration Example
Source: https://source.android.com/docs/core/tests/development/instrumentation
Shows example lines for installing extra apps within the AndroidManifest.xml configuration.
```xml
```
--------------------------------
### DynamicSystemClient API for DSU
Source: https://source.android.com/docs/core/ota/dynamic-system-updates
This Java code snippet shows the `start` method signature within the `DynamicSystemClient` class, used to initiate a Dynamic System installation from a URL.
```java
public class DynamicSystemClient {
...
...
/**
* Start installing DynamicSystem from URL with default userdata size.
*
* @param systemUrl A network URL or a file URL to system image.
* @param systemSize size of system image.
*/
public void start(String systemUrl, long systemSize) {
start(systemUrl, systemSize, DEFAULT_USERDATA_SIZE);
}
```
--------------------------------
### Install Repo and Bazel
Source: https://source.android.com/docs/core/architecture/bootloader/generic-bootloader/gbl-dev
Installs the 'repo' tool and 'bazel-bootstrap' required for building GBL. Ensure these are installed before proceeding with the build process.
```bash
sudo apt install repo bazel-bootstrap
```
--------------------------------
### Sample App Invoking Upgrade Party SDK
Source: https://source.android.com/docs/core/ota/upgrade-party
An example demonstrating how to initialize the `UpgradePartyClient`, check eligibility, and invoke the Upgrade Party activity with error handling. The UI element to start the party is shown or hidden based on eligibility.
```java
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import com.google.android.gms.growth.UpgradeParty;
import com.google.android.gms.growth.UpgradePartyClient;
public class SampleActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final UpgradePartyClient client = UpgradeParty.getClient(this);
// Hide the invocation button initially
View startUpgradePartyButton = findViewById(R.id.__some_button__);
startUpgradePartyButton.setVisibility(View.GONE);
// Register an onClick handler to invoke the Upgrade Party Activity
startUpgradePartyButton
.setOnClickListener(
view -> {
client
.invokeUpgradeParty()
.addOnCompleteListener(
task -> {
if (!task.isSuccessful()) {
// Do something with error, see task.getException()
}
});
});
}
// Check if eligible for an Upgrade Party
client
.isEligibleForUpgradeParty()
.addOnCompleteListener(
task -> {
if (!task.isSuccessful()) {
// Do something with error, see task.getException()
} else {
// Show/Hide invocation button, based on the result
int visibility =
task.getResult() ? View.VISIBLE : View.GONE;
startUpgradePartyButton..setVisibility(visibility);
}
});
}
```
--------------------------------
### Install Module to Product Partition
Source: https://source.android.com/docs/core/architecture/partitions/product-partitions
Use these flags in build files to target the product partition for module installation.
```json
product_specific: true
```
```makefile
LOCAL_PRODUCT_MODULE := true
```
--------------------------------
### Kernel Configuration Match Examples
Source: https://source.android.com/docs/core/architecture/vintf/match-rules
Examples of successful and unsuccessful kernel configuration matches against the matrix requirements.
```text
# comments don't matter
CONFIG_TRI=y
# CONFIG_NOEXIST shouldn't exist
CONFIG_DEC = 4096 # trailing comments and whitespaces are fine
CONFIG_HEX=57005 # 0XDEAD == 57005
CONFIG_STR="str"
CONFIG_EMPTY="" # empty string must have quotes
CONFIG_EXTRA="extra config items are fine too"
```
```text
CONFIG_TRI="y" # mismatch: quotes
CONFIG_NOEXIST=y # mismatch: CONFIG_NOEXIST exists
CONFIG_HEX=0x0 # mismatch; value doesn't match
CONFIG_DEC="" # mismatch; type mismatch (expect int)
CONFIG_EMPTY=1 # mismatch; expects ""
# mismatch: CONFIG_STR is missing
```
--------------------------------
### Fastboot Fetch Command Example
Source: https://source.android.com/docs/core/architecture/bootloader/fastbootd
Demonstrates how to fetch the entire vendor boot partition and stitch the data into an output file.
```bash
fastboot fetch vendor_boot out.img
```
--------------------------------
### Run End-to-End Tests Setup
Source: https://source.android.com/docs/core/graphics/winscope/run
Commands to set up and run end-to-end tests, including starting the remote tool mock and installing the Chrome driver.
```bash
$ npm run start
$ npm run start:remote_tool_mock
$ npm run test:e2e
```
--------------------------------
### Example Board Configuration for Module Loading
Source: https://source.android.com/docs/core/architecture/kernel/boot-time-opt?hl=de
This example demonstrates how to configure board settings to manage module loading for different boot scenarios. It shows how to specify modules for the vendor ramdisk, recovery, and the second initialization phase.
```makefile
BOARD_VENDOR_RAMDISK_KERNEL_MODULES +=
watchdog.ko reset.ko cpufreq.ko
BOARD_VENDOR_RAMDISK_KERNEL_MODULES_LOAD +=
watchdog.ko reset.ko cpufreq.ko
BOARD_VENDOR_RAMDISK_RECOVERY_KERNEL_MODULES_LOAD +=
"fastrpc.ko"
BOARD_VENDOR_KERNEL_MODULES +=
"vendor/lib/modules/$(call modules.list.txt,$(call find-subdir-with-file,lib/modules,vendor/lib/modules))".ko
BOARD_VENDOR_KERNEL_MODULES_LOAD +=
"vendor/lib/modules/$(call modules.list.txt,$(call find-subdir-with-file,lib/modules,vendor/lib/modules))".ko
```
--------------------------------
### Example Instrumentation Test Output
Source: https://source.android.com/docs/core/tests/tradefed/testing/through-tf/instrumentation
This is an example of the output you can expect when running instrumentation tests. It shows the start and end of individual tests and the overall run duration.
```log
07-17 10:55:32 D/InvocationToJUnitResultForwarder: Starting test: android.animation.cts.ValueAnimatorTest#testOfArgb
07-17 10:55:33 D/InvocationToJUnitResultForwarder: Starting test: android.animation.cts.ValueAnimatorTest#testIsRunning
07-17 10:55:34 D/InvocationToJUnitResultForwarder: Starting test: android.animation.cts.ValueAnimatorTest#testGetCurrentPlayTime
07-17 10:55:35 D/InvocationToJUnitResultForwarder: Starting test: android.animation.cts.ValueAnimatorTest#testStartDelay
07-17 10:55:35 I/InvocationToJUnitResultForwarder: Run ended in 2m 20s
```
--------------------------------
### Setup repack_bootimg environment
Source: https://source.android.com/docs/core/tests/vts/vts-on-gsi
Extract the otatools archive and add the binary directory to the system PATH.
```bash
unzip otatools.zip -d otatools
export PATH="${PWD}/otatools/bin:${PATH}"
repack_bootimg --help
```
--------------------------------
### Dump RRO Information
Source: https://source.android.com/docs/core/runtime/rro-troubleshoot
Use this command to get detailed information about an installed RRO, including its package name, target package, and state. This is useful for confirming installation and identifying potential issues.
```bash
adb shell cmd overlay dump [your RRO package name]
```
--------------------------------
### Kernel Log Example: Starting Bugreport Service
Source: https://source.android.com/docs/core/tests/debug/read-bug-reports
This kernel log entry shows the init process starting the 'bugreport' service. It helps in correlating the bug report's initiation with kernel events.
```log
<5>[207064.285315] init: Starting service 'bugreport'...
```
--------------------------------
### Enable RetailDemoModeService
Source: https://source.android.com/docs/core/display/retail-mode
The setup wizard sets `Global.DEVICE_DEMO_MODE` to true to enable retail mode. RetailDemoModeService then creates a demo user, switches to it, enables the custom launcher, and disables SUW.
```java
Global.DEVICE_DEMO_MODE = true;
```
--------------------------------
### System Log Example: Activity Manager Start
Source: https://source.android.com/docs/core/tests/debug/read-bug-reports
This system log entry shows the Activity Manager starting an activity, specifically the home screen intent. It's useful for tracking application launches and user interactions.
```log
10-03 17:19:52.939 1963 2071 I ActivityManager: START u0 {act=android.intent.action.MAIN cat=[android.intent.category.HOME] flg=0x10200000 cmp=com.google.android.googlequicksearchbox/com.google.android.launcher.GEL (has extras)} from uid 1000 on display 0
```
--------------------------------
### Example: Super Partition Size Calculation (With Compression)
Source: https://source.android.com/docs/core/ota/dynamic_partitions/how_to_size_super
Demonstrates calculating the super partition size for a Virtual A/B device with compression enabled, considering specific parameters and available /data space.
```plaintext
FinalDessertSize = 4GB + (4GB * 0.5) = 6GB
FinalOTASnapshotSize = 6GB * 0.7 = 4.2GB
Super = Max(6GB, 6GB + 4.2GB - 1GB) = Max(6GB, 9.2GB) = 9.2GB
```
--------------------------------
### Example CTS Gesture Test Module Configuration
Source: https://source.android.com/docs/core/tests/tradefed/testing/through-suite/android-test-structure
This configuration installs the CtsGestureTestCases.apk and runs instrumentation tests for the android.gesture.cts package.
```xml
```
--------------------------------
### Recommended Stream Configurations Example
Source: https://source.android.com/docs/core/camera/stream-config
Example of an array for a recommended stream configuration supporting 4K and 1080p, specifying use cases for recording and preview.
```c++
[3840, 2160, HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED,
ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT,
(1 << ANDROID_SCALER_AVAILABLE_RECOMMENDED_STREAM_CONFIGURATIONS_RECORD |
1 << ANDROID_SCALER_AVAILABLE_RECOMMENDED_STREAM_CONFIGURATIONS_SNAPSHOT |
1 << ANDROID_SCALER_AVAILABLE_RECOMMENDED_STREAM_CONFIGURATIONS_VIDEO_SNAPSHOT),
1920, 1080, HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED,
ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT,
(1 << ANDROID_SCALER_AVAILABLE_RECOMMENDED_STREAM_CONFIGURATIONS_PREVIEW |
1 << ANDROID_SCALER_AVAILABLE_RECOMMENDED_STREAM_CONFIGURATIONS_RECORD |
1 << ANDROID_SCALER_AVAILABLE_RECOMMENDED_STREAM_CONFIGURATIONS_SNAPSHOT |
1 << ANDROID_SCALER_AVAILABLE_RECOMMENDED_STREAM_CONFIGURATIONS_VIDEO_SNAPSHOT)]
```
--------------------------------
### Multi-device XML Configuration Example
Source: https://source.android.com/docs/core/tests/tradefed/architecture/advanced/multi-device
Defines a Trade Federation test configuration for multiple devices, specifying individual device setups and global options.
```xml
```
--------------------------------
### Host App VM Management
Source: https://source.android.com/docs/core/virtualization/writeavfapp
Java code for the host Android app to prepare the VM configuration, get or create a VirtualMachine instance, and start the VM.
```java
// Prepare the configuration file
VirtualMachineConfig config = new VirtualMachineConfig
.Builder(getApplication(), "assets/vm_config.json")
.build();
// Load (or create) the handle to a VM
VirtualMachine vm = VirtualMachineManager
.getInstance(getApplication())
.getOrCreate("my_vm", config);
// Run the VM
vm.run();
```
--------------------------------
### Configure Post-installation Steps for a Partition
Source: https://source.android.com/docs/core/ota/ab/ab_implement
Set up a post-installation script to run after a partition is updated. Specify the script path relative to the filesystem root and its type.
```makefile
AB_OTA_POSTINSTALL_CONFIG += \
RUN_POSTINSTALL_system=true \
POSTINSTALL_PATH_system=usr/bin/postinst \
FILESYSTEM_TYPE_system=ext4
```
--------------------------------
### Implement JUnit4 Setup and Test Methods
Source: https://source.android.com/docs/core/tests/development/instr-app-e2e
Demonstrates the use of @Before for setup and @Test for individual test method execution.
```java
@Before
public void setup() {
...
@Test
public void testGetProvider_shouldCacheProvider() {
...
```
--------------------------------
### Example CTS UI Rendering Test Module with Metrics Collector
Source: https://source.android.com/docs/core/tests/tradefed/testing/through-suite/android-test-structure
This configuration installs the CtsUiRenderingTestCases.apk, runs instrumentation tests, and collects files from a specified directory after the run.
```xml
```
--------------------------------
### Build Trade Federation from source
Source: https://source.android.com/docs/core/tests/tradefed/development
Commands to initialize the repository, sync the source code, and build the Trade Federation framework.
```bash
cd
mkdir android-latest-release
cd android-latest-release
repo init -u https://android.googlesource.com/platform/manifest -b android-latest-release
repo sync -c -j8
source build/envsetup.sh
lunch aosp_cf_arm64_only_phone-userdebug # or any other device target
m -j tradefed-all
```
--------------------------------
### Filter Functions for Ftrace
Source: https://source.android.com/docs/core/virtualization/pkvm-modules
Use shell-style glob matching to filter which functions are traced by Ftrace. This example traces functions starting with 'pkvm_hyp_driver'. Ensure CONFIG_PKVM_FTRACE is enabled.
```bash
echo "__kvm_nvhe_pkvm_hyp_driver*" > /sys/kernel/tracing/hypervisor/set_ftrace_filter
```
--------------------------------
### Sample Host-Driven JUnit4 Device Test
Source: https://source.android.com/docs/core/tests/tradefed/testing/through-tf/host-driven-test
A basic example of a host-driven JUnit4 test class using DeviceJUnit4ClassRunner. It demonstrates the setup and a simple test to check for device availability.
```java
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
import com.android.tradefed.testtype.BaseHostJUnit4Test;
import org.junit.Assert;
@RunWith(DeviceJUnit4ClassRunner.class)
public class SampleHostJUnit4DeviceTest extends BaseHostJUnit4Test {
@Before
public void setUp() throws Exception {
// Some setup
}
@Test
public void testCheckWeHaveDevice() throws Exception {
Assert.assertNotNull(getDevice());
}
}
```
--------------------------------
### Example Input Device Configuration
Source: https://source.android.com/docs/core/interaction/input/input-device-configuration-files
This snippet shows an example of an input device configuration file, detailing properties for an internal touch screen device.
```properties
# This is an example of an input device configuration file.
# It might be used to describe the characteristics of a built-in touch screen.
# This is an internal device, not an external peripheral attached to the USB
# or Bluetooth bus.
device.internal = 1
# The device should behave as a touch screen, which uses the same orientation
# as the built-in display.
touch.deviceType = touchScreen
touch.orientationAware = 1
# Additional calibration properties...
# etc...
```
--------------------------------
### Reproducing GKI Binaries with Repo
Source: https://source.android.com/docs/core/architecture/kernel/gki-releases
Steps to reproduce GKI binaries by initializing and syncing the kernel manifest repository.
```bash
repo init -u https://android.googlesource.com/kernel/manifest
mv manifest_7364300.xml .repo/manifests
repo init -m manifest_7364300.xml --depth=1
repo sync
```
--------------------------------
### Setup ueventd to support DMA-BUF heaps
Source: https://source.android.com/docs/core/architecture/kernel/dma-buf-heaps
Example configuration for `ueventd.rc` to enable support for a new DMA-BUF system heap. This ensures the device node for the heap is created correctly.
```text
add ueventd configuration for DMA-BUF system heap
```
--------------------------------
### Kernel Configuration Matching Examples
Source: https://source.android.com/docs/core/architecture/vintf/match-rules
Examples illustrating how different value types in the compatibility matrix match entries in `/proc/config.gz`.
```xml
bar
```
```xml
4096
```
```xml
0x1000
```
```xml
0X1000
```
```xml
y
```
```xml
m
```
```xml
n
```
```xml
1-0x3
```
--------------------------------
### Launch deqp Tests Under GDB
Source: https://source.android.com/docs/core/graphics/deqp-testing
Run deqp tests under GDB on the host machine after installing the debug build on the device. This command sets a default breakpoint at the start of deqp execution.
```bash
python android/scripts/debug.py \
--deqp-commandline="--deqp-log-filename=/sdcard/TestLog.qpa --deqp-case=dEQP-GLES2.functional.*"
```
--------------------------------
### Example: Super Partition Size Calculation (Without Compression)
Source: https://source.android.com/docs/core/ota/dynamic_partitions/how_to_size_super
Illustrates calculating the super partition size for a Virtual A/B device with specific parameters, assuming no compression and available /data space.
```plaintext
FinalDessertSize = 4GB + (4GB * 0.5) = 6GB
Super = Max(6GB, 6GB * 2 - 1GB) = Max(6GB, 11GB)
```
--------------------------------
### Event Log Output
Source: https://source.android.com/docs/core/tests/debug/read-bug-reports
Example output from the event log, showing process start and bound events. Use `logcat -b events -v threadtime -d *:v` to capture this data.
```text
------ EVENT LOG (logcat -b events -v threadtime -d *:v) ------
09-28 13:47:34.179 785 5113 I am_proc_bound: [0,23054,com.google.android.gms.unstable]
09-28 13:47:34.777 785 1975 I am_proc_start: [0,23134,10032,com.android.chrome,broadcast,com.android.chrome/org.chromium.chrome.browser.precache.PrecacheServiceLauncher]
09-28 13:47:34.806 785 2764 I am_proc_bound: [0,23134,com.android.chrome]
...
```
--------------------------------
### Get AIDL HAL Instance Names in C++
Source: https://source.android.com/docs/core/architecture/aidl/aidl-hals
Retrieve a list of all installed AIDL HAL instances on the system using this helper function in C++. This is useful for testing individual HAL services.
```cpp
android::getAidlHalInstanceNames
```
--------------------------------
### Touchscreen Configuration Example
Source: https://source.android.com/docs/core/interaction/input/touch-devices
This is an example input device configuration file for a touch screen supporting pressure, size, and orientation. It demonstrates how to set basic parameters and calibration values.
```ini
# Input device configuration file for a touch screen that supports pressure,
# size and orientation. The pressure and size scale factors were obtained
# by measuring the characteristics of the device itself and deriving
# useful approximations based on the resolution of the touch sensor and the
# display.
#
# Note that these parameters are specific to a particular device model.
# Different parameters need to be used for other devices.
# Basic Parameters
touch.deviceType = touchScreen
touch.orientationAware = 1
# Size
# Based on empirical measurements, we estimate the size of the contact
# using size = sqrt(area) * 28 + 0.
touch.size.calibration = area
touch.size.scale = 28
touch.size.bias = 0
touch.size.isSummed = 0
# Pressure
# Driver reports signal strength as pressure.
#
# A normal index finger touch typically registers about 80 signal strength
# units although we don't expect these values to be accurate.
touch.pressure.calibration = amplitude
touch.pressure.scale = 0.0125
```
--------------------------------
### Configure APEX for Multi-ABI Native Libraries and Binaries
Source: https://source.android.com/docs/core/ota/apex
This example demonstrates how to use the `multilib` property to control the installation of native shared libraries and binaries for different ABIs on a device that supports both 32-bit and 64-bit architectures.
```gradle
apex {
// other properties are omitted
native_shared_libs: ["libFoo"], // installed for 32 and 64
binaries: ["exec1"], // installed for 64, but not for 32
multilib: {
first: {
native_shared_libs: ["libBar"], // installed for 64, but not for 32
binaries: ["exec2"], // same as binaries without multilib.first
},
both: {
native_shared_libs: ["libBaz"], // same as native_shared_libs without multilib
binaries: ["exec3"], // installed for 32 and 64
},
prefer32: {
native_shared_libs: ["libX"], // installed for 32, but not for 64
},
lib64: {
native_shared_libs: ["libY"], // installed for 64, but not for 32
},
},
}
```
--------------------------------
### GTest with Tuple Parameter
Source: https://source.android.com/docs/core/tests/vts/gtest
Use `std::tuple` as the test parameter for GTests requiring multiple inputs, such as testing multiple interfaces. This example shows how to set up the test class and access parameters within `SetUp`.
```cpp
class GraphicsMapperHidlTest
: public ::testing::TestWithParam> {
protected:
void SetUp() override {
ASSERT_NO_FATAL_FAILURE(mGralloc = std::make_unique(std::get<0>(GetParam()),
std::get<1>(GetParam())));
…
```
--------------------------------
### Vendor Boot Partition Configuration Example
Source: https://source.android.com/docs/core/architecture/bootloader/partitions/vendor-boot-partitions
This configuration sets up vendor ramdisk fragments, including DLKM directories and mkbootimg arguments. Use this to define custom vendor ramdisks.
```makefile
BOARD_KERNEL_MODULE_DIRS := foo bar baz
BOARD_BOOT_HEADER_VERSION := 4
BOARD_VENDOR_RAMDISK_FRAGMENTS := dlkm_foobar
BOARD_VENDOR_RAMDISK_FRAGMENT.dlkm_foobar.KERNEL_MODULE_DIRS := foo bar
BOARD_VENDOR_RAMDISK_FRAGMENT.dlkm_foobar.MKBOOTIMG_ARGS := --board_id0 0xF00BA5 --board_id1 0xC0FFEE
```
--------------------------------
### Example recovery.fstab Configuration
Source: https://source.android.com/docs/core/ota/nonab/device_code
This example shows various mount points, filesystem types, and device configurations for the recovery.fstab file. It includes optional device2 and options fields.
```text
# mount point fstype device [device2] [options (3.0+ only)]
/sdcard vfat /dev/block/mmcblk0p1 /dev/block/mmcblk0
/cache yaffs2 cache
/misc mtd misc
/boot mtd boot
/recovery emmc /dev/block/platform/s3c-sdhci.0/by-name/recovery
/system ext4 /dev/block/platform/s3c-sdhci.0/by-name/system length=-4096
/data ext4 /dev/block/platform/s3c-sdhci.0/by-name/userdata
```
--------------------------------
### System Log Example: Dumpstate Begin
Source: https://source.android.com/docs/core/tests/debug/read-bug-reports
This system log entry indicates the start of the dumpstate process, which is used to generate a bug report. It's a key marker for identifying the bug report's initiation time.
```log
10-03 17:19:54.322 19398 19398 I dumpstate: begin
```
--------------------------------
### Dynamic Color Customization Options (Android 13+)
Source: https://source.android.com/docs/core/display/material
Starting with Android 13, theme styles are configured via JSON, replacing deprecated accent color attributes. This JSON shows an example of expressive theme style.
```json
{
"android.theme.customization.system_palette":"B1611C",
"android.theme.customization.theme_style":"EXPRESSIVE"
}
```
--------------------------------
### C++ Example: Accessing and Setting System Properties
Source: https://source.android.com/docs/core/architecture/sysprops-apis
Illustrates using generated C++ APIs to read 'ro.build.date' and 'device.status', and set 'device.status'. Demonstrates checking for value presence and using default values.
```c++
#include
using namespace android::sysprop;
…
void bar() {
…
// read "ro.build.date". default value is "(unknown)"
std::string build_date = PlatformProperties::build_date().value_or("(unknown)");
// set "device.status" to "on" if it's "unknown" or not set
using PlatformProperties::device_status_values;
auto status = PlatformProperties::device_status();
if (!status.has_value() || status.value() == device_status_values::UNKNOWN) {
PlatformProperties::device_status(device_status_values::ON);
}
…
}
…
```
--------------------------------
### Chain wait-until-ready with getstatus
Source: https://source.android.com/docs/core/perf/trade-in-mode
This example demonstrates how to chain the `wait-until-ready` command with `getstatus` to first ensure the system is ready and then retrieve the trade-in mode status. This pattern is useful for scripting and automation.
```bash
adb shell tradeinmode wait-until-ready getstatus
```
--------------------------------
### Example SDK Usage for Upgrade Invite
Source: https://source.android.com/docs/core/ota/upgrade_invite
Demonstrates how to use the UpgradePartyClient to check eligibility and invoke the upgrade invite activity. Handles task completion and UI updates based on eligibility.
```java
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import com.google.android.gms.growth.UpgradeParty;
import com.google.android.gms.growth.UpgradePartyClient;
public class SampleActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final UpgradePartyClient client = UpgradeParty.getClient(this);
// Hide the invocation button initially
View startUpgradeInviteButton = findViewById(R.id.__some_button__);
startUpgradeInviteButton.setVisibility(View.GONE);
// Register an onClick handler to invoke the Upgrade Party Activity
startUpgradeInviteButton
.setOnClickListener(
view -> {
client
.invokeUpgradeInvite()
.addOnCompleteListener(
task -> {
if (!task.isSuccessful()) {
// Do something with error, see task.getException()
}
});
});
}
// Check if eligible for an Upgrade Party
client
.isEligibleForUpgradeInvite()
.addOnCompleteListener(
task -> {
if (!task.isSuccessful()) {
// Do something with error, see task.getException()
} else {
// Show/Hide invocation button, based on the result
int visibility =
task.getResult() ? View.VISIBLE : View.GONE;
startUpgradeInviteButton.setVisibility(visibility);
}
});
}
```
--------------------------------
### AndroidTest.xml Configuration for Multi-Device Test
Source: https://source.android.com/docs/core/tests/tradefed/testing/through-suite/multi-devices-suites
This XML configuration defines a multi-device test suite. It specifies two devices, 'device1' and 'device2', with individual setup steps including APK installation and command execution. It also configures the Mobly test runner.
```xml
```
--------------------------------
### Install OmniLab ATS with Installer
Source: https://source.android.com/docs/core/tests/development/android-test-station/ats-user-guide
Run this command to download and execute the OmniLab ATS installer script. This method installs and configures all necessary programs and resources.
```bash
curl https://storage.googleapis.com/android-mtt.appspot.com/prod/install.sh | bash
```
--------------------------------
### Example PGO Configuration for a cc_library
Source: https://source.android.com/docs/core/perf/pgo
This snippet shows how to enable PGO with instrumentation and specify benchmarks and a profile file for a native library.
```json
cc_library {
name: "libexample",
srcs: [
"src1.cpp",
"src2.cpp",
],
static: [
"libstatic1",
"libstatic2",
],
shared: [
"libshared1",
]
pgo: {
instrumentation: true,
benchmarks: [
"benchmark1",
"benchmark2",
],
profile_file: "example.profdata",
}
}
```
--------------------------------
### Example: Super Partition Size (With Compression)
Source: https://source.android.com/docs/core/ota/dynamic_partitions/how_to_size_super
Demonstrates the calculation for a 4 GB factory size and 50% expected growth with compression, resulting in a 10.2 GB super partition.
```plaintext
FinalDessertSize = 4GB + (4GB * 0.5) = 6GB
FinalOTASnapshotSize = 6GB * 0.7 = 4.2GB
Super = 6GB + 4.2GB = 10.2GB
```
--------------------------------
### Configure BLE 2M PHY Advertising with Dynamic Updates
Source: https://source.android.com/docs/core/connect/bluetooth/ble_advertising
Sets up Bluetooth LE advertising using the 2M PHY, disabling legacy mode. This example includes checks for feature support, configures advertising data with potentially large payloads, and demonstrates modifying advertising data dynamically after the set has started. It also shows how to pause and resume advertising.
```java
void example2() {
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
BluetoothLeAdvertiser advertiser =
BluetoothAdapter.getDefaultAdapter().getBluetoothLeAdvertiser();
// Check if all features are supported
if (!adapter.isLe2MPhySupported()) {
Log.e(LOG_TAG, "2M PHY not supported!");
return;
}
if (!adapter.isLeExtendedAdvertisingSupported()) {
Log.e(LOG_TAG, "LE Extended Advertising not supported!");
return;
}
int maxDataLength = adapter.getLeMaximumAdvertisingDataLength();
AdvertisingSetParameters.Builder parameters = (new AdvertisingSetParameters.Builder())
.setLegacyMode(false)
.setInterval(AdvertisingSetParameters.INTERVAL_HIGH)
.setTxPowerLevel(AdvertisingSetParameters.TX_POWER_MEDIUM)
.setPrimaryPhy(BluetoothDevice.PHY_LE_1M)
.setSecondaryPhy(BluetoothDevice.PHY_LE_2M);
AdvertiseData data = (new AdvertiseData.Builder()).addServiceData(new
ParcelUuid(UUID.randomUUID()),
"You can fit large amounts of data up to maxDataLength. This goes up to 1650 bytes. For legacy advertising this would not work".getBytes()).build();
AdvertisingSetCallback callback = new AdvertisingSetCallback() {
@Override
public void onAdvertisingSetStarted(AdvertisingSet advertisingSet, int txPower, int status) {
Log.i(LOG_TAG, "onAdvertisingSetStarted(): txPower:" + txPower + " , status: "
+ status);
currentAdvertisingSet = advertisingSet;
}
@Override
public void onAdvertisingSetStopped(AdvertisingSet advertisingSet) {
Log.i(LOG_TAG, "onAdvertisingSetStopped():");
}
};
advertiser.startAdvertisingSet(parameters.build(), data, null, null, null, callback);
// After the set starts, you can modify the data and parameters of currentAdvertisingSet.
currentAdvertisingSet.setAdvertisingData((new
AdvertiseData.Builder()).addServiceData(new ParcelUuid(UUID.randomUUID()),
"Without disabling the advertiser first, you can set the data, if new data is less than 251 bytes long.".getBytes()).build());
// Wait for onAdvertisingDataSet callback...
```