rules_android Stardoc

This Stardoc was built from rules_android commit f356a97503ee6bd0681bb51aa17719f9f6412e2d on 2024 Apr 23, 22:46 UTC.

Rules

aar_import

aar_import(name, deps, data, aar, exports, has_lint_jar, package, srcjar)

Examples

The following example shows how to use aar_import.

aar_import(
    name = "hellobazellib",
    aar = "lib.aar",
    package = "bazel.hellobazellib",
    deps = [
        "//java/bazel/hellobazellib/activities",
        "//java/bazel/hellobazellib/common",
    ],
)

ATTRIBUTES

Name Description Type Mandatory Default
name A unique name for this target. Name required
deps The list of libraries to link against. List of labels optional []
data Files needed by this rule at runtime. May list file or rule targets. Generally allows any target. List of labels optional []
aar The .aar file to process. Label required
exports The closure of all rules reached via exports attributes are considered direct dependencies of any rule that directly depends on the target with exports. The exports are not direct deps of the rule they belong to. List of labels optional []
has_lint_jar Whether the aar contains a lint.jar. This is required to know at analysis time if a lint jar is included in the aar. Boolean optional False
package Package to use while processing the aar at analysis time. This needs to be the same value as the manifest’s package. String optional ""
srcjar A srcjar file that contains the source code for the JVM artifacts stored within the AAR. Label optional None

android_application

android_application(name, app_integrity_config, base_module, bundle_config_file, custom_package,
                    feature_modules, manifest_values, rotation_config, sdk_archives, sdk_bundles)

ATTRIBUTES

Name Description Type Mandatory Default
name A unique name for this target. Name required
app_integrity_config Configuration of the integrity protection options. Provide a path to a binary .binarypb instance of https://github.com/google/bundletool/blob/master/src/main/proto/app_integrity_config.proto Label optional None
base_module - Label optional None
bundle_config_file Path to config.pb.json file, see https://github.com/google/bundletool/blob/master/src/main/proto/config.proto for definition.

Note: this attribute is subject to changes which may require teams to migrate their configurations to a build target.
Label optional None
custom_package - String optional ""
feature_modules - List of labels optional []
manifest_values - Dictionary: String -> String optional {}
rotation_config - Label optional None
sdk_archives - List of labels optional []
sdk_bundles - List of labels optional []

android_binary

android_binary(name, deps, srcs, data, assets, assets_dir, custom_package, debug_key,
               debug_signing_keys, debug_signing_lineage_file, densities, dexopts,
               enable_data_binding, feature_flags, generate_art_profile, incremental_dexing,
               instruments, javacopts, key_rotation_min_sdk, main_dex_list, main_dex_list_opts,
               main_dex_proguard_specs, manifest, manifest_merger, manifest_values, min_sdk_version,
               multidex, native_target, nocompress_extensions, plugins, proguard_apply_mapping,
               proguard_generate_mapping, proguard_optimization_passes, proguard_specs, resource_apks,
               resource_configuration_filters, resource_files, shrink_resources, startup_profiles)

ATTRIBUTES

Name Description Type Mandatory Default
name A unique name for this target. Name required
deps - List of labels optional []
srcs - List of labels optional []
data Files needed by this rule at runtime. May list file or rule targets. Generally allows any target.

The default outputs and runfiles of targets in the data attribute should appear in the *.runfiles area ofany executable which is output by or has a runtime dependency on this target. This may include data files or binaries used when this target’s srcs are executed. See the data dependencies section for more information about how to depend on and use data files.

New rules should define a data attribute if they process inputs which might use other inputs at runtime. Rules’ implementation functions must also populate the target’s runfiles from the outputs and runfiles of any data attribute, as well as runfiles from any dependency attribute which provides either source code or runtime dependencies.
List of labels optional []
assets The list of assets to be packaged. This is typically a glob of all files under the assets directory. You can also reference other rules (any rule that produces files) or exported files in the other packages, as long as all those files are under the assets_dir directory in the corresponding package. List of labels optional []
assets_dir The string giving the path to the files in assets. The pair assets and assets_dir describe packaged assets and either both attributes should be provided or none of them. String optional ""
custom_package Java package for which java sources will be generated. By default the package is inferred from the directory where the BUILD file containing the rule is. You can specify a different package but this is highly discouraged since it can introduce classpath conflicts with other libraries that will only be detected at runtime. String optional ""
debug_key File containing the debug keystore to be used to sign the debug apk. Usually you do not want to use a key other than the default key, so this attribute should be omitted.

WARNING: Do not use your production keys, they should be strictly safeguarded and not kept in your source tree.
Label optional "@rules_android//tools/android:debug_keystore"
debug_signing_keys List of files, debug keystores to be used to sign the debug apk. Usually you do not want to use keys other than the default key, so this attribute should be omitted.

WARNING: Do not use your production keys, they should be strictly safeguarded and not kept in your source tree.
List of labels optional []
debug_signing_lineage_file File containing the signing lineage for the debug_signing_keys. Usually you do not want to use keys other than the default key, so this attribute should be omitted.

WARNING: Do not use your production keys, they should be strictly safeguarded and not kept in your source tree.
Label optional None
densities - List of strings optional []
dexopts - List of strings optional []
enable_data_binding - Boolean optional False
feature_flags - Dictionary: Label -> String optional {}
generate_art_profile Whether to generate ART profile. If true, the ART profile will be generated and bundled into your APK’s asset directory. During APK installation, Android Runtime(ART) will perform Ahead-of-time (AOT) compilation of methods in the profile, speeding up app startup time or reducing jank in some circumstances. Boolean optional True
incremental_dexing - Integer optional -1
instruments - Label optional None
javacopts Extra compiler options for this library. Subject to “Make variable” substitution and Bourne shell tokenization. These compiler options are passed to javac after the global compiler options. List of strings optional []
key_rotation_min_sdk Sets the minimum Android platform version (API Level) for which an APK’s rotated signing key should be used to produce the APK’s signature. The original signing key for the APK will be used for all previous platform versions. String optional ""
main_dex_list - Label optional None
main_dex_list_opts - List of strings optional []
main_dex_proguard_specs - List of labels optional []
manifest - Label optional None
manifest_merger - String optional "auto"
manifest_values - Dictionary: String -> String optional {}
min_sdk_version - Integer optional 0
multidex - String optional "native"
native_target - Label optional None
nocompress_extensions - List of strings optional []
plugins Java compiler plugins to run at compile-time. Every java_plugin specified in the plugins attribute will be run whenever this rule is built. A library may also inherit plugins from dependencies that use exported_plugins. Resources generated by the plugin will be included in the resulting jar of this rule. List of labels optional []
proguard_apply_mapping - Label optional None
proguard_generate_mapping - Boolean optional False
proguard_optimization_passes - Integer optional 0
proguard_specs - List of labels optional []
resource_apks List of resource only apks to link against. List of labels optional []
resource_configuration_filters - List of strings optional []
resource_files The list of resources to be packaged. This is typically a glob of all files under the res directory. Generated files (from genrules) can be referenced by Label here as well. The only restriction is that the generated outputs must be under the same “res” directory as any other resource files that are included. List of labels optional []
shrink_resources - Integer optional -1
startup_profiles List of baseline profiles that were collected at runtime (often from start-up) for this binary. When this is specified, all baseline profiles (including these) are used to inform code optimizations in the build toolchain. This may improve runtime performance at the cost of dex size. If the dex size cost is too large and the performance wins too small, the same profiles can be provided as a dep from an android_library with baseline_profiles to avoid the runtime-focused code optimizations that are enabled by startup_profiles. List of labels optional []

android_library

android_library(name, deps, srcs, data, assets, assets_dir, baseline_profiles, custom_package,
                enable_data_binding, exported_plugins, exports, exports_manifest, idl_import_root,
                idl_parcelables, idl_preprocessed, idl_srcs, idl_uses_aosp_compiler, idlopts,
                javacopts, manifest, neverlink, plugins, proguard_specs, resource_apks,
                resource_files)

Examples

The following example shows how to use android libraries with resources.

android_library(
    name = "hellobazellib",
    srcs = glob(["*.java"]),
    resource_files = glob(["res/**/*"]),
    manifest = "AndroidManifest.xml",
    deps = [
        "//java/bazel/hellobazellib/activities",
        "//java/bazel/hellobazellib/common",
        "//java/bazel/hellobazellib/math",
        "//java/bazel/hellobazellib/service",
    ],
)

The following example shows how to set idl_import_root. Let //java/bazel/helloandroid/BUILD contain:

android_library(
    name = "parcelable",
    srcs = ["MyParcelable.java"], # bazel.helloandroid.MyParcelable
    # MyParcelable.aidl will be used as import for other .aidl
    # files that depend on it, but will not be compiled.
    idl_parcelables = ["MyParcelable.aidl"] # bazel.helloandroid.MyParcelable
    # We don't need to specify idl_import_root since the aidl file
    # which declares bazel.helloandroid.MyParcelable
    # is present at java/bazel/helloandroid/MyParcelable.aidl
    # underneath a java root (java/).
)

android_library(
    name = "foreign_parcelable",
    srcs = ["src/android/helloandroid/OtherParcelable.java"], # android.helloandroid.OtherParcelable
    idl_parcelables = [
        "src/android/helloandroid/OtherParcelable.aidl" # android.helloandroid.OtherParcelable
    ],
    # We need to specify idl_import_root because the aidl file which
    # declares android.helloandroid.OtherParcelable is not positioned
    # at android/helloandroid/OtherParcelable.aidl under a normal java root.
    # Setting idl_import_root to "src" in //java/bazel/helloandroid
    # adds java/bazel/helloandroid/src to the list of roots
    # the aidl compiler will search for imported types.
    idl_import_root = "src",
)

# Here, OtherInterface.aidl has an "import android.helloandroid.CallbackInterface;" statement.
android_library(
    name = "foreign_interface",
    idl_srcs = [
        "src/android/helloandroid/OtherInterface.aidl" # android.helloandroid.OtherInterface
        "src/android/helloandroid/CallbackInterface.aidl" # android.helloandroid.CallbackInterface
    ],
    # As above, idl_srcs which are not correctly positioned under a java root
    # must have idl_import_root set. Otherwise, OtherInterface (or any other
    # interface in a library which depends on this one) will not be able
    # to find CallbackInterface when it is imported.
    idl_import_root = "src",
)

# MyParcelable.aidl is imported by MyInterface.aidl, so the generated
# MyInterface.java requires MyParcelable.class at compile time.
# Depending on :parcelable ensures that aidl compilation of MyInterface.aidl
# specifies the correct import roots and can access MyParcelable.aidl, and
# makes MyParcelable.class available to Java compilation of MyInterface.java
# as usual.
android_library(
    name = "idl",
    idl_srcs = ["MyInterface.aidl"],
    deps = [":parcelable"],
)

# Here, ServiceParcelable uses and thus depends on ParcelableService,
# when it's compiled, but ParcelableService also uses ServiceParcelable,
# which creates a circular dependency.
# As a result, these files must be compiled together, in the same android_library.
android_library(
    name = "circular_dependencies",
    srcs = ["ServiceParcelable.java"],
    idl_srcs = ["ParcelableService.aidl"],
    idl_parcelables = ["ServiceParcelable.aidl"],
)

ATTRIBUTES

Name Description Type Mandatory Default
name A unique name for this target. Name required
deps The list of other libraries to link against. Permitted library types are: android_library, java_library with android constraint and cc_library wrapping or producing .so native libraries for the Android target platform. List of labels optional []
srcs The list of .java or .srcjar files that are processed to create the target. srcs files of type .java are compiled. For readability’s sake, it is not good to put the name of a generated .java source file into the srcs. Instead, put the depended-on rule name in the srcs, as described below.

srcs files of type .srcjar are unpacked and compiled. (This is useful if you need to generate a set of .java files with a genrule or build extension.)
List of labels optional []
data Files needed by this rule at runtime. May list file or rule targets. Generally allows any target.

The default outputs and runfiles of targets in the data attribute should appear in the *.runfiles area ofany executable which is output by or has a runtime dependency on this target. This may include data files or binaries used when this target’s srcs are executed. See the data dependencies section for more information about how to depend on and use data files.

New rules should define a data attribute if they process inputs which might use other inputs at runtime. Rules’ implementation functions must also populate the target’s runfiles from the outputs and runfiles of any data attribute, as well as runfiles from any dependency attribute which provides either source code or runtime dependencies.
List of labels optional []
assets The list of assets to be packaged. This is typically a glob of all files under the assets directory. You can also reference other rules (any rule that produces files) or exported files in the other packages, as long as all those files are under the assets_dir directory in the corresponding package. List of labels optional []
assets_dir The string giving the path to the files in assets. The pair assets and assets_dir describe packaged assets and either both attributes should be provided or none of them. String optional ""
baseline_profiles The list of baseline profiles. They provide a way for developers to provide profile rules and could be used at installation time to speed up app startup and reduce jank. See https://developer.android.com/topic/performance/baselineprofiles/overview for more details. List of labels optional []
custom_package Java package for which java sources will be generated. By default the package is inferred from the directory where the BUILD file containing the rule is. You can specify a different package but this is highly discouraged since it can introduce classpath conflicts with other libraries that will only be detected at runtime. String optional ""
enable_data_binding If true, this rule processes data binding expressions in layout resources included through the resource_files attribute. Without this setting, data binding expressions produce build failures. To build an Android app with data binding, you must also do the following:

1. Set this attribute for all Android rules that transitively depend on this one. This is because dependers inherit the rule’s data binding expressions through resource merging. So they also need to build with data binding to parse those expressions.

2. Add a deps = entry for the data binding runtime library to all targets that set this attribute. The location of this library depends on your depot setup.
Boolean optional False
exported_plugins The list of java_plugins (e.g. annotation processors) to export to libraries that directly depend on this library. The specified list of java_plugins will be applied to any library which directly depends on this library, just as if that library had explicitly declared these labels in plugins. List of labels optional []
exports The closure of all rules reached via exports attributes are considered direct dependencies of any rule that directly depends on the target with exports. The exports are not direct deps of the rule they belong to. List of labels optional []
exports_manifest Whether to export manifest entries to android_binary targets that depend on this target. uses-permissions attributes are never exported. Integer optional 0
idl_import_root Package-relative path to the root of the java package tree containing idl sources included in this library. This path will be used as the import root when processing idl sources that depend on this library.

When idl_import_root is specified, both idl_parcelables and idl_srcs must be at the path specified by the java package of the object they represent under idl_import_root. When idl_import_root is not specified, both idl_parcelables and idl_srcs must be at the path specified by their package under a Java root. See examples
String optional ""
idl_parcelables List of Android IDL definitions to supply as imports. These files will be made available as imports for any android_library target that depends on this library, directly or via its transitive closure, but will not be translated to Java or compiled. Only .aidl files that correspond directly to .java sources in this library should be included (e.g., custom implementations of Parcelable), otherwise idl_srcs should be used.

These files must be placed appropriately for the aidl compiler to find them. See the description of idl_import_root for information about what this means.
List of labels optional []
idl_preprocessed List of preprocessed Android IDL definitions to supply as imports. These files will be made available as imports for any android_library target that depends on this library, directly or via its transitive closure, but will not be translated to Java or compiled. Only preprocessed .aidl files that correspond directly to .java sources in this library should be included (e.g., custom implementations of Parcelable), otherwise use idl_srcs for Android IDL definitions that need to be translated to Java interfaces and use idl_parcelable for non-preprocessed AIDL files. List of labels optional []
idl_srcs List of Android IDL definitions to translate to Java interfaces. After the Java interfaces are generated, they will be compiled together with the contents of srcs. These files will be made available as imports for any android_library target that depends on this library, directly or via its transitive closure.

These files must be placed appropriately for the aidl compiler to find them. See the description of idl_import_root for information about what this means.
List of labels optional []
idl_uses_aosp_compiler Use the upstream AOSP compiler to generate Java files out of idl_srcs.The upstream AOSP compiler provides several new language features that the Google3-only compiler doesn’t provide. For example: structured parcelables, unions, enums, nested type declarations, constant expressions, annotations, and more. See AIDL Doc for more details. Note: the use of the AOSP compiler in google3 is restricted due to performance considerations. This should not be broadly used unless these features are strictly required. Boolean optional False
idlopts Add these flags to the AIDL compiler command. List of strings optional []
javacopts Extra compiler options for this library. Subject to “Make variable” substitution and Bourne shell tokenization. These compiler options are passed to javac after the global compiler options. List of strings optional []
manifest The name of the Android manifest file, normally AndroidManifest.xml. Must be defined if resource_files or assets are defined. Label optional None
neverlink Only use this library for compilation and not at runtime. The outputs of a rule marked as neverlink will not be used in .apk creation. Useful if the library will be provided by the runtime environment during execution. Boolean optional False
plugins Java compiler plugins to run at compile-time. Every java_plugin specified in the plugins attribute will be run whenever this rule is built. A library may also inherit plugins from dependencies that use exported_plugins. Resources generated by the plugin will be included in the resulting jar of this rule. List of labels optional []
proguard_specs Files to be used as Proguard specification. These will describe the set of specifications to be used by Proguard. If specified, they will be added to any android_binary target depending on this library. The files included here must only have idempotent rules, namely -dontnote, -dontwarn, assumenosideeffects, and rules that start with -keep. Other options can only appear in android_binary’s proguard_specs, to ensure non-tautological merges. List of labels optional []
resource_apks List of resource only apks to link against. List of labels optional []
resource_files The list of resources to be packaged. This is typically a glob of all files under the res directory. Generated files (from genrules) can be referenced by Label here as well. The only restriction is that the generated outputs must be under the same “res” directory as any other resource files that are included. List of labels optional []

android_local_test

android_local_test(name, deps, srcs, data, resources, assets, assets_dir, custom_package, densities,
                   env, feature_flags, javacopts, jvm_flags, manifest, manifest_values,
                   nocompress_extensions, plugins, resource_configuration_filters, resource_files,
                   robolectric_properties_file, runtime_deps, stamp, test_class)

ATTRIBUTES

Name Description Type Mandatory Default
name A unique name for this target. Name required
deps The list of libraries to be tested as well as additional libraries to be linked in to the target. All resources, assets and manifest files declared in Android rules in the transitive closure of this attribute are made available in the test.

The list of allowed rules in deps are aar_import, android_library, java_import, java_library, and java_lite_proto_library.
List of labels optional []
srcs The list of source files that are processed to create the target. Required except in special case described below.

srcs files of type .java are compiled. For readability’s sake, it is not good to put the name of a generated .java source file into the srcs. Instead, put the depended-on rule name in the srcs, as described below.

srcs files of type .srcjar are unpacked and compiled. (This is useful if you need to generate a set of .java files with a genrule or build extension.)

All other files are ignored, as long as there is at least one file of a file type described above. Otherwise an error is raised.

The srcs attribute is required and cannot be empty, unless runtime_deps is specified.
List of labels optional []
data Files needed by this rule at runtime. May list file or rule targets. Generally allows any target.

The default outputs and runfiles of targets in the data attribute should appear in the *.runfiles area ofany executable which is output by or has a runtime dependency on this target. This may include data files or binaries used when this target’s srcs are executed. See the data dependencies section for more information about how to depend on and use data files.

New rules should define a data attribute if they process inputs which might use other inputs at runtime. Rules’ implementation functions must also populate the target’s runfiles from the outputs and runfiles of any data attribute, as well as runfiles from any dependency attribute which provides either source code or runtime dependencies.
List of labels optional []
resources A list of data files to include in a Java jar.

If resources are specified, they will be bundled in the jar along with the usual .class files produced by compilation. The location of the resources inside of the jar file is determined by the project structure. Bazel first looks for Maven’s standard directory layout, (a “src” directory followed by a “resources” directory grandchild). If that is not found, Bazel then looks for the topmost directory named “java” or “javatests” (so, for example, if a resource is at <workspace root>/x/java/y/java/z, the path of the resource will be y/java/z. This heuristic cannot be overridden.

Resources may be source files or generated files.
List of labels optional []
assets The list of assets to be packaged. This is typically a glob of all files under the assets directory. You can also reference other rules (any rule that produces files) or exported files in the other packages, as long as all those files are under the assets_dir directory in the corresponding package. List of labels optional []
assets_dir The string giving the path to the files in assets. The pair assets and assets_dir describe packaged assets and either both attributes should be provided or none of them. String optional ""
custom_package Java package for which java sources will be generated. By default the package is inferred from the directory where the BUILD file containing the rule is. You can specify a different package but this is highly discouraged since it can introduce classpath conflicts with other libraries that will only be detected at runtime. String optional ""
densities Densities to filter for when building the apk. A corresponding compatible-screens section will also be added to the manifest if it does not already contain a superset listing. List of strings optional []
env A dictionary of environment variables set for the execution of the test. Will be subject to make variable and $(location) expansion. Dictionary: String -> String optional {}
feature_flags This is a deprecated feature. Do not use it. Dictionary: Label -> String optional {}
javacopts Extra compiler options for this library. Subject to “Make variable” substitution and Bourne shell tokenization. These compiler options are passed to javac after the global compiler options. List of strings optional []
jvm_flags A list of flags to embed in the wrapper script generated for running this binary. Subject to $(location / execpath / rootpath) and “Make variable” substitution, and Bourne shell tokenization.

The wrapper script for a Java binary includes a CLASSPATH definition (to find all the dependent jars) and invokes the right Java interpreter. The command line generated by the wrapper script includes the name of the main class followed by a "$@" so you can pass along other arguments after the classname. However, arguments intended for parsing by the JVM must be specified before the classname on the command line. The contents of jvm_flags are added to the wrapper script before the classname is listed.

Note that this attribute has no effect on *_deploy.jar outputs.
List of strings optional []
manifest The name of the Android manifest file, normally AndroidManifest.xml. Must be defined if resource_files or assets are defined. Label optional None
manifest_values A dictionary of values to be overridden in the manifest. Any instance of ${name} in the manifest will be replaced with the value corresponding to name in this dictionary. applicationId, versionCode, versionName, minSdkVersion, targetSdkVersion and maxSdkVersion will also override the corresponding attributes of the manifest and uses-sdk tags. packageName will be ignored and will be set from either applicationId if specified or the package in the manifest. It is not necessary to have a manifest on the rule in order to use manifest_values. Dictionary: String -> String optional {}
nocompress_extensions A list of file extensions to leave uncompressed in the resource apk. List of strings optional []
plugins Java compiler plugins to run at compile-time. Every java_plugin specified in the plugins attribute will be run whenever this rule is built. A library may also inherit plugins from dependencies that use exported_plugins. Resources generated by the plugin will be included in the resulting jar of this rule. List of labels optional []
resource_configuration_filters A list of resource configuration filters, such as ‘en’ that will limit the resources in the apk to only the ones in the ‘en’ configuration. List of strings optional []
resource_files The list of resources to be packaged. This is typically a glob of all files under the res directory. Generated files (from genrules) can be referenced by Label here as well. The only restriction is that the generated outputs must be under the same “res” directory as any other resource files that are included. List of labels optional []
robolectric_properties_file The robolectric-deps.properties file. Note that the file is not directly accessed from this target, instead we just infer the file path from this. The actual artifact comes implicitly from Robolectric. Label optional "@robolectric//bazel:properties"
runtime_deps Libraries to make available to the final binary or test at runtime only. Like ordinary deps, these will appear on the runtime classpath, but unlike them, not on the compile-time classpath. Dependencies needed only at runtime should be listed here. Dependency-analysis tools should ignore targets that appear in both runtime_deps and deps. List of labels optional []
stamp Whether to encode build information into the binary. Possible values:

- stamp = 1: Always stamp the build information into the binary, even in --nostamp builds. This setting should be avoided, since it potentially kills remote caching for the binary and any downstream actions that depend on it.

- stamp = 0: Always replace build information by constant values. This gives good build result caching.

- stamp = -1: Embedding of build information is controlled by the --[no]stamp flag.

Stamped binaries are not rebuilt unless their dependencies change.
Integer optional 0
test_class The Java class to be loaded by the test runner.

This attribute specifies the name of a Java class to be run by this test. It is rare to need to set this. If this argument is omitted, the Java class whose name corresponds to the name of this android_local_test rule will be used. The test class needs to be annotated with org.junit.runner.RunWith.
String optional ""

android_sdk_repository

android_sdk_repository(name, path, api_level, build_tools_version)

Create a repository with Android SDK bindings and toolchains.

The SDK will be located at the given path, or via the ANDROID_HOME environment variable if the path attribute is unset.

PARAMETERS

Name Description Default Value
name The repository name. none
path The path to the Android SDK. ""
api_level The SDK API level to use. 0
build_tools_version The build_tools in the SDK to use. ""