This document has basic instructions on how to reference an android resource in java. It also attempts to explain what R.java is.
resources_package
in your android_library
target in BUILD.gnandroid_library("java") { sources = [ "java/org/chromium/browser_ui/Widget.java" ] resources_package = "org.chromium.browser_ui" deps = [ "//base:java", "//base:resources", "//third_party/android_deps:com_google_material_material_java", "//third_party/androidx:androidx_core_core_java", ] }
Add a dep on the android_resources
target with your resource.
android_aar_prebuilt
or android_java_prebuilt
for prebuilt targets such as those under //third_party/android_deps
In your java file, import <resources_package>.R;
You can now reference R.<type>.<name>
in your java.
R
classes.R
class from a different package than the one listed as the resources_package
in you android_library
target in BUILD.gn
Android resources are global for the whole app. While you import the R class from a package (eg: org.chromium.base.R
or org.chromium.browser_ui.R
) so you might assume that there are resources under the org.chromium.base
package that are different from org.chromium.browser_ui
, the actual resources from android's point of view are not divided into packages but form a global pool with unique consecutive ids.
The R class is a generated class that contains a mapping from the name of the resources R.string.hello
to its numeric id 0x7f015d14
. The build system generates this R class for you based on the resources in your dependencies.
In the final apk, all the R
classes from all the packages will all inherit from one global R class that has the list of all resources with the final ids as generated by aapt2
(See Life of a Resource for more details on how resources are processed by our build system).
Chrome does not compile all the java in an apk at once. But instead it builds each android_library
separately and then brings them all together in the end. This means that when compiling a single android_library
, the build system does not know the full list of resources that will end up in the apk. Thus, it can't actually generate the final R.class
with real resource ids but instead creates a temporary one that only exists when compiling these library subtargets.
resources_package
in your android_library target tells the build system which package to generate the R class in. During compile, this temporary R.class
will contain only the resources you depend on in your build target.