<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Quokkaman on Medium]]></title>
        <description><![CDATA[Stories by Quokkaman on Medium]]></description>
        <link>https://medium.com/@quokkaman?source=rss-14e3cc4acf91------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*w_kzE26jISKW6PYHg-TwMA.png</url>
            <title>Stories by Quokkaman on Medium</title>
            <link>https://medium.com/@quokkaman?source=rss-14e3cc4acf91------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 23:52:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@quokkaman/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Inside FontFamily: The Four Faces of Compose Fonts]]></title>
            <link>https://quokkaman.medium.com/inside-fontfamily-the-four-faces-of-compose-fonts-c5aad0f0fd59?source=rss-14e3cc4acf91------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5aad0f0fd59</guid>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[aosp]]></category>
            <category><![CDATA[font-family]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[framework]]></category>
            <dc:creator><![CDATA[Quokkaman]]></dc:creator>
            <pubDate>Sun, 07 Jun 2026 06:22:21 GMT</pubDate>
            <atom:updated>2026-06-07T06:22:21.581Z</atom:updated>
            <content:encoded><![CDATA[<h4>How Compose’s FontFamily Implementations Take Different Paths to Typeface Resolution</h4><h3>Introduction</h3><p>In the previous article, we explored how Jetpack Compose separates font resolution from UI components through FontFamily.Resolver.</p><p><a href="https://quokkaman.medium.com/how-compose-separates-font-resolution-from-ui-components-1fa214b5eae7">How Compose Separates Font Resolution from UI Components</a></p><p>Rather than allowing a Text composable to resolve fonts directly, Compose routes every font request through a dedicated resolution pipeline before eventually producing an android.graphics.Typeface.</p><p>Understanding that pipeline explains how Compose resolves fonts. However, it leaves another important question unanswered:</p><p><strong>What exactly is a FontFamily?</strong></p><p>When working with text in Compose, there are several different ways to create one.</p><p>We can use the platform default font:</p><pre>FontFamily.Default</pre><p>We can choose one of the generic font families provided by the platform:</p><pre>FontFamily.SansSerif<br>FontFamily.Serif<br>FontFamily.Monospace<br>FontFamily.Cursive</pre><p>We can reference a font that is already installed on the device:</p><pre>FontFamily(<br>    Font(<br>        DeviceFontFamilyName(&quot;sec&quot;)<br>    )<br>)</pre><p>We can build a font family from application font resources:</p><pre>FontFamily(<br>    Font(R.font.my_font_regular),<br>    Font(R.font.my_font_bold)<br>)</pre><p>Or we can wrap an existing native Typeface instance:</p><pre>FontFamily(nativeTypeface)</pre><p>Although these APIs all produce a FontFamily object, they do not represent the same thing internally.</p><p>Some correspond to platform-provided font families. Some describe font resources that must be matched according to weight and style. Others reference fonts installed on the device, while some simply wrap an already-existing native Typeface.</p><p>As a result, each of these font families follows a different resolution path inside Compose’s font system.</p><p>At first glance, it may seem that Compose provides a single FontFamily abstraction. In reality, that abstraction is backed by several distinct implementations:</p><pre>FontFamily<br>├─ DefaultFontFamily<br>├─ GenericFontFamily<br>├─ FontListFontFamily<br>│  ├─ ResourceFont<br>│  └─ DeviceFontFamilyNameFont<br>└─ LoadedFontFamily</pre><p>This distinction is important because the specific FontFamily implementation determines:</p><ul><li>Which adapter handles the request</li><li>Whether font matching is required</li><li>How the font is loaded</li><li>How the final native Typeface is produced</li></ul><p>In this article, we’ll examine each way of creating a FontFamily, explore the implementation behind it, and follow the path it takes through Compose&#39;s font resolution architecture.</p><h3>2. The Hidden Hierarchy Behind FontFamily</h3><p>At the API level, Compose exposes FontFamily as a single abstraction.</p><p>Whether we’re using the default font, a generic family such as SansSerif, a device-installed font, a custom font resource, or an existing Typeface, everything appears to be represented by the same FontFamily type.</p><pre>Text(<br>    text = &quot;Hello Compose&quot;,<br>    style = TextStyle(<br>        fontFamily = FontFamily.Default<br>    )<br>)</pre><pre>Text(<br>    text = &quot;Hello Compose&quot;,<br>    style = TextStyle(<br>        fontFamily = FontFamily.SansSerif<br>    )<br>)</pre><pre>Text(<br>    text = &quot;Hello Compose&quot;,<br>    style = TextStyle(<br>        fontFamily = FontFamily(<br>            Font(R.font.my_font)<br>        )<br>    )<br>)</pre><p>From the perspective of a Text composable, these font families are interchangeable. They all satisfy the same API contract.</p><p>Internally, however, Compose represents them using several different implementations.</p><p>If we look at the source code, FontFamily is defined as a sealed class:</p><pre>@Immutable<br>sealed class FontFamily</pre><p>This allows Compose to expose a single public API while maintaining specialized implementations for different font-family types.</p><p>The hierarchy can be simplified as follows:</p><pre>FontFamily<br>├─ DefaultFontFamily<br>├─ GenericFontFamily<br>├─ FontListFontFamily<br>│  ├─ ResourceFont<br>│  └─ DeviceFontFamilyNameFont<br>└─ LoadedFontFamily</pre><p>Let’s briefly examine the role of each implementation before diving into them individually.</p><h3>DefaultFontFamily</h3><p>FontFamily.Default represents the platform&#39;s default font family.</p><pre>FontFamily.Default</pre><p>Rather than describing a specific font resource, it acts as a marker indicating that Compose should use the default typeface provided by the platform.</p><p>Internally, this implementation is represented by DefaultFontFamily.</p><h3>GenericFontFamily</h3><p>Generic font families correspond to well-known platform font categories.</p><pre>FontFamily.SansSerif<br>FontFamily.Serif<br>FontFamily.Monospace<br>FontFamily.Cursive</pre><p>These families are not backed by application resources. Instead, they represent generic font family names that are understood by the underlying platform.</p><pre>sans-serif<br>serif<br>monospace<br>cursive</pre><p>Internally, these are represented by GenericFontFamily.</p><h3>FontListFontFamily</h3><p>FontListFontFamily is used whenever a font family is constructed from one or more Font descriptors.</p><p>This includes custom font resources:</p><pre>val AppFontFamily = FontFamily(<br>    Font(<br>        R.font.roboto_regular,<br>        weight = FontWeight.Normal<br>    ),<br>    Font(<br>        R.font.roboto_medium,<br>        weight = FontWeight.Medium<br>    ),<br>    Font(<br>        R.font.roboto_bold,<br>        weight = FontWeight.Bold<br>    ),<br>    Font(<br>        R.font.roboto_italic,<br>        style = FontStyle.Italic<br>    )<br>)</pre><p>and device-installed fonts:</p><pre>val SamsungOne = FontFamily(<br>    Font(<br>        DeviceFontFamilyName(&quot;sec&quot;)<br>    )<br>)</pre><p>Unlike DefaultFontFamily and GenericFontFamily, these font families contain actual font definitions.</p><p>Internally, both approaches are represented by FontListFontFamily, although they use different Font implementations.</p><p>We’ll explore these implementations in more detail later in the article.</p><h3>LoadedFontFamily</h3><p>Compose also provides a way to wrap an already-existing native Typeface.</p><pre>FontFamily(nativeTypeface)</pre><p>In this case, the typeface already exists before Compose begins the resolution process.</p><p>Internally, this implementation is represented by LoadedFontFamily and serves as a bridge between Compose&#39;s font abstractions and platform-specific typefaces.</p><p>Although Compose exposes a single FontFamily API, it is actually backed by several different implementations.</p><p>Some represent platform-provided font families. Some describe collections of font definitions. Others simply wrap an existing Typeface.</p><p>From the perspective of a Text composable, these differences are largely hidden behind the FontFamily abstraction. Internally, however, Compose uses each implementation for a different purpose.</p><p>Now that we’ve seen the overall hierarchy, let’s examine each implementation individually, beginning with FontFamily.Default.</p><h3>3. FontFamily.Default</h3><p>Let’s start with the simplest font family provided by Compose:</p><pre>FontFamily.Default</pre><p>Most Compose applications use FontFamily.Default, either explicitly or implicitly.</p><pre>Text(<br>    text = &quot;Hello Compose&quot;,<br>    style = TextStyle(<br>        fontFamily = FontFamily.Default<br>    )<br>)</pre><p>Even when no fontFamily is specified, Compose ultimately falls back to the platform&#39;s default font family.</p><p>At first glance, FontFamily.Default appears to be just another FontFamily instance. However, if we inspect the source code, we find that it has its own dedicated implementation.</p><p><a href="https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:compose/ui/ui-text/src/commonMain/kotlin/androidx/compose/ui/text/font/FontFamily.kt;drc=20573118bfaf11b88910aebb6f512ee843553ae3;l=34?q=SystemFontFamily&amp;ss=androidx">FontFamily.kt</a></p><pre>sealed class FontFamily(canLoadSynchronously: Boolean)</pre><pre>sealed class SystemFontFamily : FontFamily(true)<br>internal class DefaultFontFamily : SystemFontFamily()<br>val Default: SystemFontFamily = DefaultFontFamily()</pre><p>When developers write:</p><pre>FontFamily.Default</pre><p>they are actually using an instance of DefaultFontFamily, exposed through the SystemFontFamily abstraction.</p><p>The hierarchy looks like this:</p><pre>FontFamily<br>└─ SystemFontFamily<br>   └─ DefaultFontFamily</pre><p>This tells us something important: DefaultFontFamily does not represent an application font resource. Instead, it represents a font family provided by the underlying platform.</p><h3>Resolution Path</h3><p>When a text request reaches FontFamily.Resolver, Compose eventually identifies the font family as a DefaultFontFamily and delegates the request to the platform resolver.</p><p><a href="https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:compose/ui/ui-text/src/androidMain/kotlin/androidx/compose/ui/text/font/PlatformFontFamilyTypefaceAdapter.android.kt;l=35;drc=20573118bfaf11b88910aebb6f512ee843553ae3;bpv=1;bpt=1">PlatformFontFamilyTypefaceAdapter.android.kt</a></p><pre>when (typefaceRequest.fontFamily) {<br>    null,<br>    is DefaultFontFamily -&gt;<br>        platformTypefaceResolver.createDefault(<br>            typefaceRequest.fontWeight,<br>            typefaceRequest.fontStyle,<br>        )<br>}</pre><p>At this point, Compose still hasn’t created a Typeface.</p><p>Instead, it delegates the work to the platform-specific implementation.</p><p>If we continue following the call chain, we eventually arrive at the implementation of createDefault():</p><pre>override fun createDefault(fontWeight: FontWeight, fontStyle: FontStyle) =<br>    createAndroidTypefaceApi28(null, fontWeight, fontStyle)</pre><p>Notice that createDefault() passes null as the font-family name.</p><p>This tells Android that the request should be resolved using the platform’s default font family rather than a specific named family.</p><p>The actual implementation looks like this:</p><pre>private fun createAndroidTypefaceApi28(<br>    genericFontFamily: String? = null,<br>    fontWeight: FontWeight,<br>    fontStyle: FontStyle,<br>): Typeface {<br>    if (<br>        fontStyle == FontStyle.Normal &amp;&amp;<br>            fontWeight == FontWeight.Normal &amp;&amp;<br>            genericFontFamily.isNullOrEmpty()<br>    ) {<br>        return Typeface.DEFAULT<br>    }<br><br>    if (<br>        fontStyle == FontStyle.Normal &amp;&amp;<br>            fontWeight == FontWeight.Bold &amp;&amp;<br>            genericFontFamily.isNullOrEmpty()<br>    ) {<br>        return Typeface.DEFAULT_BOLD<br>    }<br><br>    val familyTypeface =<br>        if (genericFontFamily == null) {<br>            Typeface.DEFAULT<br>        } else {<br>            Typeface.create(genericFontFamily, Typeface.NORMAL)<br>        }<br><br>    return Typeface.create(familyTypeface, fontWeight.weight, fontStyle == FontStyle.Italic)<br>}</pre><p>This implementation reveals how Compose resolves FontFamily.Default on Android.</p><p>For the two most common cases, Compose can immediately return Android’s built-in default typefaces:</p><pre>FontFamily.Default<br>fontWeight = FontWeight.Normal<br>fontStyle = FontStyle.Normal</pre><p>returns</p><pre>Typeface.DEFAULT</pre><p>and</p><pre>FontFamily.Default<br>fontWeight = FontWeight.Bold<br>fontStyle = FontStyle.Normal</pre><p>returns:</p><pre>Typeface.DEFAULT_BOLD</pre><p>For all other weight and style combinations, Compose derives a new Typeface from the platform default:</p><pre>Typeface.create(<br>    familyTypeface,<br>    fontWeight.weight,<br>    fontStyle == FontStyle.Italic<br>)</pre><p>Conceptually, the flow looks like this:</p><pre>FontFamily.Default<br>        │<br>        ▼<br>DefaultFontFamily<br>        │<br>        ▼<br>createDefault(fontWeight, fontStyle)<br>        │<br>        ▼<br>createAndroidTypefaceApi28(<br>    genericFontFamily = null<br>)<br>        │<br>        ├─ Normal + Normal<br>        │      ▼<br>        │  Typeface.DEFAULT<br>        │<br>        ├─ Bold + Normal<br>        │      ▼<br>        │  Typeface.DEFAULT_BOLD<br>        │<br>        └─ Others<br>               ▼<br>        Typeface.create(...)</pre><p>The important detail is that Compose never decides what the default font actually is.</p><p>Rather than maintaining its own default font, Compose simply delegates the request to Android’s typeface APIs and uses whatever the platform considers to be the default font.</p><p>As we’ll see next, GenericFontFamily follows almost the same resolution path.</p><p>The key difference is that, instead of passing null, it provides a concrete platform font-family name such as “sans-serif” or “serif”.</p><h3>4. FontFamily.SansSerif and Generic Families</h3><p>In the previous section, we saw that FontFamily.Default ultimately delegates font selection to Android by passing a null font-family name.</p><p>Generic font families follow a very similar path, but with one important difference: they provide an explicit platform font-family name.</p><p>Compose provides four generic font families:</p><pre>FontFamily.SansSerif<br>FontFamily.Serif<br>FontFamily.Monospace<br>FontFamily.Cursive</pre><p>These families represent well-known font categories rather than specific font resources.</p><p>For example:</p><pre>Text(<br>    text = &quot;Hello Compose&quot;,<br>    style = TextStyle(<br>        fontFamily = FontFamily.SansSerif<br>    )<br>)</pre><p>Unlike FontFamily.Default, this request explicitly asks for a platform font family.</p><h3>GenericFontFamily</h3><p>If we inspect the source code, we can see that all of these APIs are backed by the same implementation:</p><pre>sealed class SystemFontFamily : FontFamily(true)</pre><pre>class GenericFontFamily internal constructor(val name: String, private val fontFamilyName: String) :<br>    SystemFontFamily()</pre><p>And the public APIs are simply predefined instances:</p><pre><br>val SansSerif = GenericFontFamily(&quot;sans-serif&quot;, &quot;FontFamily.SansSerif&quot;)<br>val Serif = GenericFontFamily(&quot;serif&quot;, &quot;FontFamily.Serif&quot;)<br>val Monospace = GenericFontFamily(&quot;monospace&quot;, &quot;FontFamily.Monospace&quot;)<br>val Cursive = GenericFontFamily(&quot;cursive&quot;, &quot;FontFamily.Cursive&quot;)</pre><p>The hierarchy therefore looks like this:</p><pre>FontFamily<br>└─ SystemFontFamily<br>   ├─ DefaultFontFamily<br>   └─ GenericFontFamily</pre><p>This is the same SystemFontFamily branch we encountered in the previous chapter.</p><p>The difference is that GenericFontFamily carries additional information: a platform font-family name.</p><h3>Resolution Path</h3><p>When the request reaches PlatformFontFamilyTypefaceAdapter, Compose identifies the font family as a GenericFontFamily.</p><pre>is GenericFontFamily -&gt;<br>    platformTypefaceResolver.createNamed(<br>        typefaceRequest.fontFamily,<br>        typefaceRequest.fontWeight,<br>        typefaceRequest.fontStyle,<br>    )</pre><p>Notice the contrast with DefaultFontFamily.</p><p>In the previous chapter:</p><pre>createDefault(...)</pre><p>was called.</p><p>For generic families:</p><pre>createNamed(...)</pre><p>is called instead.</p><p>If we continue following the call chain, we eventually arrive at:</p><pre>override fun createNamed(<br>    name: GenericFontFamily,<br>    fontWeight: FontWeight,<br>    fontStyle: FontStyle<br>): Typeface {<br>    return createAndroidTypefaceApi28(<br>        name.name,<br>        fontWeight,<br>        fontStyle<br>    )<br>}</pre><p>Unlike FontFamily.Default, which passed null, GenericFontFamily passes a concrete family name.</p><p>For example:</p><pre>FontFamily.SansSerif</pre><p>ultimately becomes:</p><pre>createAndroidTypefaceApi28(<br>    &quot;sans-serif&quot;,<br>    fontWeight,<br>    fontStyle<br>)</pre><h3>From GenericFontFamily to Typeface</h3><p>If we revisit the implementation from the previous chapter:</p><pre>val familyTypeface =<br>    if (genericFontFamily == null) {<br>        Typeface.DEFAULT<br>    } else {<br>        Typeface.create(<br>            genericFontFamily,<br>            Typeface.NORMAL<br>        )<br>    }</pre><p>we can now see why the genericFontFamily parameter exists.</p><p>For FontFamily.Default:</p><pre>genericFontFamily = null</pre><p>returns:</p><pre>Typeface.DEFAULT</pre><p>For FontFamily.SansSerif:</p><pre>genericFontFamily = &quot;sans-serif&quot;</pre><p>returns:</p><pre>Typeface.create(<br>    &quot;sans-serif&quot;,<br>    Typeface.NORMAL<br>)</pre><p>The remainder of the flow is identical.</p><p>Android then derives the requested weight and style from that base typeface:</p><pre>Typeface.create(<br>    familyTypeface,<br>    fontWeight.weight,<br>    fontStyle == FontStyle.Italic<br>)</pre><p>Conceptually, the flow looks like this:</p><pre>FontFamily.SansSerif<br>        │<br>        ▼<br>GenericFontFamily(&quot;sans-serif&quot;)<br>        │<br>        ▼<br>createNamed()<br>        │<br>        ▼<br>createAndroidTypefaceApi28(<br>    &quot;sans-serif&quot;<br>)<br>        │<br>        ▼<br>Typeface.create(<br>    &quot;sans-serif&quot;,<br>    Typeface.NORMAL<br>)<br>        │<br>        ▼<br>android.graphics.Typeface</pre><h3>Default vs Generic</h3><p>At first glance, DefaultFontFamily and GenericFontFamily appear to be completely different implementations.</p><p>Internally, however, they follow almost the same resolution path.</p><p>The only meaningful difference is the value passed into createAndroidTypefaceApi28():</p><pre>DefaultFontFamily<br>    ↓<br>genericFontFamily = null</pre><pre>GenericFontFamily<br>    ↓<br>genericFontFamily = &quot;sans-serif&quot;</pre><p>Everything after that point is handled by Android’s typeface APIs.</p><p>So far, all of the font families we’ve examined have belonged to the SystemFontFamily hierarchy and relied entirely on the platform to provide a typeface.</p><p>The next category is fundamentally different.</p><p>Instead of referring to fonts already known by the platform, it introduces actual font definitions that Compose must manage itself.</p><h3>5. FontListFontFamily: From Font Descriptors to Typeface</h3><p>So far, we’ve examined font families that belong to the SystemFontFamily hierarchy.</p><pre>FontFamily.Default<br>FontFamily.SansSerif<br>FontFamily.Serif<br>FontFamily.Monospace<br>FontFamily.Cursive</pre><p>These font families are resolved directly through platform-provided font-family names.</p><p>Compose also provides another way of creating a FontFamily:</p><pre>FontFamily(<br>    Font(DeviceFontFamilyName(&quot;sec&quot;))<br>)</pre><p>You can discover available device font-family names by inspecting /system/etc/fonts.xml:</p><pre>adb shell cat /system/etc/fonts.xml</pre><p>or by referencing font resources packaged with the application:</p><pre>FontFamily(<br>    Font(R.font.roboto_regular),<br>    Font(R.font.roboto_bold)<br>)</pre><p>Although these APIs appear very different, they share the same implementation path inside Compose.</p><h3>FontListFontFamily</h3><p>Whenever a FontFamily is constructed from one or more Font descriptors, Compose creates a FontListFontFamily.</p><pre><br>fun FontFamily(fonts: List&lt;Font&gt;): FontFamily = FontListFontFamily(fonts)<br>fun FontFamily(vararg fonts: Font): FontFamily = FontListFontFamily(fonts.asList())</pre><p>In other words, any FontFamily created through Font(...) is represented internally as a FontListFontFamily.</p><p>This means that both of the following declarations:</p><pre>FontFamily(<br>    Font(DeviceFontFamilyName(&quot;sec&quot;))<br>)</pre><pre>FontFamily(<br>    Font(R.font.roboto_regular),<br>    Font(R.font.roboto_bold)<br>)</pre><p>produce the same FontFamily implementation:</p><pre>FontListFontFamily</pre><p>The only difference is the type of Font stored inside the family.</p><h3>FontListFontFamilyTypefaceAdapter</h3><p>The key difference from SystemFontFamily is that<br>Compose cannot immediately create a Typeface.</p><p>It must first select a Font descriptor.</p><p>When the resolver receives a FontListFontFamily, it delegates the request to FontListFontFamilyTypefaceAdapter.</p><pre>override fun resolve(<br>    typefaceRequest: TypefaceRequest,<br>    platformFontLoader: PlatformFontLoader,<br>    onAsyncCompletion: (TypefaceResult.Immutable) -&gt; Unit,<br>    createDefaultTypeface: (TypefaceRequest) -&gt; Any<br>): TypefaceResult? {<br>    val fontFamily = typefaceRequest.fontFamily as? FontListFontFamily<br>        ?: return null<br>    val matchedFonts = fontMatcher.matchFont(<br>        fontFamily.fonts,<br>        typefaceRequest.fontWeight,<br>        typefaceRequest.fontStyle<br>    )<br>    val matchedFont = matchedFonts.first()<br>    val typeface = platformFontLoader.loadBlocking(matchedFont)<br>    return TypefaceResult.Immutable(<br>        typeface = typeface,<br>        cacheable = true<br>    )<br>}</pre><p>The important difference from DefaultFontFamily and GenericFontFamily is that Compose cannot immediately call createDefault() or createNamed().</p><p>Instead, it must first inspect the Font descriptors stored inside the FontListFontFamily.</p><pre>FontListFontFamily<br>        │<br>        ▼<br>fontMatcher.matchFont(...)<br>        │<br>        ▼<br>matched Font<br>        │<br>        ▼<br>platformFontLoader.loadBlocking(...)<br>        │<br>        ▼<br>android.graphics.Typeface</pre><h3>Font Matching</h3><p>For example, consider the following font family:</p><pre>val AppFontFamily = FontFamily(<br>    Font(<br>        R.font.roboto_regular,<br>        weight = FontWeight.Normal<br>    ),<br>    Font(<br>        R.font.roboto_bold,<br>        weight = FontWeight.Bold<br>    )<br>)</pre><p>If the text request asks for FontWeight.Bold, Compose must select the matching Font descriptor before loading anything.</p><pre>fontMatcher.matchFont(<br>    fontFamily.fonts,<br>    requestedFontWeight,<br>    requestedFontStyle<br>)</pre><p>Conceptually:</p><pre>FontListFontFamily<br>├─ ResourceFont(weight = Normal)<br>└─ ResourceFont(weight = Bold)<br>        │<br>        ▼<br>requested weight = Bold<br>        │<br>        ▼<br>ResourceFont(weight = Bold)</pre><p>Only after this matching step does Compose move on to loading the selected font.</p><h3>Loading the Selected Font</h3><p>Once a matching Font has been selected, Compose delegates loading to the platform font loader.</p><pre>platformFontLoader.loadBlocking(font)</pre><p>At this point, the path depends on the concrete Font implementation.</p><h3>DeviceFontFamilyNameFont</h3><p>For a device-installed font:</p><pre>Font(<br>    DeviceFontFamilyName(&quot;sec&quot;)<br>)</pre><p>the selected font is a DeviceFontFamilyNameFont.</p><pre>internal class DeviceFontFamilyNameFont(<br>    val familyName: DeviceFontFamilyName,<br>    override val weight: FontWeight,<br>    override val style: FontStyle,<br>    override val variationSettings: FontVariation.Settings,<br>) : AndroidFont</pre><p>Once a DeviceFontFamilyNameFont has been selected, PlatformFontLoader uses the stored family name to obtain the corresponding Android Typeface.</p><pre>fun loadCached(context: Context): Typeface? {<br>    return PlatformTypefaces()<br>        .optionalOnDeviceFontFamilyByName(<br>            familyName.name,<br>            weight,<br>            style,<br>            variationSettings,<br>            context,<br>        )<br>}</pre><p>The call eventually reaches a platform-specific implementation that attempts to resolve the device font-family name.</p><pre>when (familyName) {<br>    FontFamily.SansSerif.name -&gt; createNamed(...)<br>    FontFamily.Serif.name -&gt; createNamed(...)<br>    else -&gt; loadNamedFromTypefaceCacheOrNull(<br>        familyName,<br>        weight,<br>        style<br>    )<br>}</pre><p>For non-generic device font families, Compose eventually delegates to:</p><pre>createAndroidTypefaceApi28(<br>    familyName,<br>    weight,<br>    style<br>)</pre><p>For example, when using:</p><pre>DeviceFontFamilyName(&quot;sec&quot;)</pre><p>Compose eventually attempts to create a typeface using:</p><pre>createAndroidTypefaceApi28(<br>    &quot;sec&quot;,<br>    weight,<br>    style<br>)</pre><p>Conceptually, the path looks like this:</p><pre>DeviceFontFamilyNameFont<br>        │<br>        ▼<br>familyName = &quot;sec&quot;<br>        │<br>        ▼<br>createAndroidTypefaceApi28(&quot;sec&quot;, ...)<br>        │<br>        ▼<br>android.graphics.Typeface?</pre><p>The return type is nullable because the requested device font-family name may not exist on the current device. In that case, Compose may fall back to another typeface path.</p><h3>ResourceFont</h3><p>For a resource-backed font:</p><pre>Font(<br>    R.font.roboto_bold,<br>    weight = FontWeight.Bold<br>)</pre><p>the selected font is a ResourceFont.</p><p>Unlike DeviceFontFamilyNameFont, this font does not rely on a device font-family name. Instead, it points to a font file packaged with the application.</p><pre>ResourceFont<br> ├─ resId = R.font.roboto_bold<br> ├─ weight = Bold<br> └─ style = Normal</pre><p><a href="http://val typeface = createAndroidTypefaceApi28(         familyName,         weight,         style     )     val isItalic = style == FontStyle.Italic     return typeface.takeIf {         it != TypefaceHelperMethodsApi28.create(             Typeface.DEFAULT,             weight.weight,             isItalic         ) &amp;&amp;             it != createAndroidTypefaceApi28(                 null,                 weight,                 style             )     } }">AndroidFontLoader.android.kt</a></p><pre>is ResourceFont -&gt;<br>    when (font.loadingStrategy) {<br>        Blocking -&gt; font.load(context)<br>        OptionalLocal -&gt; runCatching {<br>            font.load(context)<br>        }.getOrNull()<br>        Async -&gt; throw UnsupportedOperationException(<br>            &quot;Unsupported Async font load path&quot;<br>        )<br>        else -&gt;<br>            throw IllegalArgumentException(<br>                &quot;Unknown loading type ${font.loadingStrategy}&quot;<br>            )<br>    }.setFontVariationSettings(<br>        font.variationSettings,<br>        context<br>    )</pre><p>For the common blocking case, the path is straightforward:</p><pre>ResourceFont<br>        │<br>        ▼<br>font.load(context)<br>        │<br>        ▼<br>load font resource from R.font<br>        │<br>        ▼<br>setFontVariationSettings(...)<br>        │<br>        ▼<br>android.graphics.Typeface</pre><p>From the perspective of FontListFontFamily, however, both paths are equivalent: a Font is selected first, and only then converted into a Typeface.</p><h3>Converging on Typeface</h3><p>Although DeviceFontFamilyNameFont and ResourceFont are loaded differently, both ultimately converge on the same resolution pipeline.</p><pre>FontListFontFamily<br>        │<br>        ▼<br>FontListFontFamilyTypefaceAdapter<br>        │<br>        ▼<br>Font Matching<br>        │<br>        ▼<br>PlatformFontLoader<br>        │<br>        ▼<br>android.graphics.Typeface</pre><pre>DeviceFontFamilyNameFont<br>        │<br>        ▼<br>createAndroidTypefaceApi28(...)<br>        │<br>        ▼<br>Typeface</pre><pre>ResourceFont<br>        │<br>        ▼<br>font.load(context)<br>        │<br>        ▼<br>Typeface</pre><p>Regardless of the source, the end result is always the same: a native Android Typeface.</p><h3>6. FontFamily(nativeTypeface)</h3><p>So far, we’ve examined font families that eventually need to produce a native Android Typeface.</p><p>DefaultFontFamily and GenericFontFamily delegate to Android&#39;s platform typeface APIs.</p><p>FontListFontFamily stores one or more Font descriptors, then goes through font matching and loading before a Typeface can be produced.</p><p>There is one final case:</p><pre>FontFamily(android.graphics.Typeface.create(/* ... */))</pre><p>Unlike the previous examples, this API starts with a Typeface that already exists.</p><h3>LoadedFontFamily</h3><p>When we pass a native typeface to FontFamily, Compose wraps it in a LoadedFontFamily.</p><pre>fun FontFamily(typeface: Typeface): FontFamily = LoadedFontFamily(typeface)</pre><pre>class LoadedFontFamily internal constructor(val typeface: Typeface) : FontFamily(true) {</pre><p>The hierarchy looks like this:</p><pre>FontFamily<br>└─ LoadedFontFamily<br>   └─ AndroidTypeface<br>      └─ android.graphics.Typeface</pre><p>This is different from FontListFontFamily.</p><p>A LoadedFontFamily does not describe fonts that need to be matched or loaded later.</p><p>Instead, it already contains a platform-backed typeface object.</p><h3>AndroidTypeface</h3><p>Internally, the native Typeface is wrapped by AndroidTypeface.</p><pre>class AndroidTypeface(<br>    val nativeTypeface: Typeface<br>)</pre><p>This wrapper allows Compose to store a platform-specific typeface inside its common font abstraction.</p><p>When the resolver later needs a native typeface, it can retrieve the original Android Typeface from this wrapper.</p><pre>val nativeTypeface = androidTypeface.nativeTypeface</pre><p>In other words, Compose does not need to ask Android to create a new typeface from a family name, nor does it need to load a font resource.</p><p>The typeface is already available.</p><h3>Resolution Path</h3><p>Conceptually, the resolution path is much shorter:</p><pre>FontFamily(nativeTypeface)<br>        │<br>        ▼<br>LoadedFontFamily<br>        │<br>        ▼<br>AndroidTypeface<br>        │<br>        ▼<br>android.graphics.Typeface</pre><p>Compared to the previous implementations:</p><pre>DefaultFontFamily<br>        │<br>        ▼<br>createDefault()<br>        │<br>        ▼<br>Typeface</pre><pre>GenericFontFamily<br>        │<br>        ▼<br>createNamed()<br>        │<br>        ▼<br>Typeface</pre><pre>FontListFontFamily<br>        │<br>        ▼<br>Font Matching<br>        │<br>        ▼<br>Font Loading<br>        │<br>        ▼<br>Typeface</pre><p>LoadedFontFamily is the most direct path.</p><p>Compose already has the final native typeface, so most of the font-resolution process can be skipped.</p><h3>Why This Exists</h3><p>This API is useful when a Typeface is created outside Compose.</p><p>For example, an application may obtain a typeface from Android APIs, a design system, or a custom font-loading layer:</p><pre>val nativeTypeface: Typeface = Typeface.create(&quot;serif&quot;, Typeface.NORMAL)</pre><pre>val fontFamily = FontFamily(nativeTypeface)</pre><p>Once wrapped, the typeface can be used through the same Compose text APIs as every other FontFamily.</p><pre>Text(<br>    text = &quot;Hello Compose&quot;,<br>    style = TextStyle(<br>        fontFamily = fontFamily<br>    )<br>)</pre><p>From the perspective of Text, this still looks like a normal FontFamily.</p><p>Internally, however, Compose no longer needs to resolve the font from scratch.</p><p>It simply unwraps and uses the already-loaded native Typeface.</p><h3>A Note on FontWeight and FontStyle</h3><p>One important consequence of using FontFamily(nativeTypeface) is that Compose no longer has access to individual font descriptors.</p><p>With FontListFontFamily, Compose can inspect multiple fonts, perform matching, and select the best candidate for a requested weight or style.</p><pre>FontListFontFamily<br>        │<br>        ▼<br>Font Matching<br>        │<br>        ▼<br>Typeface</pre><p>With LoadedFontFamily, however, Compose already has a native Typeface.</p><pre>LoadedFontFamily<br>        │<br>        ▼<br>AndroidTypeface<br>        │<br>        ▼<br>Typeface</pre><p>At this point, the font has already been chosen.</p><p>As a result, Compose can no longer perform the same font matching process used by FontListFontFamily.</p><p>For example:</p><pre>val typeface = Typeface.create(<br>    &quot;sans-serif&quot;,<br>    Typeface.NORMAL<br>)</pre><pre>Text(<br>    text = &quot;Hello Compose&quot;,<br>    style = TextStyle(<br>        fontFamily = FontFamily(typeface),<br>        fontWeight = FontWeight.Bold<br>    )<br>)</pre><p>Unlike FontListFontFamily, Compose does not have access to a dedicated Bold font descriptor that it can select during resolution.</p><p>Instead, it only has the Typeface instance that was originally provided.</p><p>In other words, FontFamily(nativeTypeface) bypasses not only font loading, but also much of Compose’s font selection machinery.</p><p>This makes LoadedFontFamily the most direct path to a native Typeface, but it also means that Compose has far less information available when resolving font weight and style.</p><h3>7. Comparing the Four Resolution Paths</h3><p>We’ve now examined the four major FontFamily implementations used by Compose. Although they all appear as the same FontFamily API, each follows a very different path before ultimately producing an android.graphics.Typeface.</p><h4>Resolution Paths at a Glance</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SzVzYVz10Qz8q3lDFZdnxg.png" /></figure><p>All four paths eventually converge on the same destination: an android.graphics.Typeface.</p><p>The difference lies in how much work Compose must perform along the way. Some implementations delegate directly to platform APIs, some perform font matching and loading, and others bypass most of the resolution pipeline entirely.</p><h3>Comparison</h3><pre>| FontFamily API | Direct Platform Resolution | Font Matching | Font Loading |<br>| -------------- | ------------ | ------------- | ------------ |<br>| Default        | ✅            | ❌             | ❌            |<br>| Generic        | ✅            | ❌             | ❌            |<br>| FontList       | △            | ✅             | ✅            |<br>| Loaded         | ❌            | ❌             | ❌            |</pre><p>DefaultFontFamily and GenericFontFamily rely entirely on platform-provided font families. FontListFontFamily introduces actual Font definitions that Compose must match and load before a Typeface can be produced. LoadedFontFamily sits at the opposite end of the spectrum, providing a Typeface that has already been resolved before Compose enters the pipeline.</p><h3>Key Takeaway</h3><p>Although Compose exposes FontFamily as a single API, it is backed by four distinct implementations that follow very different resolution paths.</p><p>From the perspective of a Text composable, these differences are hidden behind the same FontFamily abstraction. Internally, however, the specific FontFamily implementation determines how Compose resolves a font request and ultimately produces an android.graphics.Typeface.</p><p>In other words, In most cases, a FontFamily is not the font itself — it is a description of <strong>how Compose should obtain or reuse a Typeface.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5aad0f0fd59" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Compose Separates Font Resolution from UI Components]]></title>
            <link>https://quokkaman.medium.com/how-compose-separates-font-resolution-from-ui-components-1fa214b5eae7?source=rss-14e3cc4acf91------2</link>
            <guid isPermaLink="false">https://medium.com/p/1fa214b5eae7</guid>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[compose]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[framework]]></category>
            <category><![CDATA[aosp]]></category>
            <dc:creator><![CDATA[Quokkaman]]></dc:creator>
            <pubDate>Tue, 02 Jun 2026 13:31:27 GMT</pubDate>
            <atom:updated>2026-06-02T13:31:27.984Z</atom:updated>
            <content:encoded><![CDATA[<h4>From FontFamily to android.graphics.Typeface</h4><h3>Introduction</h3><p>In the traditional Android View system, font management was closely tied to the TextView implementation. Whether a developer explicitly provided a Typeface object or defined a fontFamily in XML, the TextView (or its internal utilities) was ultimately responsible for obtaining a concrete Typeface instance to perform rendering.</p><pre>&lt;TextView<br>    android:layout_width=&quot;wrap_content&quot;<br>    android:layout_height=&quot;wrap_content&quot;<br>    android:text=&quot;안녕하세요&quot;<br>    android:fontFamily=&quot;@font/nanum_square_bold&quot; /&gt;</pre><p>If we look at the internal source code of TextView.java, we can see this imperative process in action. The method setTypefaceFromAttrs is responsible for making the decision on which font to use based on the provided attributes.</p><p><a href="https://cs.android.com/android/platform/superproject/+/android-latest-release:frameworks/base/core/java/android/widget/TextView.java;l=2425?q=TextView&amp;ss=android">TextView::setTypefaceFromAttrs</a></p><pre>// Simplified snippet from TextView.java<br>private void setTypefaceFromAttrs(@Nullable Typeface typeface, @Nullable String familyName,<br>        @XMLTypefaceAttr int typefaceIndex, @Typeface.Style int style, int weight) {<br>    <br>    if (typeface == null &amp;&amp; familyName != null) {<br>        // 1. TextView directly requests the System Font Map for a Typeface <br>        // by its family name (e.g., &quot;sans-serif&quot;).<br>        final Typeface normalTypeface = Typeface.create(familyName, Typeface.NORMAL);<br>        resolveStyleAndSetTypeface(normalTypeface, style, weight);<br>    } else if (typeface != null) {<br>        // 2. If a Typeface object is already provided, it uses it directly.<br>        resolveStyleAndSetTypeface(typeface, style, weight);<br>    }<br>    // ...<br>}</pre><p>After picking a candidate, the TextView goes a step further to handle specific weights and styles:</p><p><a href="https://cs.android.com/android/platform/superproject/+/android-latest-release:frameworks/base/core/java/android/widget/TextView.java;l=2454?q=TextView&amp;ss=android">Typeface::resolveStyleAndSetTypeface</a></p><pre>    private void resolveStyleAndSetTypeface(@NonNull Typeface typeface, @Typeface.Style int style,<br>            @IntRange(from = FontStyle.FONT_WEIGHT_UNSPECIFIED, to = FontStyle.FONT_WEIGHT_MAX)<br>                    int weight) {<br>        if (weight &gt;= 0) {<br>            weight = Math.min(FontStyle.FONT_WEIGHT_MAX, weight);<br>            final boolean italic = (style &amp; Typeface.ITALIC) != 0;<br>            setTypeface(Typeface.create(typeface, weight, italic));<br>        } else {<br>            setTypeface(typeface, style);<br>        }<br>    }</pre><p>Jetpack Compose, however, moves font resolution out of the UI component itself and into a dedicated resolution system. In this declarative world, the UI toolkit no longer resolves fonts directly. Instead, it describes font requirements through a set of abstractions that are processed by a dedicated font resolution pipeline.</p><p>To understand how text is ultimately rendered in Compose, we need to follow the journey from a declarative FontFamily request to the native android.graphics.Typeface used by the Android rendering engine.</p><h3>Overview: The New Architecture of Font Resolution</h3><p>In the traditional Android View system, font resolution was largely handled within TextView. The widget itself was responsible for interpreting font-related attributes and obtaining the appropriate Typeface for rendering.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/0*5wkhI_wxxovMASlH" /></figure><p>Jetpack Compose introduces a different architecture. Instead of embedding font resolution logic inside UI components, Compose treats font resolution as an independent process. A font request flows through several dedicated layers, each responsible for a specific task — from describing the requested font, to resolving it, to producing the final platform-specific Typeface.</p><pre>Descriptor → Resolution → Platform Mapping → Typeface</pre><p>Understanding these layers is key to understanding how Compose achieves a more flexible and scalable font system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/0*TPP1fyF1Ydjjg19m" /></figure><h3>1. The Descriptors: FontFamily and Font</h3><p>Everything starts with <strong>Descriptors</strong>. In Compose, we don’t handle raw font files; we deal with logical abstractions. This layer consists of two primary entities that work in tandem:</p><p>Font is a descriptor for a single font resource. It defines the metadata required during font resolution, such as weight, style, and loading strategy.</p><p><a href="https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:compose/ui/ui-text/src/commonMain/kotlin/androidx/compose/ui/text/font/Font.kt;l=29?q=Font&amp;sq=&amp;ss=androidx%2Fplatform%2Fframeworks%2Fsupport:compose%2Fui%2Fui-text%2F">Font.kt</a></p><pre>/**<br> * The interface of the font resource.<br> *<br> * @see ResourceFont<br> */<br>@Immutable<br>interface Font {<br>    /**<br>     * The weight of the font. The system uses this to match a font to a font request that is given<br>     * in a [androidx.compose.ui.text.SpanStyle].<br>     */<br>    val weight: FontWeight<br><br>    /**<br>     * The style of the font, normal or italic. The system uses this to match a font to a font<br>     * request that is given in a [androidx.compose.ui.text.SpanStyle].<br>     */<br>    val style: FontStyle<br><br>    /** Loading strategy for this font. */<br>    val loadingStrategy: FontLoadingStrategy<br>        get() = FontLoadingStrategy.Blocking<br>}</pre><p>FontFamily is a collection of related Font instances and serves as the primary descriptor passed into the font resolution system. It represents the font requirements requested by the UI rather than the final typeface used for rendering.</p><pre>/**<br> * The primary typography interface for Compose applications.<br> *<br> * @see FontListFontFamily<br> * @see GenericFontFamily<br> * @see FontFamily.Resolver<br> */<br>@Immutable<br>sealed class FontFamily(canLoadSynchronously: Boolean) {<br><br>    @Suppress(&quot;CanBePrimaryConstructorProperty&quot;) // for deprecation<br>    @get:Deprecated(<br>        message = &quot;Unused property that has no meaning. Do not use.&quot;,<br>        level = DeprecationLevel.ERROR,<br>    )<br>    val canLoadSynchronously = canLoadSynchronously<br>}</pre><pre>// A typical representation of the Descriptor layer<br>val MyCustomFontFamily = FontFamily(<br>    Font(resId = R.font.my_font_regular, weight = FontWeight.Normal),<br>    Font(resId = R.font.my_font_bold, weight = FontWeight.Bold)<br>)</pre><p>Both Font and FontFamily are immutable descriptors. Their responsibility is not to resolve or load fonts themselves, but to describe font requirements that will later be processed by FontFamily.Resolver.</p><h3>2. The Engine: FontFamily.Resolver (The Heart of Separation)</h3><p>The most significant architectural shift is the introduction of the <strong>FontFamily.Resolver</strong>. While each TextView previously resolved fonts through its own font-handling logic, Compose delegates this responsibility to FontFamily.Resolver.</p><ul><li><strong>Decoupling</strong>: The widget no longer needs to know how to fetch a font. It simply requests a typeface from the Resolver based on a given descriptor.</li><li><strong>Centralized Strategy</strong>: All logic for font matching, fallback mechanisms, and caching policies is concentrated within this single engine.</li></ul><p><a href="https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:compose/ui/ui-text/src/commonMain/kotlin/androidx/compose/ui/text/font/FontFamily.kt;l=46?q=FontFamily&amp;ss=androidx">FontFamily.Resolver</a></p><pre>sealed interface Resolver {<br><br>    suspend fun preload(fontFamily: FontFamily)<br><br>    fun resolve(<br>        fontFamily: FontFamily? = null,<br>        fontWeight: FontWeight = FontWeight.Normal,<br>        fontStyle: FontStyle = FontStyle.Normal,<br>        fontSynthesis: FontSynthesis = FontSynthesis.All,<br>    ): State&lt;Any&gt;<br>}</pre><h4>2.1 Where Does FontFamily.Resolver Come From?</h4><p>At this point, an important question arises: if FontFamily.Resolver is responsible for font resolution, who creates it and how does a Text composable gain access to it?</p><p>Unlike the View system, where each TextView participates directly in font resolution, Compose provides a resolver through the composition itself. Text components do not create or own a resolver. Instead, they obtain the current resolver from LocalFontFamilyResolver.</p><p><a href="https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/text/BasicText.kt;l=124;drc=310b2b02c9ff33eb042e9d9ff77705f200ee1d28">BasicText.kt</a></p><pre>@Composable<br>fun BasicText(/* ... */) {<br>    // ...<br>    val fontFamilyResolver = LocalFontFamilyResolver.current</pre><p>This design is a direct consequence of Compose’s separation of concerns. A Text composable is responsible only for describing its font requirements through properties such as fontFamily, fontWeight, and fontStyle. The actual resolution process is delegated to the resolver provided by the surrounding composition.</p><p>The resolver is later used during text measurement and layout. During paragraph construction, AndroidParagraphIntrinsics receives a FontFamily.Resolver instance and uses it to resolve the requested typeface.</p><p><a href="https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:compose/ui/ui-text/src/androidMain/kotlin/androidx/compose/ui/text/ParagraphIntrinsics.android.kt;l=113;drc=310b2b02c9ff33eb042e9d9ff77705f200ee1d28;bpv=0;bpt=1">ParagraphIntrinsics.android.kt</a></p><pre>internal class AndroidParagraphIntrinsics(<br>    // ...<br>    val fontFamilyResolver: FontFamily.Resolver,<br>    // ...,<br>) : ParagraphIntrinsics {<br>    // ...<br>    init {<br>        val resolveTypeface: (FontFamily?, FontWeight, FontStyle, FontSynthesis) -&gt; Typeface =<br>            { fontFamily, fontWeight, fontStyle, fontSynthesis -&gt;<br>                val result =<br>                    fontFamilyResolver.resolve(fontFamily, fontWeight, fontStyle, fontSynthesis)<br>                // ...<br>            }<br>    }</pre><p>In other words, a Text composable never resolves fonts directly. It simply describes what it wants, while FontFamily.Resolver orchestrates the process of resolving those requirements into a platform-specific Typeface.</p><h4>2.2 What Happens Inside resolve()</h4><p>Obtaining a resolver is only the beginning. The real work starts when Compose calls FontFamily.Resolver.resolve().<br><br>At a high level, the resolver performs three major tasks:</p><p>1. Building a TypefaceRequest<br>2. Cache Lookup<br>3. Adapter Delegation</p><p><strong>1 - Building a TypefaceRequest</strong></p><p>Rather than passing individual font attributes throughout the pipeline, Compose consolidates them into a TypefaceRequest. This object becomes the canonical representation of a font lookup operation.</p><p>The request also acts as the cache key used by TypefaceRequestCache, ensuring that identical font lookups can be efficiently reused.</p><p><a href="https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:compose/ui/ui-text/src/commonMain/kotlin/androidx/compose/ui/text/font/FontFamilyResolver.kt;l=81;drc=f17774caaaacaa90810e95201467b4e6044f7708;bpv=1;bpt=1">FontFamilyResolver</a></p><pre>override fun resolve(<br>    fontFamily: FontFamily?,<br>    fontWeight: FontWeight,<br>    fontStyle: FontStyle,<br>    fontSynthesis: FontSynthesis,<br>): State&lt;Any&gt; {<br>    return resolve(<br>        TypefaceRequest(<br>            platformResolveInterceptor.interceptFontFamily(fontFamily),<br>            platformResolveInterceptor.interceptFontWeight(fontWeight),<br>            platformResolveInterceptor.interceptFontStyle(fontStyle),<br>            platformResolveInterceptor.interceptFontSynthesis(fontSynthesis),<br>            platformFontLoader.cacheKey,<br>        )<br>    )<br>}</pre><p><strong>2 - Cache Lookup</strong></p><p>Before invoking any adapter implementations, the resolver first checks whether the same TypefaceRequest has already been resolved.</p><p>This lookup happens through TypefaceRequestCache.runCached(). If a cached and cacheable result exists, it can be returned immediately without invoking any font adapter. This means that repeated requests for the same FontFamily, weight, style, and synthesis configuration can avoid going through the full resolution path again.</p><p><a href="https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:compose/ui/ui-text/src/commonMain/kotlin/androidx/compose/ui/text/font/FontFamilyResolver.kt;l=94;drc=f17774caaaacaa90810e95201467b4e6044f7708;bpv=1;bpt=1">FontFamilyResolver.kt</a></p><pre>private fun resolve(typefaceRequest: TypefaceRequest): State&lt;Any&gt; {<br>    val result =<br>        typefaceRequestCache.runCached(typefaceRequest) { /* ... */ }<br>    // ...<br>}</pre><p>The important detail is that the adapter chain is passed as the fallback block to runCached(). In other words, the resolver does not call the adapters first. It asks the cache first, and only when the cache cannot provide a valid result does it execute the actual resolution logic.</p><pre>fun runCached(<br>    typefaceRequest: TypefaceRequest,<br>    resolveTypeface: ((TypefaceResult) -&gt; Unit) -&gt; TypefaceResult,<br>): State&lt;Any&gt; {<br>    synchronized(lock) {<br>        resultCache[typefaceRequest]?.let {<br>            if (it.cacheable) {<br>                return it<br>            } else {<br>                resultCache.remove(typefaceRequest)<br>            }<br>        }<br>    }<br><br>    val currentTypefaceResult =<br>        try {<br>            resolveTypeface { finalResult -&gt;<br>                synchronized(lock) {<br>                    if (finalResult.cacheable) {<br>                        resultCache.put(typefaceRequest, finalResult)<br>                    } else {<br>                        resultCache.remove(typefaceRequest)<br>                    }<br>                }<br>            }<br>        } catch (cause: Exception) {<br>            throw IllegalStateException(&quot;Could not load font&quot;, cause)<br>        }<br>    synchronized(lock) {<br>        if (resultCache[typefaceRequest] == null &amp;&amp; currentTypefaceResult.cacheable) {<br>            resultCache.put(typefaceRequest, currentTypefaceResult)<br>        }<br>    }<br>    return currentTypefaceResult<br>}</pre><p>This cache layer is one of the reasons font resolution can remain efficient even though Compose models fonts through several abstraction layers. The abstractions are not resolved from scratch every time. Once a TypefaceRequest produces a cacheable result, subsequent identical requests can reuse it.</p><p>In practice, this means most text rendering operations never need to resolve the same font twice. As a result, the cost of font resolution is typically paid only once per unique request.</p><p><strong>3 — Adapter Delegation</strong></p><p>When a cache miss occurs, the resolver proceeds to the actual resolution phase.<br>Rather than interacting with Android APIs directly, it delegates the work to a chain of FontFamilyTypefaceAdapter implementations.</p><p><a href="https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:compose/ui/ui-text/src/commonMain/kotlin/androidx/compose/ui/text/font/FontFamilyResolver.kt;l=94;drc=f17774caaaacaa90810e95201467b4e6044f7708;bpv=1;bpt=1">FontFamilyResolver.kt</a></p><pre>fontListFontFamilyTypefaceAdapter.resolve(<br>    typefaceRequest,<br>    platformFontLoader,<br>    onAsyncCompletion,<br>    createDefaultTypeface,<br>)<br>    ?: platformFamilyTypefaceAdapter.resolve(<br>        typefaceRequest,<br>        platformFontLoader,<br>        onAsyncCompletion,<br>        createDefaultTypeface,<br>    )</pre><p>Notice that the resolver itself contains no Android-specific font resolution logic. Its responsibility is to coordinate the process, while the actual platform-dependent work is delegated to adapter implementations.</p><p>Different adapters are responsible for different categories of font families. FontListFontFamilyTypefaceAdapter resolves font-list based families, while PlatformFontFamilyTypefaceAdapter bridges Compose font requests to platform-provided font families and native typefaces.</p><p>Among them, PlatformFontFamilyTypefaceAdapter plays a particularly important role on Android because it is the component that ultimately translates Compose font abstractions into native Typeface operations.</p><h3>3. The Bridge: PlatformFontFamilyTypefaceAdapter</h3><p>When the resolver delegates font resolution to adapters, not all font families follow the same path. Some font families do not require custom font loading at all because they already correspond to platform-provided typefaces.</p><p>This is where PlatformFontFamilyTypefaceAdapter comes into play.</p><p>Unlike FontListFontFamilyTypefaceAdapter, which works with collections of Font descriptors, PlatformFontFamilyTypefaceAdapter handles font families that can be resolved directly by the underlying platform. Examples include:</p><ul><li>FontFamily.Default</li><li>FontFamily.SansSerif</li><li>FontFamily.Serif</li><li>FontFamily.Monospace</li><li>LoadedFontFamily</li></ul><p>The implementation reveals this distinction clearly:</p><p><a href="https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:compose/ui/ui-text/src/androidMain/kotlin/androidx/compose/ui/text/font/PlatformFontFamilyTypefaceAdapter.android.kt;l=26;drc=4e2257534f2b37def8b3ca8e015dcbfb7f5873b6">PlatformFontFamilyTypeface.kt</a></p><pre>when (typefaceRequest.fontFamily) {<br>    null,<br>    is DefaultFontFamily -&gt;<br>        platformTypefaceResolver.createDefault(<br>            typefaceRequest.fontWeight,<br>            typefaceRequest.fontStyle,<br>        )<br>    is GenericFontFamily -&gt;<br>        platformTypefaceResolver.createNamed(<br>            typefaceRequest.fontFamily,<br>            typefaceRequest.fontWeight,<br>            typefaceRequest.fontStyle,<br>        )<br>    is LoadedFontFamily -&gt;<br>        (typefaceRequest.fontFamily.typeface as AndroidTypeface)<br>            .getNativeTypeface(<br>                typefaceRequest.fontWeight,<br>                typefaceRequest.fontStyle,<br>                typefaceRequest.fontSynthesis,<br>            )<br>    else -&gt; return null<br>}</pre><p>Notice that no font matching, resource loading, or fallback chain construction occurs here. Instead, the adapter simply translates Compose abstractions into calls that the Android font system already understands.</p><p>For example, a request for FontFamily.SansSerif ultimately becomes a request for Android&#39;s native sans-serif typeface. In this sense, PlatformFontFamilyTypefaceAdapter acts as the bridge between Compose&#39;s font abstractions and the platform&#39;s existing typeface infrastructure.</p><p>However, not all font families can be resolved so easily. When developers define a custom FontFamily composed of multiple Font resources, Compose must perform considerably more work to determine the correct typeface. That responsibility belongs to FontListFontFamilyTypefaceAdapter.</p><h3>4. Resolving Font-Based Families: FontListFontFamilyTypefaceAdapter</h3><p>Custom font families represent the most sophisticated part of Compose’s font resolution system.</p><p>Consider the following example:</p><pre>val AppFontFamily = FontFamily(<br>    Font(R.font.roboto_regular, weight = FontWeight.Normal),<br>    Font(R.font.roboto_bold, weight = FontWeight.Bold),<br>    Font(R.font.roboto_italic, style = FontStyle.Italic)<br>)</pre><p>Unlike platform-provided families such as SansSerif, Compose cannot immediately obtain a native Typeface from the operating system. Instead, it must determine which Font within the family best satisfies the requested weight and style.</p><p>This responsibility belongs to FontListFontFamilyTypefaceAdapter.</p><p>Given a request such as:</p><pre>fontFamilyResolver.resolve(<br>    fontFamily = AppFontFamily,<br>    fontWeight = FontWeight.Bold,<br>    fontStyle = FontStyle.Normal,<br>    fontSynthesis = FontSynthesis.All<br>)</pre><p>the adapter performs several steps:</p><ol><li>Inspect the available Font entries in the family.</li><li>Find the closest match for the requested weight and style.</li><li>Load the selected font resource.</li><li>Apply fallback and synthesis rules when necessary.</li><li>Produce the final platform-specific Typeface.</li></ol><p>This process is significantly more complex than the platform adapter because the adapter must reason about multiple candidate fonts rather than simply mapping a request to a known platform typeface.</p><p>The distinction between the two adapters reflects the overall architecture of Compose’s font system:</p><ul><li>PlatformFontFamilyTypefaceAdapter handles platform-provided font families.</li><li>FontListFontFamilyTypefaceAdapter handles developer-defined font families.</li><li>FontFamily.Resolver coordinates both without needing to know the platform-specific details of either implementation.</li></ul><p>This separation of concerns allows Compose to support both simple platform fonts and sophisticated custom font families through the same high-level FontFamily API.</p><h3>5. Why Does resolve() Return State?</h3><p>At first glance, the signature of FontFamily.Resolver.resolve() looks somewhat surprising.</p><pre>fun resolve(<br>    fontFamily: FontFamily?,<br>    fontWeight: FontWeight,<br>    fontStyle: FontStyle,<br>    fontSynthesis: FontSynthesis,<br>): State&lt;Any&gt;</pre><p>Given that the purpose of the resolver is to obtain a typeface, one might expect this method to return a Typeface directly. Instead, Compose returns a State&lt;Any&gt;.</p><p>The reason becomes clear when we consider asynchronous font loading.</p><h4>Async Fonts</h4><p>Not all fonts are available immediately when text measurement begins. Some fonts may be loaded asynchronously through FontLoadingStrategy.Async.</p><p>In these situations, the final typeface may not be available at the moment resolve() is called. Returning a simple Typeface would make it difficult for the text system to react when the font eventually becomes available.</p><p>By returning a state-backed result, Compose can continue to observe changes to the resolved typeface over time.</p><h4>TypefaceResult</h4><p>Internally, the resolver produces instances of TypefaceResult.</p><p>When the requested typeface can be resolved immediately, Compose returns a TypefaceResult.Immutable.</p><pre>if (result is TypefaceResult.Immutable) {<br>    return result.value as Typeface<br>}</pre><p>In this case, the typeface is final and no further updates are expected.</p><p>However, asynchronous font requests may produce results that continue to evolve as loading progresses. This allows the font system to expose a single API regardless of whether the font is available immediately or must be loaded later.</p><h4>Dirty Tracking</h4><p>This design becomes visible inside <a href="https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:compose/ui/ui-text/src/androidMain/kotlin/androidx/compose/ui/text/ParagraphIntrinsics.android.kt;l=114?q=AndroidParagraphIntrinsics&amp;ss=androidx%2Fplatform%2Fframeworks%2Fsupport">AndroidParagraphIntrinsics</a>.</p><pre>val result =<br>    fontFamilyResolver.resolve(<br>        fontFamily,<br>        fontWeight,<br>        fontStyle,<br>        fontSynthesis<br>    )<br>if (result !is TypefaceResult.Immutable) {<br>    val newHead =<br>        TypefaceDirtyTrackerLinkedList(<br>            result,<br>            resolvedTypefaces<br>        )<br>    resolvedTypefaces = newHead<br>}</pre><p>Rather than immediately rebuilding the text layout, Compose registers non-immutable results for tracking.</p><p>When an asynchronously loaded font becomes available, the tracked state changes. The text layout system can then detect that the previously resolved typeface is no longer current and rebuild the paragraph using the updated font.</p><h4>Why This Matters</h4><p>This is one of the reasons Compose’s font system can support asynchronous font loading without exposing additional complexity to UI components.</p><p>A Text composable does not need to know whether a font is already available, still loading, or retrieved from cache. It simply describes its font requirements and delegates the rest of the process to the font resolution system.</p><p>From the perspective of the UI layer, font resolution remains a declarative operation. Internally, however, Compose maintains a state-aware pipeline capable of reacting to typeface updates as they occur.</p><h3>6. Key Takeaway</h3><p>The most important architectural shift in Compose’s font system is not the introduction of a new font API, but the separation of font resolution from UI components.</p><p>In the traditional View system, TextView was responsible for both describing text and resolving the typeface used to render it. Font selection, fallback handling, and typeface creation were all closely tied to the widget itself.</p><p>Compose takes a fundamentally different approach.</p><p>A Text composable does not resolve fonts. Instead, it describes its requirements through abstractions such as FontFamily, FontWeight, and FontStyle. These descriptors are then processed by a dedicated font resolution pipeline centered around FontFamily.Resolver.</p><p>Along the way, Compose:</p><ul><li>Converts font requirements into a TypefaceRequest</li><li>Reuses previous results through TypefaceRequestCache</li><li>Delegates platform-specific work to adapter implementations</li><li>Supports asynchronous font loading through state-backed results</li><li>Ultimately produces a native android.graphics.Typeface</li></ul><p>Conceptually, the entire flow can be summarized as follows:</p><pre>Text Composable<br> ↓<br>FontFamily<br> ↓<br>FontFamily.Resolver<br> ↓<br>TypefaceRequest<br> ↓<br>TypefaceRequestCache<br> ↓<br>FontFamilyTypefaceAdapter<br> ├─ FontListFontFamilyTypefaceAdapter<br> └─ PlatformFontFamilyTypefaceAdapter<br> ↓<br>android.graphics.Typeface</pre><p>This architecture allows Compose to remain declarative at the UI layer while maintaining a sophisticated and highly optimized font resolution system underneath.</p><p>Understanding this separation of concerns is the key to understanding how Compose transforms a simple FontFamily declaration into the concrete Typeface ultimately used by the Android rendering engine.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1fa214b5eae7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Loading Resources with Custom Qualifiers at Runtime in Android]]></title>
            <link>https://quokkaman.medium.com/loading-resources-with-custom-qualifiers-at-runtime-in-android-099145153884?source=rss-14e3cc4acf91------2</link>
            <guid isPermaLink="false">https://medium.com/p/099145153884</guid>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[compose]]></category>
            <dc:creator><![CDATA[Quokkaman]]></dc:creator>
            <pubDate>Sun, 14 Sep 2025 09:56:05 GMT</pubDate>
            <atom:updated>2025-09-14T09:56:05.453Z</atom:updated>
            <content:encoded><![CDATA[<h4>how to use Context#createConfigurationContext(Configuration) to fetch resources at runtime — with Kotlin and Java examples.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WjGxvcdrkP-Taycg" /><figcaption>Photo by <a href="https://unsplash.com/@vincentiu?utm_source=medium&amp;utm_medium=referral">Vincentiu Solomon</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3><strong>Introduction</strong></h3><p>As a developer building a custom Compose Design System library, I’ve run into a common but tricky problem. Our app leverages Android’s Runtime Resource Overlay (RRO) technology, allowing customers to download and apply various theme APKs. This resource-based approach has been the foundation of our theming system for a long time.</p><p><a href="https://source.android.com/docs/core/runtime/rros">Change the value of an app&#39;s resources at runtime | Android Open Source Project</a></p><p>However, with the rise of Jetpack Compose, a conflict has emerged. Google’s official Material theme system is built on Kotlin files for performance, not resources. While this is great for modern development, it threatens our existing, resource-based system. To maintain usability and ensure our extensive library of theme APKs remains compatible, I’ve built a resource-based Compose theme. The challenge? Even when I set darkTheme = true in my Theme composable, the resource system defaults to the system&#39;s uiMode. This means when the system is in light mode, my app incorrectly loads light-themed resources, even when I&#39;ve explicitly requested dark mode. This has led me to a crucial question: how can we dynamically load resources with a specific qualifier at runtime, independent of the device&#39;s configuration?</p><h3>The Basics: What Are Android Resource Qualifiers</h3><p>Android resource qualifiers are a core feature that allows you to create specialized resource directories (e.g., values-ko, values-night) within your res folder. This enables the Android system to automatically select the most appropriate resource based on a device&#39;s current configuration, helping developers efficiently support a wide range of devices and settings.</p><h3>III. The Solution: Using Context#createConfigurationContext()</h3><p>In the Android Context class, there is a method named createConfigurationContext .</p><p><a href="https://cs.android.com/android/platform/superproject/+/android-latest-release:frameworks/base/core/java/android/content/Context.java;l=7692?q=configurationContext">Context.java</a></p><pre>/**<br> * Return a new Context object for the current Context but whose resources<br> * are adjusted to match the given Configuration.  Each call to this method<br> * returns a new instance of a Context object; Context objects are not<br> * shared, however common state (ClassLoader, other Resources for the<br> * same configuration) may be so the Context itself can be fairly lightweight.<br> *<br> * @param overrideConfiguration A {@link Configuration} specifying what<br> * values to modify in the base Configuration of the original Context&#39;s<br> * resources.  If the base configuration changes (such as due to an<br> * orientation change), the resources of this context will also change except<br> * for those that have been explicitly overridden with a value here.<br> *<br> * @return A {@link Context} with the given configuration override.<br> */<br>public abstract Context createConfigurationContext(<br>        @NonNull Configuration overrideConfiguration);</pre><p>To understand this method, we need to look at ContextImpl, which is the implementation class for Context.</p><p><a href="https://cs.android.com/android/platform/superproject/+/android-latest-release:frameworks/base/core/java/android/app/ContextImpl.java;l=2869?q=ContextImpl">ContextImpl.java</a></p><pre>@Override<br>public Context createConfigurationContext(Configuration overrideConfiguration) {<br>    if (overrideConfiguration == null) {<br>        throw new IllegalArgumentException(&quot;overrideConfiguration must not be null&quot;);<br>    }<br><br>    if (mForceDisplayOverrideInResources) {<br>        // Ensure the resources display metrics are adjusted to match the display this context<br>        // is based on.<br>        Configuration displayAdjustedConfig = new Configuration();<br>        displayAdjustedConfig.setTo(mDisplay.getDisplayAdjustments().getConfiguration(),<br>                ActivityInfo.CONFIG_WINDOW_CONFIGURATION, 1);<br>        displayAdjustedConfig.updateFrom(overrideConfiguration);<br>        overrideConfiguration = displayAdjustedConfig;<br>    }<br><br>    ContextImpl context = new ContextImpl(this, mMainThread, mPackageInfo, mParams,<br>            mAttributionSource.getAttributionTag(), mAttributionSource.getNext(), mSplitName,<br>            mToken, mUser, mFlags, mClassLoader, null, mDeviceId,<br>            mIsExplicitDeviceId);<br>    context.mIsConfigurationBasedContext = true;<br><br>    final int displayId = getDisplayId();<br>    final Integer overrideDisplayId = mForceDisplayOverrideInResources<br>            ? displayId : null;<br>    context.setResources(createResources(mToken, mPackageInfo, mSplitName, overrideDisplayId,<br>            overrideConfiguration, getDisplayAdjustments(displayId).getCompatibilityInfo(),<br>            mResources.getLoaders()));<br>    return context;<br>}</pre><p>Based on the code and comments, we can guess that it creates a new Resources instance with an overridden configuration.</p><p>So, we can test it first because this API is public.</p><p>I set the color like this because testing a runtime resource overlay theme is a bit complex, so I’ll use the color for night mode even if the app’s UI mode is light.</p><p>values/colors.xml</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;resources&gt;<br>    &lt;!-- ... --&gt;<br>    &lt;color name=&quot;custom_text_color&quot;&gt;#FF000000&lt;/color&gt;<br>&lt;/resources&gt;</pre><p>values-night/colors.xml</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;resources&gt;<br>    &lt;!-- ... --&gt;<br>    &lt;color name=&quot;custom_text_color&quot;&gt;#FFFFFF&lt;/color&gt;<br>&lt;/resources&gt;</pre><p>Now, let’s get the color in Java/Kotlin first. We can get the color based on the configuration’s night mode.</p><pre>val color = ContextCompat.getColor(context, R.color.custom_text_color)<br>Log.d(&quot;ColorTest(Activity)&quot;, &quot;color=${color.toHexString(HexFormat.Default)}&quot;)</pre><p>with light mode(device settings)</p><pre>ColorTest(Activity): D color=ff000000</pre><p>with night mode(device settings)</p><pre>ColorTest(Activity): D color=ffffffff</pre><p>But this isn’t the behavior we expected, so we can use ConfigurationContext.</p><pre>val contextInDark= context.createConfigurationContext(<br>    Configuration().apply {<br>        uiMode = Configuration.UI_MODE_NIGHT_YES<br>    }<br>)<br>val colorInNight = ContextCompat.getColor(contextInDark, R.color.custom_text_color)<br>Log.d(&quot;ColorTest(Activity)&quot;, &quot;color=${colorInNight.toHexString(HexFormat.Default)}&quot;)</pre><p>Now, let’s execute the code. You will see that the color from the night folder is returned, even if the system settings are still in light mode.</p><p>with light mode(device settings)</p><pre>ColorTest(Activity): D color=ffffffff</pre><p>This can be advanced as shown below, allowing us to create a runtime resource qualifier for uiMode by changing darkTheme to either true or false.</p><pre>val darkTheme = true<br>val configurationContext = context.createConfigurationContext(<br>    Configuration().apply {<br>        uiMode = if (darkTheme) Configuration.UI_MODE_NIGHT_YES<br>        else Configuration.UI_MODE_NIGHT_NO<br>    }<br>)<br>val colorForDark = ContextCompat.getColor(configurationContext, R.color.custom_text_color)<br>Log.d(&quot;ColorTest(Activity)&quot;, &quot;color=${colorForDark.toHexString(HexFormat.Default)}&quot;)</pre><p>with light mode(device settings) + darkTheme(false)</p><pre>ColorTest(Activity): D color=ff000000</pre><p>with light mode(device settings) + darkTheme(true)</p><pre>ColorTest(Activity): D color=ffffffff</pre><h3>IV. Applying This to Jetpack Compose</h3><p>Now, let’s apply this to the Compose side!</p><p>First, I created a custom theme composable function. (Technically, I need to create a custom theme system, but I’ll simplify it with staticCompositionLocalOf for easier explanation.)</p><pre><br>val LocalCustomTextColor = staticCompositionLocalOf {<br>    Color.Unspecified<br>}<br>@Composable<br>public fun CustomTheme(<br>    darkTheme : Boolean = isSystemInDarkTheme(),<br>    content: @Composable () -&gt; Unit<br>) {<br>    val context = LocalContext.current<br><br>    val colorForDark = remember(darkTheme) {<br>        val configurationContext = context.createConfigurationContext(<br>            Configuration().apply {<br>                uiMode = if (darkTheme) Configuration.UI_MODE_NIGHT_YES<br>                else Configuration.UI_MODE_NIGHT_NO<br>            }<br>        )<br>        Color(ContextCompat.getColor(<br>            configurationContext,<br>            R.color.custom_text_color<br>        ))<br>    }<br><br>    CompositionLocalProvider(<br>        LocalCustomTextColor provides colorForDark<br>    ) {<br>        MaterialTheme(<br>            colorScheme = if (darkTheme) darkColorScheme()<br>            else lightColorScheme(),<br>            content = content<br>        )<br>    }<br>}</pre><p>Then, we can test it like this.</p><pre>CustomTheme(darkTheme = true) {<br>    Box(<br>        modifier = Modifier.fillMaxSize(),<br>        contentAlignment = Alignment.Center<br>    ) {<br>        Surface(<br>            color = MaterialTheme.colorScheme.background<br>        ) {<br>            Text(<br>                text = &quot;Hello, Quokkaman!&quot;,<br>                color = LocalCustomTextColor.current,<br>            )<br>        }<br>    }<br>}</pre><p>The text color from values-night has been loaded in Compose!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WIoEpfWsKuYsJMj0QZfi3g.png" /></figure><p>But someone might say, ‘Hey, on the Compose side, using colorResource is more friendly than ContextCompat.</p><p><a href="https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:compose/ui/ui/src/androidMain/kotlin/androidx/compose/ui/res/ColorResources.android.kt;l=35?q=fun%20colorResources&amp;sq=&amp;ss=androidx">ColorResources.android.kt</a></p><pre>/**<br> * Load a color resource.<br> *<br> * @param id the resource identifier<br> * @return the color associated with the resource<br> */<br>@Composable<br>@ReadOnlyComposable<br>fun colorResource(@ColorRes id: Int): Color {<br>    val context = LocalContext.current<br>    return Color(ResourcesCompat.getColor(LocalResources.current, id, context.theme))<br>}</pre><p>Yes, if you want to use colorResource, you can update LocalContext as shown below.</p><pre>val LocalCustomTextColor = staticCompositionLocalOf {<br>    Color.Unspecified<br>}<br>@Composable<br>public fun CustomTheme(<br>    darkTheme : Boolean = isSystemInDarkTheme(),<br>    content: @Composable () -&gt; Unit<br>) {<br>    val context = LocalContext.current<br><br>    val configurationContext = remember(darkTheme) {<br>        context.createConfigurationContext(<br>            Configuration().apply {<br>                uiMode = if (darkTheme) Configuration.UI_MODE_NIGHT_YES<br>                else Configuration.UI_MODE_NIGHT_NO<br>            }<br>        )<br>    }<br><br>    CompositionLocalProvider(<br>        LocalContext provides configurationContext<br>    ) {<br>        MaterialTheme(<br>            colorScheme = if (darkTheme) darkColorScheme()<br>            else lightColorScheme(),<br>            content = content<br>        )<br>    }<br>}</pre><p>Wonderful, by updating LocalContext, we can also support colorResource at the caller level! This seems much more powerful!</p><h3>V. A Word of Caution: Pitfalls to Avoid</h3><p>However, there is a critical issue: LocalContext has too many dependencies, so replacing the context with a configuration context can cause many side effects.</p><p>This is because a configuration context is not an ActivityContext, but most dependencies assume that LocalContext is an ActivityContext</p><p>So, if you update LocalContext, you need to be careful of this phenomenon.</p><h3>VI. Conclusion</h3><p>In conclusion, we’ve explored how powerful dynamic resource loading can be for specific scenarios, and hopefully, you now understand that Context#createConfigurationContext() is the key tool for achieving it.</p><p>This allows us to use a resource-based theme in Compose, and with this approach, I can support a resource theme system in Compose.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=099145153884" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Jetpack XR: How XR Development Works]]></title>
            <link>https://quokkaman.medium.com/exploring-jetpack-xr-how-xr-development-works-e38a32696f30?source=rss-14e3cc4acf91------2</link>
            <guid isPermaLink="false">https://medium.com/p/e38a32696f30</guid>
            <category><![CDATA[droidknights]]></category>
            <category><![CDATA[xr]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[jetpack]]></category>
            <category><![CDATA[project-moohan]]></category>
            <dc:creator><![CDATA[Quokkaman]]></dc:creator>
            <pubDate>Sat, 21 Jun 2025 10:46:25 GMT</pubDate>
            <atom:updated>2025-06-21T10:46:25.211Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>DroidKnights 2025 Session Recap</strong></h4><p>In this post, we’ll recap the session titled “Exploring Jetpack XR: How XR Development Works” presented at DroidKnights 2025. We’ll take a deep dive into how Android XR SDK and Jetpack XR enable XR development, focusing on their structure and operation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K6pU-FEF6GzK48HWJtul2g.png" /></figure><h3>The Background of Android XR</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S3c9vF2Ko4aCfTt-dFAZYw.png" /></figure><p>Recently, Samsung, Google, and Qualcomm have been collaborating on <strong>“Project Moohan” </strong>to develop a new Android-based XR device. In line with this, the Android XR SDK was introduced, followed by Preview 2 at Google I/O 2025.</p><p>The Android XR SDK is introduced in detail in the Google I/O session:</p><ul><li><a href="https://io.google/2025/explore/technical-session-22">Building differentiated apps for Android XR with 3D content</a></li><li><a href="https://io.google/2025/explore/technical-session-2">The future is now, with Compose and AI on Android XR</a></li></ul><p>Jetpack XR is here to provide a variety of XR features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q-0nNsrQj7KBjRqUJe28IA.png" /></figure><p>But will simply adding this library give us immediate available to XR features?</p><p>Jetpack XR enables XR features based on the Extensions architecture.</p><h3>The Extensions Structure</h3><p>A clear grasp of compile-time and runtime behavior is key to understanding how the Extensions structure works.</p><p>Let’s start by taking a closer look at the Android SDK and Android libraries.</p><h3>Background — Android SDK</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N4uHhlmKS6v3rrmqxN73FQ.png" /></figure><p>Android partners create their own system images based on the Android SDK. The SDK serves as a standard guideline that all manufacturers must follow, and each partner configures a system image that suits their own characteristics and needs, within the scope of this guide.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4xKjrSNSVBTWXWS5nHTY0A.png" /></figure><p><strong>Compile SDK</strong> refers to the Android API version used during app compilation. It sets the upper limit of APIs the app can reference during development, but has no impact on runtime. The Compile SDK is the official SDK provided by Google and used only during the build process — it is not included in the final APK.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i_VDw8t5CX1EeKYuml3M1g.png" /></figure><p><strong>Min SDK</strong> defines the minimum Android version required to install and run the app. It sets the lower bound for the runtime environment and determines whether an app can run on a given device.</p><h3>Background — Android Library</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m8P9C6ecox_hvQvn-G53WA.png" /></figure><p>Android Libraries are Java-based libraries that also bundle resources, manifests, and component definitions needed for Android development.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NLzmjw2Cd-LVzoqSPKFJhw.png" /></figure><p>When building an app, your code and resources are merged with the contents of the referenced libraries (classes, resources, manifests, and Proguard rules), eventually packaged into a single APK.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mYQkLXjClusApHjGTlVJKg.png" /></figure><h3>Why Extensions Were Introduced</h3><p>Android needs to support various form factors (phones, foldables, watches, XR, etc.).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nQNqU1irErvQfflP1KQtrA.png" /></figure><p>Splitting the SDK by device type would create fragmentation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z7WzbR_4UvNDRegJk0NWlQ.png" /></figure><p>Android have to maintain a unified SDK and exposes device-specific functionality.</p><p>This led to the creation of the Extensions structure.</p><p>Android is designed to provide device-specific features in the form of system libraries, while allowing the existing Android SDK to remain unchanged.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HC_TTT40Q4IeI3i9BRjP9w.png" /></figure><p>It allows Android to retain consistency and compatibility while extending functionality per device.</p><h3>The &lt;uses-library&gt; Tag</h3><p>At the heart of the Extensions structure is the &lt;uses-library&gt; tag in AndroidManifest.xml.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XI7lyg8_fOgWRu5Tn2p4Cw.png" /></figure><p>This tag allows your app to reference system libraries that are preinstalled on the device at runtime, without bundling them in your APK.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I10q0YhHkTpPsBr3_mIwcQ.png" /></figure><h3>How Extensions Work</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UK9x7i8fU3uKZ-faidiceA.png" /></figure><p>The Extensions structure uses &lt;uses-library&gt; to allow different libraries to be referenced at compile time and runtime.</p><p>A <strong>stub library</strong> is created with the same API signatures as the real system library but contains no actual functionality. Since these were developed using TODO() or RuntimeException, errors will occur when actually executed.</p><p>This stub library is included in the build using compileOnly, so it’s available at compile time but not packaged into the APK.</p><p>At runtime, the real implementation is accessed through the system library declared via &lt;uses-library&gt;.</p><p>This allows developers to use Extension features in a consistent manner, as if they were a single API.</p><h3>Downsides of the Extensions Structure</h3><p>Of course, the extension structure provides powerful extensibility, but it also comes with some caveats.</p><p><strong>Runtime Vulnerabilities:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GZmj_DtHCDKvmL6vhiFY5g.png" /></figure><p>If the stub and system libraries become mismatched, runtime crashes may occur.</p><p><strong>Optimization Restriction</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N2b6A_gUA1uxsR1C1bi6Dg.png" /></figure><p>Since Extension APIs are only used at runtime, tools like R8 may strip them during optimization because they can only analyze on compile time.</p><p><strong>Difficult API Changes</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9FnKI9pMB72RQ9rsKRzi3w.png" /></figure><p>Once a system library is released, it’s hard to update because it’s part of the platform binary.</p><p><strong>Complex Setup</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MruOtMP6HxSxPqAGfi-fgA.png" /></figure><p>Developers must properly configure:</p><ul><li>compileOnly for the stub library</li><li>&lt;uses-library&gt; in the manifest</li><li>Proguard rules to avoid stripping Extension APIs</li></ul><h3>High-Level Libraries</h3><p>To compensate for these complexities and shortcomings, high-level libraries emerged.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FIwMHvVofFoDnlNC2Ua7-Q.png" /></figure><p>The high-level library internally hides the Extension library and provides an independent API scheme that removes direct dependency on XrExtensions.</p><p>This will allow developers to use XR features in a more intuitive and concise way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y21jrF0vHXaKpw6Ca8iiCA.png" /></figure><p>Additionally, this high-level library already includes manifest settings with usage-library tags, and Proguard settings, so they should be automatically updated during the app build process.</p><p>Since the stub library is only needed when generating the class files of the high-level library, it can work without stub library.</p><p>As a result, developers can enjoy an environment where they can use XR functions easily and reliably without having to know the complex internal structure, with all necessary settings automatically applied by simply adding one high-level library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Joq0Xpn92D6INxix43yq9A.png" /></figure><h3>SceneCore</h3><p>SceneCore is a high-level library that abstracts XR Extensions, letting developers work with XR features through intuitive APIs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SxRw3_MuKsVrZuA1muMrDA.png" /></figure><p>SceneCore is a high-level abstraction of the XR Extensions library that provides XR features, allowing developers to leverage XR features through intuitive APIs without having to deal with complex internal implementations.</p><h3>Checking for Extensions</h3><p>You can easily check whether the extension structure is present through the settings file.</p><ul><li>Whether &lt;uses-library&gt; is defined in AndroidManifest.xml</li><li>Whether the stub library is added with compileOnly in build.gradle</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YHkZj9YsLY3Gagz5PDbenA.png" /></figure><p>SceneCore typically references the system library package com.android.extensions.xr.</p><p>That is, SceneCore has a structural design that operates on top of the Extensions structure while providing high-level abstractions.</p><h3>Entity-Component System</h3><p>The SceneCore library has a structure designed based on the Entity-Component system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EMlzG4jJVFnX6LPk_LYhFg.png" /></figure><p>The core unit in this structure is the Entity.</p><p>The core unit in this structure is the <strong>Entity</strong>. All XR elements are expressed as Entities, and a <strong>tree hierarchical structure</strong> can be formed through parent-child relationships.</p><p>Each Entity is given specific functions or properties by combining various <strong>Components</strong>.</p><p>The space where these Entities are placed is called a Scene. A <strong>Scene</strong> is a root container representing the entire XR environment, and contains one Root Entity inside.</p><p>And the controller that encompasses all of this is Session. <strong>Session</strong> operates under an Activity and plays a key role in managing the state and lifecycle of the XR environment. It also contains a Scene inside, which oversees the entire XR configuration.</p><p>In this article, we will look at how SceneCore internally forms an abstraction layer on top of XrExtensions, focusing specifically on the structure of Session and Entity.</p><h3>How Session is Created</h3><p>Let’s first take a look at how a Session is created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ldn-A0jffnRmg0h8NfGL8Q.png" /></figure><p>The Session is instantiated via a static factory method that accepts an Activity as an argument, and the actual logic is delegated to an internal method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M9K_o2nuaCvVcBYmlpqQEg.png" /></figure><p>Within the delegated method, a PlatformAdapter instance is first created, which is then used to initialize the Session object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K9LkrYSjlZ1jKWwX-_DgeA.png" /></figure><p>The PlatformAdapter instance created is specifically <strong>JxrPlatformAdapterAxr</strong>, which internally makes calls to the XR Extensions API.</p><h4>JxrPlatformAdapter</h4><p>JxrPlatformAdapter is an interface defined in the xr.runtime library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VPiwksncjEKGZQZGYuqUwQ.png" /></figure><p>The class that implements this interface is JxrPlatformAdapterAxr of SceneCore, and the XrExtensions API calls are made internally. In other words, SceneCore has a structure that indirectly connects to XR Extensions through this Adapter.</p><h3>Entity Creation</h3><p>Next, let’s look at the creation process of a PanelEntity that floats a View between Entities in 3D space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3epC_EpHaPefN9S8ah1swg.png" /></figure><p>PanelEntity is created via a static factory method that takes a Session and a View as arguments. This method decomposes the Session, extracts the necessary components, and passes them to the internal methods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VVCgPg27gc4-xkz4XVzvDQ.png" /></figure><p>PanelEntity wraps an rtEntity created through the adapter</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J9QnLKiJyGiN0WQYDUkoBQ.png" /></figure><p>Following the creation function of PlatformAdapter, this rtEntity is created with a Node of XrExtensions to form PanelEntityImpl.</p><h4>Entity and EntityImpl</h4><p>SceneCore’s Entity can be divided into an Entity that is not dependent on the platform, and an EntityImpl that is responsible for platform-dependent functions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ozz-BqEKnV5CcksM-Bu1JA.png" /></figure><p>Both Entity and EntityImpl implement the Entity interface defined in the xr.runtime class. This part is related to understanding the section, and it takes a structure that separates its responsibilities from the outside.</p><p>Entity is designed to be easy for developers to use with XR Extensions and cached abstraction APIs.</p><p>Entity creates EntityImpl through platformAdapter at creation time and then saves it. <br>EntityImpl internally saves and implements the Node of XrExtensions, and all platform-light functions are handled by EntityImpl.</p><p><strong>AndroidXrEntity::setScale</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3D0HoIVIMRRkMoQ3IKF03w.png" /></figure><p>The setScale method of Entity creates a Node Transaction to adjust the scale value when changing the size.</p><p><strong>AndroidXrEntity::setPose</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pB_ZJZGyUWeZdOME4Kn-_Q.png" /></figure><p>The setPose method specifically creates a NodeTransaction, sets the values, and then calls apply to apply them.</p><h4>Entity and Node</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pb06tQ0QZxYaVik6kAB1rw.png" /></figure><p>In XrExtensions, all XR elements are represented by a Node class.</p><p>It is designed to maintain the state of a Node and update it atomically by creating a NodeTransaction.</p><p>XrExtensions consists of a <strong>minimal set of classes</strong> and follows a design <strong>philosophy of minimizing API changes</strong>.</p><p>On the other hand, SceneCore provides other entities that separate permissions through trust structures.</p><p>As a result, SceneCore’s entities abstract the Extension API in an OOP manner, providing developers with more and easier-to-use structures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sStvriU6QcO-aNKcxadBpA.png" /></figure><h3>XR Compose</h3><p>XR Compose allows you to compose XR UIs using the features of existing Compose. There are two main types:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-WIykmeVcqYO6zwBnG-6rQ.png" /></figure><ul><li>Spatialized components: @Composable based</li><li>Sub-spatial components: @SubspaceComposable base</li></ul><h4>Spatialized Components</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9qffEyYo_bn3jyBE2fD2WQ.png" /></figure><p>Spatialized components include Orbiter, SpatialDialog, SpatialPopup, and SpatialElevation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z-iLbnMfCKnf94_r1zExqg.png" /></figure><p>All of these Spatialized components are based on ElevatedPanel.</p><p>So let’s take a look at the structure and internal implementation of ElevatedPanel and see how Spatialized components are structured.</p><p><strong>Explore an ElevatedPanel</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VIVtt7MzHkXhVhTIxH-y6g.png" /></figure><p>ElevatedPanel is a @Composable function that takes size, position, and content as arguments.</p><p>Inside ElevatedPanel, rememberComposeView is called to create a view object, and inside this, a ComposeView instance is created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QqwVLgaYceDG7ytZZKACdA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iuxpQ0fIZdLNWEytoTJloA.png" /></figure><p>The View created in this way is used to create PanelEntity, which is an API of SceneCore that we looked at earlier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y7SxNoJN2nCmI3VoOFIXyg.png" /></figure><p>Content passed to the store is linked to the ComposeView we create.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JiCLfT2JRMv_StyEJcAR8w.png" /></figure><p>When the position or size changes, we update the position and size in XR space by calling the Entity’s API whenever the value changes through LaunchedEffect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n91CbSBeaEaWpdMKgTpe5g.png" /></figure><p>Spatialized components are based on ElevatedPanel.</p><p>Create a ComposeView inside an ElevatedPanel, convert it to a PanelEntity in SceneCore, and then place it in the XR space.</p><p>In other words, Spatialized components serve the purpose of easily placing existing Compose UIs in 3D space.</p><h4>Subspace Components</h4><p>Next is the Subspace components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uEhUC3FhOBUHYxl-KWH_-g.png" /></figure><p>Subspace components include SpatialRow, SpatialColumn, SpatialBox that compose the layout, and SpatialPanel that can hold Compose UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HWcI932cSGSILmgLyR_XeQ.png" /></figure><p>Subspace components are all Subspace Composable functions annotated with th @SubspaceComposable annotation.</p><p>The content of the layout is also passed to the @SubspaceComposable function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bFqqkLB1jelfDNF8aFwDDQ.png" /></figure><p>All Subspace components are implemented based on SubspaceLayout.</p><p>So let’s take a look at how the Subspace component organizes and manages space, focusing on SubspaceLayout.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UPkQQ-VKz3HnasJlkt5Cuw.png" /></figure><p>SubspaceLayout receives content, SubspaceModifier, coreEntity, etc. as arguments.</p><p>If coreEntity is not shared, ContentlessEntity is created and used internally. ContentlessEntity is a special entity that does not contain content and is intended to support spatial arrangement such as position and size within the XR space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gWtoNPRK22NbDMwRHbEjgQ.png" /></figure><p>Internally, we create a ComposeSubspaceNode and set the SubspaceModifier and coreEntity.</p><p><strong>SubspaceLayoutNode::placeAt</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Flom_s-Hq_qPwg_cXghSQ.png" /></figure><p>In the placeAt method of SubspaceLayoutNode, which is a subclass of ComposeSubspaceNode, updateEntityPose of coreEntity is called internally.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZrneqmInCkUszxEkLK7ROQ.png" /></figure><p>This API calls setPose on an Entity to update its position in XR space.</p><p><strong>Subspace entry point</strong></p><p>Subspace Composable functions cannot be called directly from regular Composable functions. This requires a separate entry point, and the first entry point is the Subspace Composable function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D7zFiEHzEhA6zcXYkY9Eaw.png" /></figure><p>Subspace is a regular Composable function, but it takes a SubspaceComposable function as its content. Therefore, developers can call SubspaceComposable functions naturally in a regular Compose environment.</p><p>Looking at the internal implementation, if it is not nested, Subspace is delegated to ApplicationSubspace for processing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pRy_6Sg3wn5PvnupRa2JWQ.png" /></figure><p>ApplicationSubspace creates a SpatialComposeScene internally and connects the corresponding Composable function to this Scene.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ojdKOc0SuuOr03JZA9lsRA.png" /></figure><p>The second entry point is an extension function on Activity called setSubspaceContent.</p><p>This function internally calls getOrCreateSpatialSceneForActivity to get a Scene and then calls setContent on it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hbbZjQJpMSL6bKkTWkIobw.png" /></figure><p>This method also creates and uses a SpatialComposeScene.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HQ0oVGQ0hMjKI-zYWZHYNA.png" /></figure><p>Both the Subspace Composable function and setSubspaceContent internally create a SpatialComposeScene, which acts as an entry point for calling the Subspace Composable function.</p><p><strong>Configuration related to Compose UI</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EdrTEQ7wXYFyfXTxXS6moQ.png" /></figure><p>From what we’ve seen so far, we can see that the concept of Subspace is designed very similarly to the original Compose.</p><p>SubspaceComposable is actually implemented as a form that wraps Composable, and instead of the existing Compose UI node, it newly defines SubspaceNode to connect the Compose UI node and the SceneCore Entity, thereby supporting layout composition in the XR space.</p><p><strong>Explore a SpatialPanel</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Aj8DRX0AI1WouU032CfMfg.png" /></figure><p>Next, let’s look at the internal implementation of SpatialPanel, one of the Spatial components.</p><p>Inside that function, we are creating a ComposeView and creating a PanelEntity with CoreEntity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CNj0XFEorskz1Z0_3Um8BA.png" /></figure><p>SpatialPanel creates a PanelEntity and a ComposeView to draw the content, similar to a Spatialized component.</p><p>However, SpatialPanel also acts as an entry point from within the SubspaceComposable function, allowing you to call Composable functions again.</p><h3>Recap</h3><p>The Extensions structure provides a foundation for extending the functionality needed for XR devices while keeping the Android SDK intact.</p><p>This structure allows us to flexibly introduce new features without changing the SDK itself.</p><p>SceneCore abstracts XrExtensions to a high level, allowing developers to intuitively work with XR elements without having to know the complex internal implementation.</p><p>Finally, XR Compose helps existing Compose developers structure and control UI in a familiar way in an XR environment.</p><p>In this way, Jetpack XR will make future Android XR development easier and more efficient based on three major advantages: extensibility, intuitiveness, and productivity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*I-6Ca3P5Ik-I2MHyxmPGvQ.png" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fspeakerdeck.com%2Fplayer%2F17a88643962a459792f415e344389bd6&amp;display_name=Speaker+Deck&amp;url=https%3A%2F%2Fspeakerdeck.com%2Fheesung6701%2Fdroidknights-2025-jetpack-xr-salpyeobogi-xr-gaebaleun-eoddeohge-irueojineunga&amp;image=https%3A%2F%2Ffiles.speakerdeck.com%2Fpresentations%2F17a88643962a459792f415e344389bd6%2Fslide_0.jpg%3F35481542&amp;type=text%2Fhtml&amp;schema=speakerdeck" width="710" height="399" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6bc4c85a75bd07dbc7571873c7559cd/href">https://medium.com/media/b6bc4c85a75bd07dbc7571873c7559cd/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e38a32696f30" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Jetpack XR 살펴보기: XR 개발은 어떻게 이루어지는가?]]></title>
            <link>https://quokkaman.medium.com/jetpack-xr-%EC%82%B4%ED%8E%B4%EB%B3%B4%EA%B8%B0-xr-%EA%B0%9C%EB%B0%9C%EC%9D%80-%EC%96%B4%EB%96%BB%EA%B2%8C-%EC%9D%B4%EB%A3%A8%EC%96%B4%EC%A7%80%EB%8A%94%EA%B0%80-3b06af2151b5?source=rss-14e3cc4acf91------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b06af2151b5</guid>
            <category><![CDATA[project-moohan]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[droidknights]]></category>
            <category><![CDATA[jetpack]]></category>
            <category><![CDATA[xr]]></category>
            <dc:creator><![CDATA[Quokkaman]]></dc:creator>
            <pubDate>Sat, 21 Jun 2025 10:45:58 GMT</pubDate>
            <atom:updated>2025-06-21T10:45:58.996Z</atom:updated>
            <content:encoded><![CDATA[<h4>DroidKnights 2025 발표 정리</h4><p>이번 글에서는 Droid Knights 2025에서 발표한 “Jetpack XR 살펴보기: XR 개발은 어떻게 이루어지는가” 세션 내용을 정리해보려고 합니다. Android XR SDK 및 Jetpack XR이 어떻게 XR 개발을 가능하게 하는지, 그리고 그 구조와 동작 방식에 대해 자세히 살펴보겠습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K6pU-FEF6GzK48HWJtul2g.png" /></figure><h3>Android XR의 등장 배경</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S3c9vF2Ko4aCfTt-dFAZYw.png" /></figure><p>최근 삼성, 구글, 퀄컴은 공동으로 <strong>‘프로젝트 무한(Project Moohan)’</strong>을 통해 새로운 Android 기반 XR 디바이스를 개발하고 있습니다. 이에 발맞춰 Android XR SDK도 공개되었으며, 이어 Google I/O 2025에서 Preview 2가 소개되었습니다.</p><p>Android XR에 대한 소개는 Google IO 영상에서 소개 되고 있습니다.</p><ul><li><a href="https://io.google/2025/explore/technical-session-22">Building differentiated apps for Android XR with 3D content</a></li><li><a href="https://io.google/2025/explore/technical-session-2">The future is now, with Compose and AI on Android XR</a></li></ul><p>이처럼 다양한 XR 기능들을 제공하기 위해 등장한 것이 바로 <strong>Jetpack XR 라이브러리</strong>입니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q-0nNsrQj7KBjRqUJe28IA.png" /></figure><p>하지만 단순히 이 라이브러리를 추가한다고 해서 곧바로 XR 기능을 활용할 수 있을까요?</p><p>Jetpack XR은 Extensions 구조를 기반으로 하여서 XR 기능을 가능하게 만들어 줍니다.</p><h3>Extensions 구조</h3><p>Extensions의 구조를 이해 하려면, <strong>컴파일타임과</strong> <strong>런타임에</strong> <strong>대한 명확한 이해</strong>가 필요 합니다.</p><p>따라서 Android SDK와 Android Library를 살펴 보는 것으로 시작하겠습니다.</p><h4>사전 배경 — Android SDK</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N4uHhlmKS6v3rrmqxN73FQ.png" /></figure><p>안드로이드 파트너사들은 <strong>Android SDK를 기반으로 자체 시스템 이미지를 제작</strong>합니다. 즉, Android SDK는 모든 제조사가 따르는 <strong>표준 가이드라인</strong>의 역할을 하며, 각 파트너사는 이 가이드를 벗어나지 않는 범위 내에서 <strong>자신들의 특성과 요구에 맞는 시스템 이미지를 구성</strong>하게 됩니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4xKjrSNSVBTWXWS5nHTY0A.png" /></figure><p><strong>Compile SDK</strong>는 앱을 빌드할 때 <strong>어떤 Android API 버전을 기준으로 컴파일할 것인지 지정하는 설정</strong>입니다. 이는 곧 개발 중에 <strong>참조할 수 있는 최대 API 레벨</strong>을 의미하며, 실제 앱이 실행되는 런타임에는 영향을 주지 않습니다.</p><p>Compile SDK로 사용되는 Android SDK는 <strong>구글에서 제공하는 공식 SDK</strong>이며, 개발자의 데스크탑 환경에 설치되어 <strong>컴파일 시 참조용으로만 활용됩니다</strong>.</p><p>즉, 이 SDK는 앱을 빌드할 때 사용될 뿐, <strong>최종 APK 산출물에는 포함되지 않습니다.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i_VDw8t5CX1EeKYuml3M1g.png" /></figure><p><strong>Min SDK</strong>는 앱이 설치되고 실행되기 위해 필요한 <strong>최소 Android 버전</strong>을 정의하는 설정입니다. 이는 곧 앱이 동작할 수 있는 <strong>최소한의 런타임 환경을 지정</strong>합니다.</p><p>즉, Min SDK는 앱이 <strong>지원할 수 있는 가장 낮은 Android 버전</strong>을 의미하며, 이는 곧 런타임에서의 <strong>실행 가능 여부를 결정짓는 제약 조건</strong>으로 작용합니다.</p><h4>사전 배경 — Android Library</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m8P9C6ecox_hvQvn-G53WA.png" /></figure><p><strong>안드로이드 라이브러리(Android Library)</strong>는 <strong>기존 자바 라이브러리</strong>를 기반으로, 안드로이드 앱 개발에 필요한 <strong>리소스, 매니페스트, 컴포넌트 정의 등 다양한 구성 요소</strong>를 함께 포함한 형태로 제공됩니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NLzmjw2Cd-LVzoqSPKFJhw.png" /></figure><p>앱을 빌드할 때는 <strong>개발자가 작성한 소스 코드와 리소스</strong>뿐만 아니라,</p><p><strong>참조된 라이브러리의 클래스, 리소스, 매니페스트, Proguard 설정 등</strong> 다양한 구성 요소가 함께 병합됩니다.</p><p>이러한 과정을 거쳐 모든 요소가 통합된 후, 최종적으로 하나의 <strong>APK(Android Package)</strong> 파일로 생성되어 배포됩니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mYQkLXjClusApHjGTlVJKg.png" /></figure><h4>등장 배경</h4><p>Android는 다양한 폼팩터(폰, 폴더블, 워치, XR 등)를 지원해야 합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nQNqU1irErvQfflP1KQtrA.png" /></figure><p>그러나 이를 위해 SDK를 디바이스 별로 나누면 파편화 문제가 발생합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z7WzbR_4UvNDRegJk0NWlQ.png" /></figure><p>이를 해결하기 위해 Android SDK는 단일로 유지하면서, 시스템 라이브러리 형태로 확장을 지원하는 구조가 필요해졌고, 그 결과가 Extensions 구조입니다.</p><p>Android는 단말별 특화 기능을 <strong>시스템 라이브러리 형태로 분리 제공</strong>하고, 기존 <strong>Android SDK는 변경 없이 그대로 유지</strong>할 수 있도록 설계되었습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HC_TTT40Q4IeI3i9BRjP9w.png" /></figure><p>이로써 다양한 디바이스 요구사항을 충족하면서도, Android 플랫폼의 <strong>일관성과 호환성</strong>을 유지할 수 있게 된 것입니다.</p><h4>&lt;uses-library&gt; 태그</h4><p><strong>Extensions 구조의 기반이 되는 핵심 요소는 &lt;uses-library&gt; 태그입니다.</strong></p><p>이 태그는 AndroidManifest.xml에 정의되며, 앱이 <strong>런타임 시 디바이스에 내장된 시스템 라이브러리를 참조</strong>할 수 있도록 설정해 줍니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XI7lyg8_fOgWRu5Tn2p4Cw.png" /></figure><p>이를 통해 앱은 별도로 라이브러리를 포함하지 않더라도, <strong>시스템에 이미 존재하는 확장 기능들을 안정적으로 활용</strong>할 수 있게 됩니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I10q0YhHkTpPsBr3_mIwcQ.png" /></figure><h4><strong>Extensions 구조 동작 원리</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UK9x7i8fU3uKZ-faidiceA.png" /></figure><p><strong>Extensions 구조는 &lt;uses-library&gt; 태그를 활용해</strong>, <strong>동일한 API 심볼</strong>에 대해 <strong>컴파일 타임과 런타임에 서로 다른 라이브러리</strong>를 참조할 수 있도록 설계된 구조입니다.</p><p>Extensions 구조를 구현하기 위해서는, <strong>시스템 라이브러리와 동일한 API 시그니처를 가진 stub 라이브러리</strong>를 별도로 생성해야 합니다.</p><p>이 stub 라이브러리는 실제 기능을 포함하지 않으며, 내부 구현은 TODO()나 RuntimeException 등을 포함해 <strong>실행 시 오류가 발생하도록 의도적으로 비워진 상태</strong>입니다.</p><p>즉, <strong>오직 컴파일 타임 용도로만 사용되는 라이브러리</strong>인 셈입니다.</p><p>개발자는 이 stub 라이브러리를 <strong>compileOnly 설정을 통해 컴파일 시에만 참조</strong>하도록 구성합니다. 이렇게 하면 Extension API를 호출하더라도 빌드가 가능하며, <strong>최종 산출물인 APK에는 이 라이브러리의 구현이 포함되지 않게 됩니다.</strong></p><p>그러나 이로 인해 <strong>런타임 시 API 호출이 발생하면 심볼을 찾을 수 없어 오류가 날 수 있습니다. </strong>이를 해결하기 위해 사용하는 것이 바로 앞서 소개한 &lt;uses-library&gt; 태그입니다.</p><p>이 태그를 활용하면, 앱이 실행될 때 <strong>디바이스에 내장된 시스템 라이브러리를 참조</strong>하게 됩니다.</p><p>즉, 컴파일 시에는 stub 라이브럴리를, 런타임 시에는 실제 구현참조 합니다.</p><p>덕분에 개발자는 마치 하나의 API처럼 <strong>일관된 방식</strong>으로 Extension 기능을 사용할 수 있습니다.</p><h4><strong>단점</strong></h4><p>물론 Extensions 구조는 강력한 확장성을 제공하지만, 그만큼 <strong>주의해야 할 단점과 복잡성</strong>도 함께 존재합니다.</p><p><strong>단점 1 - 런타임 에러에 취약</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GZmj_DtHCDKvmL6vhiFY5g.png" /></figure><p>가장 큰 리스크는 <strong>stub 라이브러리와 시스템 라이브러리 간의 버전 불일치</strong>입니다. 컴파일 시에는 문제가 없어 보이더라도, 런타임에 실제 구현과 API 시그니처가 다를 경우 <strong>예기치 않은 크래시나 동작 오류</strong>가 발생할 수 있습니다.</p><p><strong>단점 2 — 코드 최적화 제약</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N2b6A_gUA1uxsR1C1bi6Dg.png" /></figure><p>또한 Extension API는 <strong>런타임에만 참조되는 구조</strong>이기 때문에, 컴파일 시점에는 사용되지 않는 코드로 간주되어 R8에 의해 <strong>난독화되거나 제거될 수 있는 위험</strong>이 존재합니다.</p><p>이 경우, 앱 실행 중 해당 심볼을 찾지 못해 <strong>런타임 오류가 발생할 수 있습니다.</strong></p><p><strong>단점 3 —API 변경 어려움</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9FnKI9pMB72RQ9rsKRzi3w.png" /></figure><p>게다가 Extension API는 <strong>시스템 라이브러리 형태로 배포</strong>되기 때문에, 일반 라이브러리처럼 단순히 버전 업만으로 수정할 수 없습니다.</p><p>실제로는 <strong>플랫폼 수준에서의 바이너리 배포가 필요</strong>하며, 한 번 배포된 API는 <strong>사후 수정이 매우 어렵다는 제약</strong>을 가집니다.</p><p><strong>단점 4 — 복잡한 환경 설정</strong></p><p>따라서 Extensions 구조를 안정적으로 사용하려면 다음과 같은 설정이 필요합니다:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MruOtMP6HxSxPqAGfi-fgA.png" /></figure><ul><li>build.gradle에서 <strong>stub 라이브러리를 compileOnly로 설정</strong></li><li>AndroidManifest.xml에 <strong>&lt;uses-library&gt; 태그로 시스템 라이브러리 명시</strong></li><li>R8 최적화 과정에서 API가 제거되지 않도록 <strong>적절한 Proguard 설정 추가</strong></li></ul><p>이러한 조건들을 정확히 이해하고 세팅해야만</p><p>Extension API가 <strong>정상적으로 동작하며 안정적인 앱 실행이 보장</strong>됩니다.</p><p>결과적으로, 이 구조는 <strong>개발자에게 다소 복잡하고 정교한 환경 설정을 요구</strong>하게 됩니다.</p><h4><strong>고수준 라이브러리</strong></h4><p>이러한 복잡성과 단점을 보완하기 위해 등장한 것이 바로 <strong>고수준 라이브러리(high-level library)</strong>입니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FIwMHvVofFoDnlNC2Ua7-Q.png" /></figure><p>고수준 라이브러리는 내부적으로 Extension 라이브러리를 감추고, <strong>XrExtensions와의 직접적인 의존성을 제거한 독립적인 API 체계</strong>를 제공합니다.</p><p>덕분에 개발자는 <strong>보다 직관적이고 간결한 방식</strong>으로 XR 기능을 사용할 수 있게 됩니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y21jrF0vHXaKpw6Ca8iiCA.png" /></figure><p>또한 이 고수준 라이브러리는 이미 uses-library 태그가 포함된 <strong>Manifest 설정</strong>과, R8 최적화를 고려한 <strong>Proguard 설정</strong>까지 포함하고 있어, 앱 빌드 과정에서 <strong>자동으로 병합</strong>되도록 설계되어 있습니다.</p><p>stub 라이브러리는 고수준 라이브러리의 <strong>클래스 파일 생성 시점에만 필요</strong>하기 때문에, 실제 앱은 stub 라이브러리에 대한 참조가 필요하지 않습니다.</p><p>결과적으로, 개발자는 단지 <strong>고수준 라이브러리 하나만 추가</strong>하면, 필요한 설정이 모두 자동으로 적용되고, 복잡한 내부 구조를 몰라도 <strong>간편하고 안정적으로 XR 기능을 사용할 수 있는 환경</strong>을 누릴 수 있게 됩니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Joq0Xpn92D6INxix43yq9A.png" /></figure><h3>SceneCore: 고수준 XR 추상화</h3><p>앞서 살펴본 것처럼 <strong>Extensions 구조는 설정이 까다롭고 런타임 리스크가 존재</strong>하기 때문에, 실제 개발 환경에서는 이를 <strong>고수준 라이브러리로 감싸 제공하는 전략</strong>이 널리 사용되고 있습니다.</p><p>SceneCore는 바로 이러한 전략을 사용 하고 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SxRw3_MuKsVrZuA1muMrDA.png" /></figure><p>SceneCore는 XR 기능을 제공하는 <strong>XR Extensions 라이브러리를 고수준으로 추상화</strong>한 라이브러리로, 개발자가 복잡한 내부 구현을 직접 다루지 않고도 <strong>직관적인 API를 통해 XR 기능을 활용할 수 있도록</strong> 도와줍니다.</p><h4>Extensions 확인</h4><p>Extension 구조 여부는 <strong>설정 파일</strong>을 통해서 쉽게 확인할 수 있습니다.</p><ul><li><strong>AndroidManifest.xml</strong>에 &lt;uses-library&gt; 태그가 정의되어 있는지</li><li><strong>build.gradle</strong> 파일에 stub 라이브러리가 compileOnly로 추가되어 있는지</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YHkZj9YsLY3Gagz5PDbenA.png" /></figure><p>실제로 SceneCore의 설정을 확인해보면, com.android.extensions.xr 패키지를 기반으로 한 시스템 라이브러리가 명시되어 있으며, 이는 SceneCore가 <strong>Extensions 구조를 활용해 XR 기능을 제공하고 있다는 사실</strong>을 보여줍니다.</p><p>즉, SceneCore는 <strong>고수준 추상화를 제공하는 동시에</strong>, <strong>Extensions 구조의 기반 위에 동작하는 구조적 설계</strong>를 갖추고 있는 것입니다.</p><h4>Entity Component System</h4><p><strong>SceneCore 라이브러리</strong>는 Entity-Component 시스템을 기반으로 설계된 구조를 갖고 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EMlzG4jJVFnX6LPk_LYhFg.png" /></figure><p>이 구조에서 핵심이 되는 단위는 바로 <strong>Entity</strong>입니다. 모든 XR 요소는 Entity로 표현되며, <strong>부모-자식 관계를 통해 트리 형태의 계층 구조</strong>를 구성할 수 있습니다.</p><p>각 Entity는 다양한 <strong>Component를 조합</strong>함으로써 특정 기능이나 속성을 부여받게 됩니다.</p><p>이러한 Entity들이 배치되는 공간이 바로 <strong>Scene</strong>입니다. Scene은 <strong>XR 환경 전체를 대표하는 루트 컨테이너</strong>로, 내부에는 하나의 <strong>Root Entity</strong>를 포함하고 있습니다.</p><p>그리고 이 모든 것을 아우르는 컨트롤러가 바로 <strong>Session</strong>입니다. Session은 하나의 Activity에 종속되어 동작하며, <strong>XR 환경의 상태 및 생명주기 전반을 관리</strong>하는 핵심 역할을 수행합니다. 또한 내부에는 하나의 Scene을 포함하고 있어, 전체 XR 구성을 총괄합니다.</p><p>이번 내용에서는 특히 <strong>Session과 Entity의 구조</strong>를 중심으로, SceneCore가 내부적으로 어떻게 <strong>XrExtensions 위에 추상화 계층을 형성하고 있는지</strong> 함께 살펴보겠습니다.</p><h4>Session의 생성 과정</h4><p>가장 먼저 Session이 생성되는 과정을 살펴 보고자 합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ldn-A0jffnRmg0h8NfGL8Q.png" /></figure><p>Session은 Activity를 인자로 받는 정적 팩토리 메서드를 통해 생성되며, 이 메서드는 내부 구현 메서드로 위임됩니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M9K_o2nuaCvVcBYmlpqQEg.png" /></figure><p>내부로 위임된 메서드에서는 먼저 PlatformAdapter 인스턴스를 생성한 뒤, 이를 활용해 Session 객체를 생성합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K9LkrYSjlZ1jKWwX-_DgeA.png" /></figure><p>생성되는 PlatformAdapter는 실제로 JxrPlatformAdapterAxr이며, 내부에서 XR Extensions API가 호출되고 있습니다.</p><h4>JxrPlatformAdapter</h4><p>JxrPlatformAdapter는 xr.runtime 라이브러리 내에 정의된 인터페이스입니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VPiwksncjEKGZQZGYuqUwQ.png" /></figure><p>이 인터페이스를 구현한 클래스가 SceneCore의 JxrPlatformAdapterAxr이며, 내부에서 XrExtensions API 호출이 이루어지고 있습니다.</p><p>즉, SceneCore는 이 Adapter를 통해 간접적으로 XR Extensions와 연결되는 구조를 갖습니다.</p><h4>Entity 생성 과정</h4><p>다음은 Entity 중 View를 3D 공간에 띄우는 PanelEntity의 생성 과정을 살펴보겠습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3epC_EpHaPefN9S8ah1swg.png" /></figure><p>PanelEntity는 Session과 View를 인자로 받는 정적 팩토리 메서드를 통해 생성됩니다.</p><p>이 메서드는 Session을 분해해 필요한 구성 요소를 추출한 뒤, 이를 내부 메서드에 전달합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VVCgPg27gc4-xkz4XVzvDQ.png" /></figure><p>내부 메서드에서는 PanelEntity를 생성하는데, 이때 PanelEntity는 내부적으로 rtEntity를 래핑하고 있으며, 이 rtEntity는 PlatformAdapter를 통해 생성됩니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J9QnLKiJyGiN0WQYDUkoBQ.png" /></figure><p>PlatformAdapter의 생성 함수를 따라가보면, XrExtensions의 Node 객체를 생성한 뒤 이를 인자로 PanelEntityImpl 객체를 생성하고 있습니다.</p><h4>Entity와 EntityImpl</h4><p>SceneCore의 Entity는 platform에 종속되지 않은 추상화된 Entity와, platform 종속적인 기능을 담당하는 EntityImpl로 나눌 수 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ozz-BqEKnV5CcksM-Bu1JA.png" /></figure><p>Entity와 EntityImpl은 모두 xr.runtime 라이브러리에 정의된 Entity 인터페이스를 구현하고 있습니다. 이를 통해 공통된 기능을 동일한 형태로 다루면서, 외부와 내부의 책임을 명확히 분리하는 구조를 갖추고 있습니다.</p><p>Entity는 XR Extensions와 독립된 추상화된 API로, 개발자가 쉽게 사용할 수 있도록 설계되어 있습니다. Entity는 생성 시점에 platformAdapter를 통해 EntityImpl을 생성한 뒤 이를 래핑합니다.</p><p>EntityImpl은 내부적으로 XrExtensions의 Node를 래핑해 구현되며, 플랫폼 종속적인 기능은 모두 EntityImpl에서 처리합니다.</p><p><strong>AndroidXrEntity::setScale</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3D0HoIVIMRRkMoQ3IKF03w.png" /></figure><p>Entity의 setScale 메서드는 크기를 변경할 때 NodeTransaction을 생성하여 scale 값을 조정합니다.</p><p><strong>AndroidXrEntity::setPose</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pB_ZJZGyUWeZdOME4Kn-_Q.png" /></figure><p>setPose 메서드 역시 NodeTransaction을 생성한 뒤 값을 설정하고, apply를 호출하여 적용합니다.</p><h4>Entity와 Node</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pb06tQ0QZxYaVik6kAB1rw.png" /></figure><p>XrExtensions에서는 모든 XR 요소가 공통된 Node 클래스로 표현됩니다.</p><p>Node의 상태를 변경할 때는 NodeTransaction을 생성해 원자적으로 업데이트하도록 설계되어 있습니다.</p><p>XrExtensions는 최소한의 클래스 세트로 구성되어 있으며, API 변경을 최소화하려는 설계 철학을 따르고 있습니다.</p><p>반면 SceneCore는 상속 구조를 통해 책임을 분리한 다양한 Entity를 제공하고 있습니다.</p><p>결과적으로 SceneCore의 Entity는 Extension API를 OOP 방식으로 추상화하여, 개발자에게 더 직관적이고 사용하기 쉬운 구조를 제공합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sStvriU6QcO-aNKcxadBpA.png" /></figure><h3>XR Compose: Compose 기반 XR UI 구성</h3><p>XR Compose는 기존 Compose와 유사한 방식으로 XR UI를 구성할 수 있도록 해줍니다. 크게 두 가지 유형이 있습니다:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-WIykmeVcqYO6zwBnG-6rQ.png" /></figure><ul><li><strong>Spatialized 컴포넌트</strong>: @Composable 기반 (e.g., Orbiter, SpatialDialog)</li><li><strong>Subspace 컴포넌트</strong>: @SubspaceComposable 기반 (e.g., SpatialRow, SpatialPanel)</li></ul><h4>Spatialized 컴포넌트</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9qffEyYo_bn3jyBE2fD2WQ.png" /></figure><p>Spatialized 컴포넌트에는 Orbiter, SpatialDialog, SpatialPopup, SpatialElevation 등이 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z-iLbnMfCKnf94_r1zExqg.png" /></figure><p>이러한 Spatialized 컴포넌트들은 모두 ElevatedPanel을 기반으로 구성되어 있습니다.</p><p>따라서 ElevatedPanel의 구조와 내부 구현을 살펴보며, Spatialized 컴포넌트들이 어떻게 구성되어 있는지 알아보겠습니다.</p><p><strong>ElevatedPanel 살펴보기</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VIVtt7MzHkXhVhTIxH-y6g.png" /></figure><p>ElevatedPanel은 크기, 위치, 그리고 content를 인자로 받는 @Composable 함수입니다.</p><p>ElevatedPanel 내부에서는 rememberComposeView를 호출해 view 객체를 생성하고 있으며, 이 내부에서는 ComposeView 인스턴스를 생성하고 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QqwVLgaYceDG7ytZZKACdA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iuxpQ0fIZdLNWEytoTJloA.png" /></figure><p>이렇게 생성된 View는 앞서 살펴본 SceneCore의 API인 PanelEntity를 생성하는 데 사용됩니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y7SxNoJN2nCmI3VoOFIXyg.png" /></figure><p>인자로 전달된 content는 앞서 생성한 ComposeView에 연결되고 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JiCLfT2JRMv_StyEJcAR8w.png" /></figure><p>위치나 사이즈가 변경될 경우, LaunchedEffect를 통해 값이 변경될 때마다 Entity의 API를 호출하여 XR 공간상의 위치와 크기를 갱신하고 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n91CbSBeaEaWpdMKgTpe5g.png" /></figure><p>Spatialized 컴포넌트는 ElevatedPanel을 기반으로 동작합니다.</p><p>ElevatedPanel 내부에서는 ComposeView를 생성하고, 이를 SceneCore의 PanelEntity로 변환하여 XR 공간에 배치합니다.</p><p>즉, Spatialized 컴포넌트는 기존 Compose UI를 손쉽게 3D 공간에 배치하는 역할을 수행합니다.</p><h4>Subspace 컴포넌트</h4><p>다음은 Subspace 컴포넌트입니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uEhUC3FhOBUHYxl-KWH_-g.png" /></figure><p>Subspace 컴포넌트에는 레이아웃을 구성하는 SpatialRow, SpatialColumn, SpatialBox와 Compose UI를 올릴 수 있는 SpatialPanel 등이 포함되어 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HWcI932cSGSILmgLyR_XeQ.png" /></figure><p>Subspace 컴포넌트들은 모두 @SubspaceComposable 어노테이션이 적용된 Subspace Composable 함수입니다.</p><p>레이아웃의 content 역시 @SubspaceComposable 함수로 전달받고 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bFqqkLB1jelfDNF8aFwDDQ.png" /></figure><p>Subspace 컴포넌트는 모두 SubspaceLayout을 기반으로 구현되어 있습니다.</p><p>따라서 SubspaceLayout을 중심으로 Subspace 컴포넌트가 공간을 어떻게 구성하고 관리하는지 살펴보겠습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UPkQQ-VKz3HnasJlkt5Cuw.png" /></figure><p>SubspaceLayout은 content, SubspaceModifier, coreEntity 등을 인자로 받고 있습니다.</p><p>coreEntity를 별도로 전달하지 않은 경우, 내부적으로 ContentlessEntity를 생성해 사용합니다. ContentlessEntity는 직접적인 콘텐츠는 없지만, XR 공간 내에서 위치나 크기 등 공간 배치를 지원하기 위해 설계된 특별한 Entity입니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gWtoNPRK22NbDMwRHbEjgQ.png" /></figure><p>내부적으로는 ComposeSubspaceNode를 생성해 SubspaceModifier와 coreEntity를 설정하고 있습니다.</p><p><strong>SubspaceLayoutNode의 placeAt</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Flom_s-Hq_qPwg_cXghSQ.png" /></figure><p>ComposeSubspaceNode의 서브클래스인 SubspaceLayoutNode의 placeAt 메서드에서는, 내부에서 coreEntity의 updateEntityPose를 호출하고 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZrneqmInCkUszxEkLK7ROQ.png" /></figure><p>그리고 이 API에서는 Entity의 setPose를 호출하여 XR 공간상의 위치를 업데이트하고 있습니다.</p><p><strong>Subspace 진입점</strong></p><p>Subspace Composable 함수는 일반 Composable 함수에서 바로 호출할 수 없습니다. 이를 위해서는 별도의 진입점이 필요하며, 첫 번째 진입점은 Subspace 컴포저블 함수입니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D7zFiEHzEhA6zcXYkY9Eaw.png" /></figure><p>Subspace는 일반 Composable 함수지만, content로 SubspaceComposable 함수를 인자로 받고 있습니다. 따라서 개발자는 일반 Compose 환경에서 자연스럽게 SubspaceComposable 함수를 호출할 수 있습니다.</p><p>내부 구현을 살펴보면, 중첩된 경우가 아니라면 Subspace는 ApplicationSubspace로 위임되어 처리됩니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pRy_6Sg3wn5PvnupRa2JWQ.png" /></figure><p>ApplicationSubspace는 내부에서 SpatialComposeScene을 생성하고, 해당 Composable 함수를 이 Scene에 연결해주고 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ojdKOc0SuuOr03JZA9lsRA.png" /></figure><p>두 번째 진입점은 Activity의 확장 함수인 setSubspaceContent입니다.</p><p>이 함수는 내부적으로 getOrCreateSpatialSceneForActivity를 호출해 Scene을 가져오고, 그 위에서 setContent를 호출합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hbbZjQJpMSL6bKkTWkIobw.png" /></figure><p>이 메서드 역시 SpatialComposeScene을 생성하여 사용하고 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HQ0oVGQ0hMjKI-zYWZHYNA.png" /></figure><p>Subspace 컴포저블 함수와 setSubspaceContent는 모두 내부적으로 SpatialComposeScene을 생성하여, Subspace Composable 함수를 호출할 수 있는 진입점 역할을 수행하고 있습니다.</p><p><strong>Compose UI 와 유사한 구조</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EdrTEQ7wXYFyfXTxXS6moQ.png" /></figure><p>지금까지 살펴본 내용을 보면, Subspace의 개념은 기존 Compose와 매우 유사하게 설계되었음을 알 수 있습니다.</p><p>SubspaceComposable은 실제로 Composable을 래핑한 형태로 구현되어 있으며, 기존 Compose UI 노드 대신 SubspaceNode를 새롭게 정의해 Compose UI 노드와 SceneCore의 Entity를 연결함으로써 XR 공간에서의 레이아웃 구성을 지원하고 있습니다.</p><p><strong>SpatialPanel 살펴보기</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Aj8DRX0AI1WouU032CfMfg.png" /></figure><p>다음으로 Spatial 컴포넌트 중 하나인 SpatialPanel의 내부 구현을 살펴보겠습니다.</p><p>해당 함수 내부에서는 ComposeView를 생성하고, CoreEntity로 PanelEntity를 생성하고 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CNj0XFEorskz1Z0_3Um8BA.png" /></figure><p>SpatialPanel은 content를 그리기 위해 PanelEntity와 ComposeView를 생성하며, 이는 Spatialized 컴포넌트와 유사합니다.</p><p>하지만 SpatialPanel은 SubspaceComposable 함수 내에서 다시 Composable 함수를 호출할 수 있는 <strong>진입점 역할</strong>을 함께 수행합니다.</p><h3>마무리 하며</h3><p><strong>Extensions 구조</strong>는 Android SDK를 그대로 유지하면서도 XR 디바이스에 필요한 기능을 확장할 수 있는 기반을 제공했습니다.</p><p>이 구조 덕분에 SDK 자체를 변경하지 않고도 새로운 기능을 유연하게 도입할 수 있게 되었습니다.</p><p><strong>SceneCore</strong>는 XrExtensions를 고수준으로 추상화하여, 개발자가 복잡한 내부 구현을 몰라도 직관적으로 XR 요소를 다룰 수 있게 해주었습니다.</p><p>마지막으로 <strong>XR Compose</strong>는 기존 Compose 개발자들이 XR 환경에서도 친숙한 방식으로 UI를 구성하고 제어할 수 있도록 돕는 역할을 합니다.</p><p>이처럼 Jetpack XR은 <strong>확장성, 직관성, 생산성</strong>이라는 세 가지 큰 장점을 기반으로, 앞으로의 Android XR 개발을 더욱 쉽고 효율적으로 만들어 줄 것입니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*I-6Ca3P5Ik-I2MHyxmPGvQ.png" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fspeakerdeck.com%2Fplayer%2F17a88643962a459792f415e344389bd6&amp;display_name=Speaker+Deck&amp;url=https%3A%2F%2Fspeakerdeck.com%2Fheesung6701%2Fdroidknights-2025-jetpack-xr-salpyeobogi-xr-gaebaleun-eoddeohge-irueojineunga&amp;image=https%3A%2F%2Ffiles.speakerdeck.com%2Fpresentations%2F17a88643962a459792f415e344389bd6%2Fslide_0.jpg%3F35481542&amp;type=text%2Fhtml&amp;schema=speakerdeck" width="710" height="399" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6bc4c85a75bd07dbc7571873c7559cd/href">https://medium.com/media/b6bc4c85a75bd07dbc7571873c7559cd/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b06af2151b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android SDK, AAR, 그리고 Extensions Architecture]]></title>
            <link>https://quokkaman.medium.com/android-sdk-aar-%EA%B7%B8%EB%A6%AC%EA%B3%A0-extensions-architecture-0a58b69b17da?source=rss-14e3cc4acf91------2</link>
            <guid isPermaLink="false">https://medium.com/p/0a58b69b17da</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-sdk]]></category>
            <category><![CDATA[androidx]]></category>
            <category><![CDATA[jetpack]]></category>
            <category><![CDATA[extensions-architecture]]></category>
            <dc:creator><![CDATA[Quokkaman]]></dc:creator>
            <pubDate>Fri, 25 Apr 2025 16:24:08 GMT</pubDate>
            <atom:updated>2025-04-25T16:24:08.351Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>SDK에서 AAR, 그리고 Extensions Architecture</strong></p><p>안드로이드 개발자라면 Android SDK를 사용해 앱을 컴파일하고, AAR 라이브러리를 포함시키며, APK를 생성하는 과정에 익숙할 것입니다. 하지만 이 간단해 보이는 과정 뒤에는 컴파일 타임 추상화와 런타임 구현, 동적 클래스 로딩을 연결해주는 복잡한 시스템이 숨어 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*a9f-AQ1a7Xs2CxfGyxXENQ.png" /></figure><p>Android는 다양한 기기를 지원하기 위해 일부 라이브러리는 Extesions Architecture를 기반으로 라이브러리를 설계했습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nkn5xjN1KayzDHrnJ3yiuw.png" /><figcaption>이 글을 통해 위 다이어그램에 나타난 구조를 명확하게 이해할 수 있기를 바랍니다.</figcaption></figure><p>예를 들어 androidx.wear, androidx.window, androidx.xr 같은 라이브러리들이 모두 이 구조에 기반을 두고 있습니다. 이 아키텍처를 이해하려면 먼저 Android SDK와 라이브러리와 관련된 몇 가지 과정을 살펴볼 필요가 있습니다.</p><h3>Android SDK</h3><p>Android 앱을 개발할 때 우리는 Android SDK를 사용합니다. 이 SDK는 android.jar 같은 도구와 라이브러리를 포함하고 있으며, 이는 Android 앱을 만들고 특정 시스템 구성요소와 상호작용할 수 있게 해주는 API를 정의합니다.</p><p>우리는 항상 Gradle 파일에서 compileSdk, targetSdk, minSdk를 정의합니다.</p><p>compileSdk는 앱을 빌드할 때 사용하는 Android SDK입니다. 새롭게 추가된 API를 사용하려면 최신 SDK가 필요합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7TTr6zVm0Ve_MyiWjw8QuQ.png" /><figcaption>this api can use since API 31</figcaption></figure><p>minSdk는 앱이 실행될 수 있는 최소 Android SDK 버전을 의미합니다.</p><p>이보다 이후에 도입된 API를 사용하면 런타임 오류가 발생할 수 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m_7K3v381TxyBHKI9OXxNw.png" /></figure><p>이러한 이유로 IDE는 보통 다음 중 하나를 제안합니다:</p><ul><li>애너테이션 추가</li><li>조건문으로 감싸기</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BK_HIe8qEPjUv7uzV6WytA.png" /></figure><p>Android SDK의 작동 방식을 이해하려면 Compile SDK와 Framework의 관계를 이해해야 합니다. 흔히 우리가 말하는 android SDK는 플랫폼이며 각 제조사는 이를 기반으로 바이너리를 개발합니다. 즉, 우리가 앱을 빌드하기 위해서 사용하는 Android SDK는 컴파일을 위해서만 사용 되며, 실제 동작은 바이너리내 Framework을 참조하여 동작하게 됩니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*8OobxiSgBDyI30AJO4Tn0g.png" /></figure><p>각 제조사가 개발한다면 Android SDK로 개발한 앱이 정상적인 동작을 보장할 수 없다고 생각할 수 있습니다. 그래서 모든 Android 기반 기기는 **Compatibility Test Suite (CTS)**를 통과해야 Android 이름을 사용할 수 있게 되며, 우리가 Android SDK로 앱을 빌드했을 때 모든 Android 기기에서 문제없이 작동하는 것을 기대할 수 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*CdI9jWQU2J8B_Zzu.png" /><figcaption><a href="https://source.android.com/docs/compatibility/cts?hl=en">Compatibility Test Suite (CTS)</a></figcaption></figure><p>안드로이드 플랫폼, Android 파트너 및 개발자 간의 관계를 아래와 같이 나타낼 수 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*unUvF5FMFDLEolm1M9A-0A.png" /></figure><p>이제 우리는 위 그림을 보고 어떻게 제조사 앱이 더 다양한 기능을 구현할 수 있는 지 알수 있게 되었습니다.</p><h3>Android Library</h3><p>Java 라이브러리(.jar)와는 달리, Android 라이브러리는 .aar 확장자를 사용합니다. .aar 파일은 .jar 파일보다 더 많은 정보를 담고 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/1*MB8FBIALjArmppwM4YrFFg.png" /></figure><p>AAR 파일들은 APK가 빌드 되는 시점에 합쳐집니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*R5-jLQurrsgBKuD7fmCgMA.png" /></figure><h4>Resources Merging</h4><p>앱 모듈의 리소스와 AAR 라이브러리의 리소스는 하나의 res 디렉토리로 병합됩니다.</p><p>동일한 이름의 리소스가 존재할 경우, 앱 모듈 쪽이 우선됩니다 (예: res/values/strings.xml)</p><p>AndroidManifest.xml 파일도 병합됩니다:</p><ul><li>앱 모듈의 매니페스트가 기본이 되며,</li><li>AAR 라이브러리의 매니페스트가 추가됩니다.</li><li>uses-permission, application, activity, provider 등 태그가 병합 대상입니다.</li></ul><p>Manifest를 합칠 때 충돌이 발생하면 경고나 오류가 발생할 수 있습니다.</p><h4>Res and Resoures.arsc</h4><p>APK에는 다음 두 가지 리소스 관련 파일이 포함됩니다:</p><ul><li>res/: 실제 이미지, 레이아웃, 문자열 등 리소스 파일을 포함</li><li>resources.arsc: 바이너리 파일로, 리소스 인덱스 및 메타데이터를 저장하여 런타임에서 효율적인 접근을 가능하게 함</li></ul><p>이 두 파일은 리소스를 저장 및 로딩하는 데 상호 보완적인 역할을 합니다.</p><h4>Code Compile &amp; Dexing</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*7FoZqBrsFrbjbfHUQ4_gDw.png" /></figure><p>AAR 내부의 classes.jar와 앱의 .class 파일은 함께 컴파일됩니다. 이후 D8 또는 R8을 통해 .dex(Dalvik Executable) 형식으로 변환됩니다. 상황에 따라서 dex 파일은 classes.dex, classes2.dex, … 등의 여러개 생성될 수 있습니다. R8을 사용할 경우 코드 난독화, 제거, 최적화도 함께 수행됩니다.</p><h4>Native Libraries Merging</h4><p>.so 파일(네이티브 라이브러리)도 APK에 병합됩니다.</p><h4>Asset Merging</h4><p>assets/ 디렉토리의 콘텐츠도 병합됩니다. AAR 라이브러리와 앱 모두의 에셋이 APK에 포함됩니다.</p><h3>Extensions Architecture</h3><p>이 구조는 androidx.window가 출시되며 처음 소개되었습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/0*4nBPw3jYNPxANzLG.png" /><figcaption><a href="https://source.android.com/docs/core/display/windowmanager-extensions?hl=en">WindowManager Extensions</a></figcaption></figure><p>이 구조는 동일한 심볼에 대해서 컴파일 타임과 런타임에 다른 라이브러리를 참조하도록 설계 되었습니다.</p><h4>&lt;uses-libarary&gt;</h4><p>AndroidManifest.xml에 선언되는 &lt;uses-library&gt; 태그는 특정 라이브러리를 명시적으로 포함시키기 위해 사용됩니다. 컴파일 타임에 라이브러리 API를 호출할 수 있게 하고, 런타임에 해당 라이브러리가 반드시 존재해야 함을 보장합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jq_aEdHcj0rABM-nyh-g3g.png" /></figure><h4><strong>Extensions Archicture Structure</strong></h4><p>이 태그를 사용하면 두 개의 라이브러리가 <strong>같은 심볼을 공유</strong>할 수 있습니다.컴파일 타임에는 <strong>stub(구현 없는 인터페이스)</strong> 라이브러리를 참조하고, 런타임에는 시스템 이미지 내의 <strong>구현 라이브러리</strong>를 참조합니다.</p><p>즉, 컴파일 타임과 런타임에 서로 다른 라이브러리를 사용하지만, 동일한 API 심볼을 유지할 수 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*89CT0jm8LAbacbbZu8uKbA.png" /></figure><h4>Advantages of the Extensions Archicture</h4><ul><li>Android SDK 자체를 수정하지 않고도 라이브러리만으로 <strong>기기 특화 기능</strong>을 지원할 수 있습니다.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*IYds1yx6_yv7_5FeNOlNxQ.png" /></figure><h4>Considerations for the Extensions Architecture</h4><p>이 아키텍처는 유용하지만 <strong>아주 엄격한 조건</strong>이 요구됩니다.</p><p><strong>1. 시스템 이미지와 심볼 일치</strong></p><p>시스템 이미지와 심볼이 정확히 일치해야 합니다.</p><p><strong>2. 런타임 오류 가능성</strong></p><p>컴파일 타임에는 stub만 검사하므로, 실제 구현 라이브러리가 잘못될 경우 컴파일 타임이 아닌 <strong>런타임에 오류가 발생</strong> 합니다.</p><p><strong>3. R8 엔진과의 충돌</strong></p><p>R8를 키면 난독화, 축소 등의 단계를 가지고 있습니다. 난독화가 적용 되면 심볼리 달라지기 때문에 런타임에 class를 찾을 수 없는 에러로 이어지게 됩니다. 또한 Consumer와 같이 impl에서 소비되는 코드에 대해서 컴파일 타임에 사용되지 않는 코드로 오인하여 이를 삭제하여 심볼이 변경되어 에러로 이어질 수 있습니다. 따라서 이를 방지하기 위해서는 proguard를 잘 정의 해야 합니다.</p><h4>그래서 어떻게 해야 할까?</h4><ul><li>확장 아키텍처는 <strong>직접 사용하기에는 위험</strong>하며,</li><li>일반적으로는 <strong>상위 레벨 라이브러리</strong>에서 래핑(wrapping)하여 제공합니다.</li><li>이 방식은 사용 전 디바이스의 기능을 체크하고, API 사용을 통제할 수 있어 안전합니다.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*79JvGt56XYi_BCquxSKtUw.png" /></figure><p><strong>Summary</strong></p><p>Android SDK와 AAR 를 시작으로 Extensions API에 대해서 살펴 보았습니다.</p><p>Extensions Architecture는 Android SDK를 수정하지 않고도 기기 특화 기능을 지원하기 위한 구조라는 것을 알 수 있습니다.</p><p>동일한 심볼에 대해서 컴파일 타임과 런타임에 서로 다른 JAR을 참조하도록 하여 이를 가능하게 만들었습니다.</p><p>아래는 이 구조가 작동하는 방식을 보여주는 전체 다이어그램입니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nkn5xjN1KayzDHrnJ3yiuw.png" /></figure><p>이 글이 확장 아키텍처에 대한 이해를 돕고, 위의 다이어그램을 보다 명확하게 이해하는 데 도움이 되었기를 바랍니다</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0a58b69b17da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Behind the Scenes of Android: SDKs, AARs, and the Extensions Architecture]]></title>
            <link>https://quokkaman.medium.com/behind-the-scenes-of-android-sdks-aars-and-the-extensions-architecture-052b0b4d61ca?source=rss-14e3cc4acf91------2</link>
            <guid isPermaLink="false">https://medium.com/p/052b0b4d61ca</guid>
            <category><![CDATA[extensions-architecture]]></category>
            <category><![CDATA[jetpack]]></category>
            <category><![CDATA[android-sdk]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[androidx]]></category>
            <dc:creator><![CDATA[Quokkaman]]></dc:creator>
            <pubDate>Fri, 25 Apr 2025 15:47:04 GMT</pubDate>
            <atom:updated>2025-04-25T16:22:57.211Z</atom:updated>
            <content:encoded><![CDATA[<h4>Understanding Android SDK, AAR, and the Extensions Architecture</h4><p>As Android developers, we’re used to compiling apps using the Android SDK, including AAR libraries, and generating APKs. But behind this seemingly straightforward process lies a complex system that connects compile-time abstractions with runtime implementations, dynamic class loading.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*a9f-AQ1a7Xs2CxfGyxXENQ.png" /></figure><p>To support a wider range of devices on the Android platform, Some android libaries are designed with an <a href="https://source.android.com/docs/core/display/windowmanager-extensions?hl=en">extension architecture</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nkn5xjN1KayzDHrnJ3yiuw.png" /><figcaption>I hope this post helped you clearly understand the structure illustrated in the diagram above.</figcaption></figure><p>The androidx.wear, androidx.window, and androidx.xr libraries are all designed based on this architecture. To understand this design, we first need to understand several processes involving the Android SDK and libraries.</p><h3><strong>Android SDK</strong></h3><p>When developing an Android app, we use the Android SDK. This SDK includes tools and libraries such as android.jar, which defines the APIs used to build Android apps and interact with certain system components.</p><p>We’ve always defined the compile SDK, target SDK, and min SDK at gradle file.</p><p>As the name implies, the compile SDK is the Android SDK used when building your app. Since every Android API has a minimum required compile SDK version, you need the latest SDK to use newly added APIs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7TTr6zVm0Ve_MyiWjw8QuQ.png" /><figcaption>this api can use since API 31</figcaption></figure><p>The minSDK defines the minimum Android SDK version your app can run on.</p><p>Using APIs introduced after this version may lead to runtime errors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m_7K3v381TxyBHKI9OXxNw.png" /></figure><p>So the IDE often suggests either adding a version-check annotation or wrapping the API call with an if (Build.VERSION.SDK_INT &gt;= …) statement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BK_HIe8qEPjUv7uzV6WytA.png" /></figure><p>To understand how the Android SDK works, we need to look at the relationship between the compile-time SDK and the runtime framework.</p><p>The Android SDK serves as an abstraction layer, and each device manufacturer builds a framework system image based on it.</p><p>So, our application uses the Android SDK only at compile time, but it actually relies on the system image at runtime.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*8OobxiSgBDyI30AJO4Tn0g.png" /></figure><p>We can’t be certain that the system image fully conforms to the Android SDK specifications.</p><p>Therefore, all devices released based on the Android platform must pass the Compatibility Test Suite (CTS).</p><p>This ensures that when you build your app with the Android SDK, it will function correctly across all Android devices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*CdI9jWQU2J8B_Zzu.png" /><figcaption><a href="https://source.android.com/docs/compatibility/cts?hl=en">Compatibility Test Suite (CTS)</a></figcaption></figure><p>The diagram below provides a more detailed diagram to help you better understand the relationship between AOSP, Android Partner, and developers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*unUvF5FMFDLEolm1M9A-0A.png" /></figure><p>Now, the diagram above helps explain why android partner can access more features than third-party apps.</p><h3><strong>Android Library</strong></h3><p>Unlike Java libraries (jar), Android libraries use the .aar extension.</p><p>As shown below, .aar files contain more information than .jar files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/1*MB8FBIALjArmppwM4YrFFg.png" /></figure><p>The components of the .aar file are merged when the application is built.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*R5-jLQurrsgBKuD7fmCgMA.png" /></figure><h4>Resources Merging</h4><p>The resources of the app module and the resources of the AAR are merged into a single res/ directory. In this process, the priority is given to the app module over the dependency modules. For example, if there are resources with the same name (e.g., res/values/strings.xml), the resources from the app module take precedence.</p><p>Additionally, all AndroidManifest.xml files are merged:</p><ul><li>The app module’s manifest is used as the base,</li><li>The manifest from the AAR library is merged,</li><li>Tags such as uses-permission, application, activity, and provider may be included.</li></ul><p>Merge conflicts may trigger warnings or errors.</p><h4>Res and Resoures.arsc</h4><p>In an APK, there are both /res and resources.arsc.</p><p><strong>The res directory</strong> stores the actual resource files, including images, layouts, strings, and other resources created by the developer.</p><p><strong>resources.arsc</strong> is a binary file that contains the index and metadata for these resources, helping the app manage them efficiently during runtime.</p><p>These two files complement each other in handling Android resources: one defines and stores the resources, while the other enables quick access and loading of those resource</p><h4>Code Compile &amp; Dexing</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*7FoZqBrsFrbjbfHUQ4_gDw.png" /></figure><p>The classes.jar (library class files) inside the AAR and the .class files of the app module are compiled together. Then, they are converted into the .dex (Dalvik Executable) format using D8 or R8. Finally, classes.dex (or classes2.dex, classes3.dex, etc.) files are generated.</p><p>If R8 is used, code obfuscation, removal, and optimization are also performed during this process.</p><h4>Native Libraries Merging</h4><p>The .so file, which is for native libraries, is also merged into the APK.</p><h4>Asset Merging</h4><p>The contents of the assets/ directory are also merged. The assets provided by the AAR library and the app’s assets are both included in the APK’s assets/ directory.</p><h3>Extensions Architecture</h3><p>The <strong>Extensions Architecture</strong> was introduced with the release of androidx.window.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/0*4nBPw3jYNPxANzLG.png" /><figcaption><a href="https://source.android.com/docs/core/display/windowmanager-extensions?hl=en">WindowManager Extensions</a></figcaption></figure><p>This structure is essentially designed to use different libraries between compile time and runtime while maintaining the same symbol.</p><h4>&lt;uses-libarary&gt;</h4><p>uses-library is a setting used in the Android AndroidManifest.xml file to explicitly include a specific library or module during the app’s compile time. It is primarily needed when the app calls APIs from a particular library and ensures that the library is present at runtime.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jq_aEdHcj0rABM-nyh-g3g.png" /></figure><p>By using this setting, the Android build system recognizes the need for the library and includes it during the compile process.</p><h4>Extensions Archicture Structure</h4><p>By using the &lt;uses-library&gt; tag, we can make two libraries share the same symbol stub and implementation. The stub is used only during compile time in the library, while the implementation is placed in the system image. This allows the symbol reference to differ between compile time and runtime, pointing to different libraries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*89CT0jm8LAbacbbZu8uKbA.png" /></figure><h4>Advantages of the Extensions Archicture</h4><p>This structure is designed to support device-specific features without <strong>modifying the Android SDK</strong>. With this, we can support many features using just libraries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*IYds1yx6_yv7_5FeNOlNxQ.png" /></figure><h4>Considerations for the Extensions Architecture</h4><p>The extensions architecture is a very useful and powerful tool, but in order for it to function as intended, there are a few key conditions that must be met. The most important of these is that the s<strong>ystem image and symbols must match</strong>. If this condition is not met, unexpected errors may occur at runtime, even if there are no issues during compile time. This architecture has the potential for side effects, which can affect the stability of Android apps.</p><p><strong>1. The Need for Matching System Image and Symbol</strong></p><p>The extension architecture works correctly when these system image and symbols are precisely aligned. If the app runs on a system with a different image than intended, the APIs may not function properly, leading to unexpected results.</p><p><strong>2. Potential for Runtime Errors</strong></p><p>At compile time, only the stub library is checked, and the compiler cannot verify the implementation library. Therefore, even if everything seems fine at compile time, a mismatch between the stub and implementation libraries can lead to issues at runtime.</p><p><strong>3. R8 Engine</strong></p><p>The R8 engine performs tasks like obfuscation and minification. When it detects extension stub APIs, issues can arise. If it obfuscates the extension API, the symbols may change, causing it to fail at runtime. Additionally, some APIs, like those that consume, are never called at compile time because the stub is just a stub. As a result, certain extension APIs may become targets for minification, leading to potential API mismatch issues.</p><h4>wrap with more abstraction library</h4><p>For these reasons, the extensions architecture library is hard to modification and can easily lead to exceptions, so it must be designed simply. However, with a simple API, it’s difficult to provide a good API. Therefore, the extensions library is generally not open for direct use by developers. Instead, it is wrapped in a higher-level library and provided this way. This approach makes it safer because we can check the device’s feature level at the higher level and control the usage of the extension API in a reserved manner, as we are the only consumers of the extensions API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*79JvGt56XYi_BCquxSKtUw.png" /></figure><p><strong>Summary</strong></p><p>To understand the Extensions API, we began by exploring the Android SDK and Android libraries.</p><p>Then, we learned about the Extensions Architecture, which is designed to support device-specific APIs through libraries without modifying the Android SDK.</p><p>This architecture works by referencing different JAR files at compile time and runtime while using the same symbols.</p><p>Below is an overall diagram showing how the Extensions Architecture works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nkn5xjN1KayzDHrnJ3yiuw.png" /></figure><p>I hope this post helped you understand what the Extensions Architecture is and made the diagram above clearer to you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=052b0b4d61ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Session and Entity in androidx.xr.scenecore — (2) impl and common]]></title>
            <link>https://quokkaman.medium.com/exploring-session-and-entity-in-androidx-xr-scenecore-2-impl-and-common-0030e0c4c850?source=rss-14e3cc4acf91------2</link>
            <guid isPermaLink="false">https://medium.com/p/0030e0c4c850</guid>
            <category><![CDATA[androidx]]></category>
            <category><![CDATA[jetpackxr]]></category>
            <category><![CDATA[jetpack]]></category>
            <category><![CDATA[android-xr]]></category>
            <dc:creator><![CDATA[Quokkaman]]></dc:creator>
            <pubDate>Thu, 17 Apr 2025 14:38:57 GMT</pubDate>
            <atom:updated>2025-04-17T14:38:57.940Z</atom:updated>
            <content:encoded><![CDATA[<h3>Exploring Session and Entity in androidx.xr.scenecore — (2) impl and common</h3><h4>By exploring andridx.xr.scnecore, let’s discover how Elevated UI is made possible</h4><p><a href="https://quokkaman.medium.com/exploring-entity-in-androidx-xr-scenecore-1-public-interface-d1e388d3de59">Exploring Entity in androidx.xr.scenecore — (1) public interface</a></p><h3>Subclasses of Entity (Impl)</h3><blockquote><em>There are additional entities in both the impl and common packages.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/261/1*KYTiAwEE3DbnTPnagYHHpg.png" /></figure><p>below is overview of entities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*64sSsfNTrQDLYYV5gWwVyQ.png" /></figure><p>{위 이미지에서 SubspaceNodeEntityImpl은 AnadroidXrEntity의 자식임 수정 필요}<br>BasePanelEntity의 Parent는 runtime내 에 있음</p><p>{여기서 부터는 gpt 번역이 필요함}</p><h3>impl vs common</h3><p>We noticed that some entities are located in the impl package, while others are in the common package. This made us start to question the reasoning behind this separation.</p><p>Simply put, this kind of separation is driven by high-level and low-level layering.</p><p>To better understand the distinction between impl and common, let’s take a look at BaseEntity and AndroidXrEntity.</p><p>BaseEntity.kt</p><pre>package androidx.xr.scenecore.common;<br><br>import android.util.Log;<br><br>import androidx.annotation.NonNull;<br>import androidx.annotation.Nullable;<br>import androidx.annotation.RestrictTo;<br>import androidx.xr.runtime.internal.Component;<br>import androidx.xr.runtime.internal.Entity;<br>import androidx.xr.runtime.internal.Space;<br>import androidx.xr.runtime.internal.SpaceValue;<br>import androidx.xr.runtime.math.Pose;<br>import androidx.xr.runtime.math.Vector3;<br><br>import java.util.ArrayList;<br>import java.util.List;<br><br>/** Implementation of a subset of core RealityCore Entity functionality. */<br>@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX)<br>public abstract class BaseEntity extends BaseActivityPose implements Entity {</pre><p>AndroidXrEntity</p><pre>package androidx.xr.scenecore.impl;<br><br>// ...<br>import androidx.xr.scenecore.common.BaseEntity;<br><br>import com.android.extensions.xr.XrExtensions;<br>import com.android.extensions.xr.function.Consumer;<br>import com.android.extensions.xr.node.InputEvent;<br>import com.android.extensions.xr.node.Node;<br>import com.android.extensions.xr.node.NodeTransaction;<br>import com.android.extensions.xr.node.ReformEvent;<br>import com.android.extensions.xr.node.ReformOptions;<br><br>import com.google.common.util.concurrent.ListenableFuture;<br><br>import java.util.Optional;<br>import java.util.concurrent.ConcurrentHashMap;<br>import java.util.concurrent.Executor;<br>import java.util.concurrent.ScheduledExecutorService;<br><br>/**<br> * Implementation of a JXR SceneCore Entity that wraps an android XR extension Node.<br> *<br> * &lt;p&gt;This should not be created on its own but should be inherited by objects that need to wrap an<br> * Android extension node.<br> */<br>@SuppressWarnings({&quot;BanSynchronizedMethods&quot;, &quot;BanConcurrentHashMap&quot;})<br>abstract class AndroidXrEntity extends BaseEntity implements Entity {</pre><p>Even by just looking at the import statements, we can identify the differences between them.</p><p>BaseEntity is a pure abstract class that relies on androidx.xr.runtime. In contrast, AndroidxXrEntity has additional dependencies, including com.android.extensions.xr. Although we’re not entirely sure what this is, the name AndroidxXrEntity gives us a clue.</p><p>So, let’s begin with the top-level classes and work our way down.</p><p><a href="https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:xr/scenecore/scenecore/src/main/java/androidx/xr/scenecore/common/BaseActivityPose.java">Common/BaseActivityPose.kt</a></p><p>It simply manages the responsibility related to positioning within an activity. From this, we can see that all entities are organized based on their association with activities.</p><pre>/**<br> * Base implementation of JXRCore ActivityPose.<br> *<br> * &lt;p&gt;A ActivityPose is an object that has a pose in the world space.<br> */<br>@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX)<br>public abstract class BaseActivityPose implements ActivityPose {<br>    @Override<br>    @NonNull<br>    public Pose getActivitySpacePose()<br><br>    /** Returns the pose for this entity, relative to the activity space root. */<br>    @NonNull<br>    public Pose getPoseInActivitySpace()<br><br>    @Override<br>    @NonNull<br>    public Vector3 getWorldSpaceScale()<br><br>    @Override<br>    @NonNull<br>    public Vector3 getActivitySpaceScale()<br><br>    @Override<br>    @NonNull<br>    public ListenableFuture&lt;HitTestResult&gt; hitTest(<br>            @NonNull Vector3 origin,<br>            @NonNull Vector3 direction,<br>            @HitTestFilterValue int hitTestFilter)<br><br>    @Override<br>    @NonNull<br>    public Pose transformPoseTo(@NonNull Pose pose, @NonNull ActivityPose destination)<br>}</pre><p><a href="https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:xr/scenecore/scenecore/src/main/java/androidx/xr/scenecore/common/BaseEntity.java;drc=c1f74175062cc2fe4e9c4c18413a0aa5b0629630">Common/BaseEntity.kt</a></p><p>BaseEntity contains a number of operations.</p><p><strong>Parent-child</strong></p><p>The first thing we notice is the API for managing the parent-child structure.</p><p>It’s clear that each entity can be part of a hierarchy, having both a parent and one or more children.</p><pre>/** Implementation of a subset of core RealityCore Entity functionality. */<br>@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX)<br>public abstract class BaseEntity extends BaseActivityPose implements Entity {<br>    private final List&lt;Entity&gt; mChildren = new ArrayList&lt;&gt;();<br>    private BaseEntity mParent;<br>    <br>    // ...<br><br>    protected void addChildInternal(@NonNull Entity child)<br><br>    protected void removeChildInternal(@NonNull Entity child)<br><br>    @Override<br>    public void addChild(@NonNull Entity child)<br><br>    @Override<br>    public void addChildren(@NonNull List&lt;? extends Entity&gt; mChildren)<br><br>    @Override<br>    @Nullable<br>    public Entity getParent()<br><br>    @Override<br>    public void setParent(@Nullable Entity parent)<br><br>    @Override<br>    @NonNull<br>    public List&lt;Entity&gt; getChildren()</pre><p><strong>Control API</strong></p><p>The following is an API designed for controlling entities in a way that’s similar to how views are managed. This approach feels very familiar to Android developers.</p><ul><li>pose</li><li>scale</li><li>contentDescription</li><li>isHidden</li></ul><pre>/** Implementation of a subset of core RealityCore Entity functionality. */<br>@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX)<br>public abstract class BaseEntity extends BaseActivityPose implements Entity {<br>    private Pose mPose = new Pose();<br>    private Vector3 mScale = new Vector3(1.0f, 1.0f, 1.0f);<br>    private float mAlpha = 1.0f;<br>    private boolean mHidden = false;<br><br>    @Override<br>    @NonNull<br>    public String getContentDescription()<br><br>    @Override<br>    public void setContentDescription(@NonNull String text)<br><br>    @Override<br>    @NonNull<br>    public Pose getPose(@SpaceValue int relativeTo)<br><br>    @Override<br>    public void setPose(@NonNull Pose pose, @SpaceValue int relativeTo)<br>    // ...<br><br>    @Override<br>    @NonNull<br>    public Vector3 getScale(@SpaceValue int relativeTo)<br><br>    @Override<br>    public void setScale(@NonNull Vector3 scale, @SpaceValue int relativeTo)<br><br>    // Purely sets the value of the scale.<br>    protected final void setScaleInternal(@NonNull Vector3 scale)<br><br>    @Override<br>    public float getAlpha(@SpaceValue int relativeTo)<br><br>    @Override<br>    public void setAlpha(float alpha, @SpaceValue int relativeTo)<br><br>    private float getActivitySpaceAlpha()<br><br>    @Override<br>    @NonNull<br>    public Vector3 getWorldSpaceScale()<br><br>    @Override<br>    @NonNull<br>    public Vector3 getActivitySpaceScale()<br><br>    @Override<br>    public boolean isHidden(boolean includeParents)<br><br>    @Override<br>    public void setHidden(boolean hidden)</pre><p>However, there are also some unconventional APIs, such as getActivitySpaceXX and getWorldSpaceXXX. These APIs are read-only and only provide getters, with no corresponding setters or modifiers.</p><p>Let’s take a closer look at how this API works.</p><pre>    @Override<br>    @NonNull<br>    public Vector3 getWorldSpaceScale() {<br>        if (mParent == null) {<br>            throw new IllegalStateException(&quot;Cannot get scale in WorldSpace with a null parent&quot;);<br>        }<br>        return mParent.getWorldSpaceScale().times(mScale);<br>    }<br><br>    @Override<br>    @NonNull<br>    public Vector3 getActivitySpaceScale() {<br>        if (mParent == null) {<br>            throw new IllegalStateException(&quot;Cannot get scale in ActivitySpace with a null parent&quot;);<br>        }<br>        return mParent.getActivitySpaceScale().times(mScale);<br>    }</pre><p>Now, it’s clearer than before — both WorldSpaceXXX and ActivitySpaceXXX retrieve values while considering inheritance effects. In other words, the actual value is influenced by the specific space in which it’s accessed.</p><p><strong>Dispose</strong></p><p>Interestingly, the BaseEntity class provides a dispose API. This suggests that some entities might be prone to memory leaks if not properly disposed of.</p><pre>/** Implementation of a subset of core RealityCore Entity functionality. */<br>@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX)<br>public abstract class BaseEntity extends BaseActivityPose implements Entity {<br><br>    @Override<br>    public void dispose() {<br>        // Create a copy to avoid concurrent modification issues since the children detach<br>        // themselves<br>        // from their parents as they are disposed.<br>        List&lt;Entity&gt; childrenToDispose = new ArrayList&lt;&gt;(mChildren);<br>        for (Entity child : childrenToDispose) {<br>            child.dispose();<br>        }<br>      }</pre><p><strong>Component API</strong></p><p>We haven’t covered the concept of Components yet, but we can already see that an Entity can have one or more Components attached dynamically. We’ll take a closer look at this when we explore Components in a future session.</p><pre>/** Implementation of a subset of core RealityCore Entity functionality. */<br>@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX)<br>public abstract class BaseEntity extends BaseActivityPose implements Entity {<br>    private final List&lt;Component&gt; mComponentList = new ArrayList&lt;&gt;();<br><br>    @Override<br>    public boolean addComponent(@NonNull Component component)<br><br>    @Override<br>    @NonNull<br>    public &lt;T extends Component&gt; List&lt;T&gt; getComponentsOfType(@NonNull Class&lt;? extends T&gt; type)<br><br>    @Override<br>    @NonNull<br>    public List&lt;Component&gt; getComponents()<br><br>    @Override<br>    public void removeComponent(@NonNull Component component)<br><br>    @Override<br>    public void removeAllComponents()<br>}</pre><h4><a href="https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:xr/scenecore/scenecore/src/main/java/androidx/xr/scenecore/impl/AndroidXrEntity.java;bpv=1;bpt=0">AndroidXrEntity</a></h4><p>Starting with AndroidXrEntity, there’s an additional dependency on the com.android.extensions.xr library.</p><p>The AndroidXrEntity is associated with the following classes.</p><ul><li>Node</li><li>XrExtensions</li><li>EntityManager</li><li>ScheduleExecutorService</li></ul><pre>abstract class AndroidXrEntity extends BaseEntity implements Entity {<br><br>    protected final Node mNode;<br>    protected final XrExtensions mExtensions;<br>    protected final ScheduledExecutorService mExecutor;<br><br>    private final EntityManager mEntityManager;<br>    private ReformOptions mReformOptions;<br><br>    AndroidXrEntity(<br>            Node node,<br>            XrExtensions extensions,<br>            EntityManager entityManager,<br>            ScheduledExecutorService executor) {<br>        mNode = node;<br>        mExtensions = extensions;<br>        mEntityManager = entityManager;<br>        mExecutor = executor;<br>        mEntityManager.setEntityForNode(node, (Entity) this);<br>    }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*jAsr9WkDUpPZI-WlfqqMkQ.png" /></figure><p>Most of the APIs eventually reference the NodeTransaction class from the XrExtensions library.</p><pre>    @Override<br>    public void setScale(@NonNull Vector3 scale, @SpaceValue int relativeTo) {<br>        super.setScale(scale, relativeTo);<br>        Vector3 localScale = super.getScale(Space.PARENT);<br>        try (NodeTransaction transaction = mExtensions.createNodeTransaction()) {<br>            transaction<br>                    .setScale(mNode, localScale.getX(), localScale.getY(), localScale.getZ())<br>                    .apply();<br>        }<br>    }</pre><p>We need to understand what exactly NodeTransaction in XrExtensions is.</p><p>For now, it’s enough to recognize that AndroidXrEntity delegates certain operations through a NodeTransaction.</p><h4><a href="https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:xr/scenecore/scenecore/src/main/java/androidx/xr/scenecore/impl/BasePanelEntity.java;bpv=1;bpt=0">BasePanelEntity</a></h4><p>Starting with BasePanelEntity, entities support a corner radius property, allowing for more refined control over their shape or layout.</p><pre><br>/** BasePanelEntity provides implementations of capabilities common to PanelEntities. */<br>abstract class BasePanelEntity extends AndroidXrEntity implements PanelEntity {<br>    private static final float DEFAULT_CORNER_RADIUS_DP = 32.0f;<br><br>    protected float getDefaultPixelDensity()<br><br>    @SuppressLint(&quot;ObsoleteSdkInt&quot;)<br>    @RequiresApi(34)<br>    protected float getDefaultCornerRadiusInMeters()<br><br>    @NonNull<br>    @Override<br>    @Deprecated<br>    public Vector3 getPixelDensity()<br><br>    @NonNull<br>    @Override<br>    public Dimensions getSize()<br><br>    @Override<br>    public void setSize(@NonNull Dimensions dimensions)<br><br>    @NonNull<br>    @Override<br>    public PixelDimensions getSizeInPixels()<br><br>    @Override<br>    public void setSizeInPixels(@NonNull PixelDimensions dimensions)<br><br>    @Override<br>    public void setCornerRadius(float value)<br><br>    // Sets just the value of the corner radius, without updating the node. This should be only be<br>    // used when constructing the entity so that the stored value is consistent with the value set<br>    // in<br>    // the node transaction.<br>    public void setCornerRadiusValue(float value)<br>    @Override<br>    public float getCornerRadius()<br>}</pre><p>There are many Entity implementations that are closely integrated with the xrExtensions API.</p><ul><li><a href="http://Exploring Session and Entity in androidx.xr.scenecore (1) By exploring andridx.xr.scnecore, let&#39;s discover how Elevated UI is made possible">PanelEntityImpl</a></li><li><a href="https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:xr/scenecore/scenecore/src/main/java/androidx/xr/scenecore/impl/ActivityPanelEntityImpl.java;bpv=1;bpt=0">ActivityPanelEntityImpl</a></li><li><a href="https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:xr/scenecore/scenecore/src/main/java/androidx/xr/scenecore/impl/AnchorEntityImpl.java;bpv=1;bpt=0">AnchorEntityImpl</a></li><li><a href="https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:xr/scenecore/scenecore/src/main/java/androidx/xr/scenecore/impl/GltfEntityImpl.java;bpv=1;bpt=0">GltfEntityImpl</a></li><li><a href="https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:xr/scenecore/scenecore/src/main/java/androidx/xr/scenecore/impl/MainPanelEntityImpl.java;bpv=1;bpt=0">MainPanelEntityImpl</a></li></ul><p>Each of these implementations defines its own responsibility for a specific feature and delegates the corresponding operations via NodeTransaction in XrExtensions.</p><p>In conclusion, an Entity serves as an inherent structure for abstracting certain NodeTransactions. It can be viewed as a higher-level API built on top of xr-extensions.</p><p>Before diving into the individual features of SceneCore, we’ll first take a deep dive into what xr-extensions are and how they are built.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0030e0c4c850" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Entity in androidx.xr.scenecore — (1) public interface]]></title>
            <link>https://quokkaman.medium.com/exploring-entity-in-androidx-xr-scenecore-1-public-interface-d1e388d3de59?source=rss-14e3cc4acf91------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1e388d3de59</guid>
            <category><![CDATA[android-xr]]></category>
            <category><![CDATA[jetpack]]></category>
            <category><![CDATA[xr]]></category>
            <category><![CDATA[jetpackxr]]></category>
            <dc:creator><![CDATA[Quokkaman]]></dc:creator>
            <pubDate>Thu, 17 Apr 2025 14:38:27 GMT</pubDate>
            <atom:updated>2025-04-17T14:38:27.228Z</atom:updated>
            <content:encoded><![CDATA[<h3>Exploring Entity in androidx.xr.scenecore — (1) public interface</h3><h4>By exploring andridx.xr.scnecore, let’s discover how Elevated UI is made possible</h4><p>Last time, we took a deep dive into androidx.xr.compose. We discovered that there are two types of SubspaceLayout and ElevatedPanel.</p><p><a href="https://quokkaman.medium.com/exploring-spatial-and-subspace-in-androidx-xr-compose-251c2088d76b">Exploring Spatial and Subspace in androidx.xr.compose</a></p><p>In ElevatedPanel, they utilize the Session and Panel entity from scenecore.</p><pre>/**<br> * This is the base panel underlying the implementations of SpatialElevation, SpatialPopup, and<br> * SpatialDialog. It allows creating a panel at a specific size and [Pose].<br> */<br>@Composable<br>internal fun ElevatedPanel(<br>    contentSize: IntSize,<br>    shape: SpatialShape = ElevatedPanelDefaults.shape,<br>    pose: Pose? = null,<br>    content: @Composable () -&gt; Unit,<br>) {<br>    val session = checkNotNull(LocalSession.current) { &quot;session must be initialized&quot; }<br>    val parentPanelEntity = LocalPanelEntity.current ?: session.mainPanelEntity<br>    val density = LocalDensity.current<br>    var panelEntity by remember { mutableStateOf&lt;PanelEntity?&gt;(null) }<br>    val meterSize = contentSize.toMeterSize(density)<br><br>    val view = rememberComposeView {<br>        CompositionLocalProvider(LocalPanelEntity provides panelEntity) {<br>            Box(Modifier.alpha(if (pose == null) 0.0f else 1.0f)) { content() }<br>        }<br>    }<br><br>    DisposableEffect(Unit) {<br>        panelEntity =<br>            session.createPanelEntity(<br>                view = view,<br>                surfaceDimensionsPx = meterSize.toCorePixelDimensions(density),<br>                dimensions = meterSize.toCoreMeterDimensions(),<br>                name = &quot;ElevatedPanel:${view.id}&quot;,<br>            )<br>        onDispose {<br>            panelEntity?.dispose()<br>            panelEntity = null<br>        }<br>    }<br><br>    LaunchedEffect(pose) {<br>        if (pose != null) {<br>            panelEntity?.setPose(pose)<br>        }<br>    }<br><br>    LaunchedEffect(contentSize) {<br>        val width = contentSize.width.toFloat()<br>        val height = contentSize.height.toFloat()<br><br>        panelEntity?.setSize(Dimensions(width = width, height = height, depth = 0f))<br>        if (shape is SpatialRoundedCornerShape) {<br>            panelEntity?.setCornerRadius(<br>                Meter.fromPixel(shape.computeCornerRadius(width, height, density), density).value<br>            )<br>        }<br>    }<br><br>    LaunchedEffect(parentPanelEntity) { panelEntity?.setParent(parentPanelEntity) }<br>}</pre><p>This time, we’ll explore androidx.scenecore to understand what Session and its entities are.</p><h3>androidx.scenecore packages</h3><p>Before diving into androidx.scenecore, let’s first take a look at the package structure of scenecore to get an overview of its architecture.</p><pre>├── extensions<br>│   ├── // ...<br>└── scenecore<br>    ├── ActivityPose.kt<br>    ├── AnchorPlacement.kt<br>    ├── Component.kt<br>    ├── CubeMapTexture.kt<br>    ├── Entity.kt<br>    ├── EntityManager.kt<br>    ├── ExrImage.kt<br>    ├── InputEvent.kt<br>    ├── InteractableComponent.kt<br>    ├── JxrPlatformAdapter.java<br>    ├── Model.kt<br>    ├── MovableComponent.kt<br>    ├── MoveEvent.kt<br>    ├── PermissionHelper.kt<br>    ├── PointSourceAttributes.kt<br>    ├── PointerCaptureComponent.kt<br>    ├── ResizableComponent.kt<br>    ├── ResizeEvent.kt<br>    ├── Session.kt<br>    ├── SessionExt.kt<br>    ├── SoundFieldAttributes.kt<br>    ├── SpatialAudioTrack.kt<br>    ├── SpatialCapabilities.kt<br>    ├── SpatialEnvironment.kt<br>    ├── SpatialMediaPlayer.kt<br>    ├── SpatialSoundPool.kt<br>    ├── SpatialUser.kt<br>    ├── SpatializerConstants.kt<br>    ├── Texture.kt<br>    ├── TextureSampler.kt<br>    ├── Types.kt<br>    ├── Utils.kt<br>    ├── WaterMaterial.kt<br>    ├── common<br>    │   ├── BaseActivityPose.java<br>    │   ├── BaseEntity.java<br>    │   └── package-info.java<br>    ├── impl<br>    │   ├── // ...<br>    └── package-info.java<br><br></pre><p>Let’s start with Entity, since I prefer exploring from the bottom up rather than top down to better understand things.</p><h3>Entity.kt</h3><p><a href="https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:/xr/scenecore/scenecore/src/main/java/androidx/xr/scenecore/Entity.kt">source</a></p><p>Entity is an interface that provides several APIs for control.</p><pre>@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX)<br>public interface Entity : ActivityPose {<br><br>    public fun setParent(parent: Entity?)<br>    public fun getParent(): Entity?<br>    public fun addChild(child: Entity)<br>    public fun setPose(pose: Pose, @SpaceValue relativeTo: Int = Space.PARENT)<br>    public fun setPose(pose: Pose): Unit = setPose(pose, Space.PARENT)<br>    public fun getPose(@SpaceValue relativeTo: Int = Space.PARENT): Pose<br>    public fun getPose(): Pose = getPose(Space.PARENT)<br>    public fun setScale(scale: Float, @SpaceValue relativeTo: Int = Space.PARENT)<br>    public fun setScale(scale: Float): Unit = setScale(scale, Space.PARENT)<br>    public fun getScale(@SpaceValue relativeTo: Int = Space.PARENT): Float<br>    public fun getScale(): Float = getScale(Space.PARENT)<br>    public fun setAlpha(alpha: Float, @SpaceValue relativeTo: Int = Space.PARENT)<br>    public fun setAlpha(alpha: Float): Unit = setAlpha(alpha, Space.PARENT)<br>    public fun getAlpha(@SpaceValue relativeTo: Int = Space.PARENT): Float<br>    public fun getAlpha(): Float = getAlpha(Space.PARENT)<br>    public fun setHidden(hidden: Boolean)<br>    public fun isHidden(includeParents: Boolean = true): Boolean<br><br>    public fun dispose()<br><br>    public fun setContentDescription(text: String)<br>    public fun addComponent(component: Component): Boolean<br>    public fun removeComponent(component: Component)<br>    public fun &lt;T : Component&gt; getComponentsOfType(type: Class&lt;out T&gt;): List&lt;T&gt;<br>    public fun getComponents(): List&lt;Component&gt;<br>    public fun removeAllComponents()<br>}</pre><p>It seems that Entity is capable of aggregating `Component` classes</p><p>Component are very simple interface that can attach to entity or detach.</p><pre>/**<br> * Base interface for all components.<br> *<br> * Components are attached to entities, to add functionality to those entities.<br> */<br>@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX)<br>public interface Component {<br>    /**<br>     * Called when this component is attached to the entity.<br>     *<br>     * @param entity Entity this component is being attached to.<br>     * @return True if the component can attach to given Entity.<br>     */<br>    public fun onAttach(entity: Entity): Boolean<br><br>    /**<br>     * Called when this component is detached from the entity.<br>     *<br>     * @param entity Entity this component is being detached from.<br>     */<br>    public fun onDetach(entity: Entity)<br>}</pre><p>To better understand the Entity and Component classes, let’s search for all of their subclasses.</p><p>If you’d like to start with the official documentation, here it is: <a href="https://developer.android.com/develop/xr/jetpack-xr-sdk/work-with-entities?hl=ko">link</a></p><h3>Subclasses of Entity</h3><p>Entities are built using inheritance, and this structure feels very familiar. It’s easy to see that BaseEntity handles common logic, while each subclass has its own specific responsibility.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*F3jf937EyAf9Dz9Q_04r0A.png" /></figure><p>Let’s take a deeper dive into PanelEntity, since this is the part we’re most interested in.</p><h4><a href="https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:xr/scenecore/scenecore/src/main/java/androidx/xr/scenecore/PanelEntity.kt">PanelEntity</a></h4><pre>/** PanelEntity creates a spatial panel in Android XR. */<br>public open class PanelEntity</pre><p>We can see that this is intended for spatial panels in Android XR. A spatial panel is an elevated UI that floats separately from the main panel in an immersive environment.</p><pre>public companion object {<br>    internal fun create(<br>        context: Context,<br>        adapter: JxrPlatformAdapter,<br>        entityManager: EntityManager,<br>        view: View,<br>        dimensions: Dimensions,<br>        name: String,<br>        pose: Pose = Pose.Identity,<br>    ): PanelEntity =<br>        PanelEntity(<br>            adapter.createPanelEntity(<br>                context,<br>                pose,<br>                view,<br>                dimensions.toRtDimensions(),<br>                name,<br>                adapter.activitySpaceRootImpl,<br>            ),<br>            entityManager,<br>        )<br>   // ...</pre><p>PanelEntity doesn’t define any operations, but it does provide static factory methods.</p><p>When creating a Panel, it calls the JxrPlatformAdapter::createPanelEntity API. This suggests that certain features are defined in rtEntiy, which is of type JxrPlatformAdapter.PanelEntity. But before dicing deeper into Entity, we should finish exploring the subclasses of Entities.</p><pre>adapter.createPanelEntity(<br>    context,<br>    pose,<br>    view,<br>    dimensions.toRtDimensions(),<br>    name,<br>    adapter.activitySpaceRootImpl,<br>),</pre><p>Inside the adapter’s create API, we can tell that PanelEntity is tied to a View because view instance is injected along with some classes that appears to handle position and dimensions.</p><p>Hence, we can understand that PanelEntity is used to elevate an Android View within an immersive environment.</p><p>The other entities also follow a similar structure, delegating their behavior to the Jxr Adapter. However, diving deep into the JxrAdapter is too complex for now, so this time, we’ll take a look at what kinds of parameters are passed into the JxrAdapter APIs.</p><h4><a href="https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:xr/scenecore/scenecore/src/main/java/androidx/xr/scenecore/ActivityPanelEntity.kt"><strong>ActivityPanelEntity</strong></a></h4><pre>/**<br> * Factory method for ActivityPanelEntity.<br> *<br> * @param adapter JxrPlatformAdapter to use.<br> * @param windowBoundsPx Bounds for the underlying surface for the given view.<br> * @param name Name of this panel.<br> * @param hostActivity Activity which created this panel.<br> * @param pose Pose for this panel, relative to its parent.<br> */<br>internal fun create(<br>    adapter: JxrPlatformAdapter,<br>    entityManager: EntityManager,<br>    windowBoundsPx: PixelDimensions,<br>    name: String,<br>    hostActivity: Activity,<br>    pose: Pose = Pose.Identity,<br>): ActivityPanelEntity =<br>    ActivityPanelEntity(<br>        adapter.createActivityPanelEntity(<br>            pose,<br>            windowBoundsPx.toRtPixelDimensions(),<br>            name,<br>            hostActivity,<br>            adapter.activitySpaceRootImpl,<br>        ),<br>        entityManager,<br>    )</pre><p>ActivityPanelEntity is created using an Activity instead of a View.</p><h4><a href="https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:xr/scenecore/scenecore/src/main/java/androidx/xr/scenecore/AnchorEntity.kt">AnchorEntity</a></h4><pre>/**<br> * Factory method for AnchorEntity.<br> *<br> * @param adapter JxrPlatformAdapter to use.<br> * @param bounds Bounds for this Anchor Entity.<br> * @param planeType Orientation for the plane to which this Anchor should attach.<br> * @param planeSemantic Semantics for the plane to which this Anchor should attach.<br> * @param timeout Maximum time to search for the anchor, if a suitable plane is not found<br> *   within the timeout time the AnchorEntity state will be set to TIMED_OUT.<br> */<br>internal fun create(<br>    adapter: JxrPlatformAdapter,<br>    entityManager: EntityManager,<br>    bounds: Dimensions,<br>    planeType: @PlaneTypeValue Int,<br>    planeSemantic: @PlaneSemanticValue Int,<br>    timeout: Duration = Duration.ZERO,<br>): AnchorEntity {<br>    val rtAnchorEntity =<br>        adapter.createAnchorEntity(<br>            bounds.toRtDimensions(),<br>            planeType.toRtPlaneType(),<br>            planeSemantic.toRtPlaneSemantic(),<br>            timeout,<br>        )<br>    return create(rtAnchorEntity, entityManager)<br>}</pre><p>AnchorEntity has properties like bounds , planeType, and semantic. To fully understand what an anchor is, we’ll need to take a deeper look later.</p><h4><a href="https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:xr/scenecore/scenecore/src/main/java/androidx/xr/scenecore/ContentlessEntity.kt;bpv=1;bpt=0">ContentlessEntity</a></h4><pre>/** Factory method to create ContentlessEntity entities. */<br>internal fun create(<br>    adapter: JxrPlatformAdapter,<br>    entityManager: EntityManager,<br>    name: String,<br>    pose: Pose = Pose.Identity,<br>): Entity =<br>    ContentlessEntity(<br>        adapter.createEntity(pose, name, adapter.activitySpaceRootImpl),<br>        entityManager,<br>    )</pre><p>This is create with just a name and position. What is it used for?</p><pre>/**<br> * An Entity that itself has no content. ContentlessEntity is useful for organizing the placement,<br> * movement of a group of SceneCore Entities.<br> */<br>@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX)<br>public class ContentlessEntity</pre><p>There is some checking logic in CoreEntity of androidx.xr.compose. it seems to be intended as an extension point for androidx.xr.compose.</p><h4><a href="https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:xr/compose/compose/src/main/kotlin/androidx/xr/compose/subspace/layout/CoreEntity.kt;l=150;bpv=1?q=ContentlessEntity&amp;sq=&amp;ss=androidx%2Fplatform%2Fframeworks%2Fsupport">CoreEntity</a></h4><pre>/** Wrapper class for contentless entities from SceneCore. */<br>@PublishedApi<br>internal class CoreContentlessEntity(entity: Entity) : CoreEntity(entity) {<br>    init {<br>        require(entity is ContentlessEntity) {<br>            &quot;Entity passed to CoreContentlessEntity should be a ContentlessEntity.&quot;<br>        }<br>    }<br>}</pre><blockquote>Oh. i. didn’t know there were more entities in androidx.compoe. For now, I’ll focus only on the entities in scenecore.</blockquote><h4><a href="https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:xr/scenecore/scenecore/src/main/java/androidx/xr/scenecore/GltfModelEntity.kt;bpv=1;bpt=0">GltfModelEntity</a></h4><pre>/**<br> * Factory method for GltfModelEntity.<br> *<br> * @param adapter Jetpack XR platform adapter.<br> * @param model [GltfModel] which this entity will display.<br> * @param pose Pose for this [GltfModelEntity], relative to its parent.<br> */<br>internal fun create(<br>    adapter: JxrPlatformAdapter,<br>    entityManager: EntityManager,<br>    model: GltfModel,<br>    pose: Pose = Pose.Identity,<br>): GltfModelEntity =<br>    GltfModelEntity(<br>        adapter.createGltfEntity(pose, model.model, adapter.activitySpaceRootImpl),<br>        entityManager,<br>    )</pre><p>GLTF (GL Tansmission Format) is a standard format for 3D objects. So, we can tell that this is used for rendering 3D objects in androidx.xr, and that their positions can be adjusted.</p><h4><a href="https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:xr/scenecore/scenecore/src/main/java/androidx/xr/scenecore/SurfaceEntity.kt;bpv=1;bpt=0">SurfaceEntity</a></h4><pre>/**<br> * Factory method for SurfaceEntity.<br> *<br> * @param adapter JxrPlatformAdapter to use.<br> * @param entityManager A SceneCore EntityManager<br> * @param stereoMode An [Int] which defines how surface subregions map to eyes<br> * @param pose Pose for this StereoSurface entity, relative to its parent.<br> * @param canvasShape The [CanvasShape] which describes the spatialized shape of the canvas.<br> */<br>internal fun create(<br>    adapter: JxrPlatformAdapter,<br>    entityManager: EntityManager,<br>    stereoMode: Int = StereoMode.SIDE_BY_SIDE,<br>    pose: Pose = Pose.Identity,<br>    canvasShape: CanvasShape = CanvasShape.Quad(1.0f, 1.0f),<br>): SurfaceEntity {<br>    val rtCanvasShape =<br>        when (canvasShape) {<br>            is CanvasShape.Quad -&gt;<br>                JxrPlatformAdapter.SurfaceEntity.CanvasShape.Quad(<br>                    canvasShape.width,<br>                    canvasShape.height<br>                )<br>            is CanvasShape.Vr360Sphere -&gt;<br>                JxrPlatformAdapter.SurfaceEntity.CanvasShape.Vr360Sphere(canvasShape.radius)<br>            is CanvasShape.Vr180Hemisphere -&gt;<br>                JxrPlatformAdapter.SurfaceEntity.CanvasShape.Vr180Hemisphere(<br>                    canvasShape.radius<br>                )<br>            else -&gt; throw IllegalArgumentException(&quot;Unsupported canvas shape: $canvasShape&quot;)<br>        }<br>    return SurfaceEntity(<br>        adapter.createSurfaceEntity(<br>            getRtStereoMode(stereoMode),<br>            rtCanvasShape,<br>            pose,<br>            adapter.activitySpaceRootImpl,<br>        ),<br>        entityManager,<br>        canvasShape,<br>    )<br>}</pre><p>The creation of SurfaceEntity is a bit complex, and we can only guess its behavior from the comments.</p><pre>/**<br> * SurfaceEntity is a concrete implementation of Entity that hosts a StereoSurface Canvas. The<br> * entity creates and owns an Android Surface into which the application can render stereo image<br> * content. This Surface is then texture mapped to the canvas, and if a stereoscopic StereoMode is<br> * specified, then the User will see left and right eye content mapped to the appropriate display.<br> *<br> * Note that it is not currently possible to synchronize CanvasShape and StereoMode changes with<br> * application rendering or video decoding. Applications are advised to carefully hide this entity<br> * around transitions to manage glitchiness.<br> *<br> * @property canvasShape The [CanvasShape] which describes the mesh to which the Surface is mapped.<br> * @property stereoMode The [StereoMode] which describes how parts of the surface are displayed to<br> *   the user&#39;s eyes.<br> * @property dimensions The dimensions of the canvas in the local spatial coordinate system of the<br> *   entity.<br> */<br>@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX)<br>public class SurfaceEntity</pre><p>It seems that SurfaceEntity supports some kind of StereoSurfaceCanvas.</p><p>We want to understand what an Entity really is, but most of its behavior is delegated to the JxrPlatformAdapter APIs. JxrPlatformAdapter is just an interface, and its implementation can be found in the impl packages, where there are also many additional entities.</p><p>This time, I’ll dig into what JxrPlatformAdapter is and explore the implmentation classes of the entiteis</p><h3>What is JxrPlatformAdapter?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*jvYdsWYOUC8IF8n__H-twQ.png" /></figure><p>JxrPlatformAdapter is an interface, and JxrPlatformAdapterAxr is its implementation class.</p><p>This implementation class is created by the Session.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oSrzkKBH5HxajQr9tUd7pw.png" /></figure><p><a href="https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:xr/scenecore/scenecore/src/main/java/androidx/xr/scenecore/Session.kt;bpv=1;bpt=0">Session.kt</a></p><pre>@JvmStatic<br>@JvmOverloads<br>public fun create(<br>    activity: Activity,<br>    platformAdapter: JxrPlatformAdapter? = null<br>): Session {<br>    return activitySessionMap.computeIfAbsent(activity) {<br>        Log.i(TAG, &quot;Creating session for activity $activity&quot;)<br>        val session =<br>            when (platformAdapter) {<br>                null -&gt; {<br>                    val platformAdapterImpl =<br>                        JxrPlatformAdapterAxr.create(<br>                            activity,<br>                            Executors.newSingleThreadScheduledExecutor(<br>                                object : ThreadFactory {<br>                                    override fun newThread(r: Runnable): Thread {<br>                                        return Thread(r, &quot;JXRCoreSession&quot;)<br>                                    }<br>                                }<br>                            ),<br>                        )<br>                    Session(<br>                        activity,<br>                        platformAdapterImpl,<br>                        SpatialEnvironment(platformAdapterImpl)<br>                    )<br>                }<br>                else -&gt;<br>                    Session(activity, platformAdapter, SpatialEnvironment(platformAdapter))<br>            }</pre><p>JxrPlatformAdapter is also created using a static factory method. After the instance is created, there’s an additional step to initialize the perceptionLibray.</p><pre>static JxrPlatformAdapterAxr create(<br>        @NonNull Activity activity,<br>        @NonNull ScheduledExecutorService executor,<br>        @NonNull XrExtensions extensions,<br>        @Nullable ImpressApi impressApi,<br>        @NonNull EntityManager entityManager,<br>        @NonNull PerceptionLibrary perceptionLibrary,<br>        @Nullable SplitEngineSubspaceManager splitEngineSubspaceManager,<br>        @Nullable ImpSplitEngineRenderer splitEngineRenderer,<br>        @NonNull Node rootSceneNode,<br>        @NonNull Node taskWindowLeashNode,<br>        boolean useSplitEngine) {<br>    JxrPlatformAdapterAxr runtime =<br>            new JxrPlatformAdapterAxr(<br>                    activity,<br>                    executor,<br>                    extensions,<br>                    impressApi,<br>                    entityManager,<br>                    perceptionLibrary,<br>                    splitEngineSubspaceManager,<br>                    splitEngineRenderer,<br>                    rootSceneNode,<br>                    taskWindowLeashNode,<br>                    useSplitEngine);<br><br>    Log.i(TAG, &quot;Initing perception library soon&quot;);<br>    runtime.initPerceptionLibrary();<br>    return runtime;<br>}</pre><blockquote>What is the perception library?,</blockquote><p>From the code below, we can tell that the perception library is a native library.</p><pre>@SuppressWarnings(&quot;VisiblySynchronized&quot;)<br>protected static synchronized void loadLibraryAsync(@NonNull String nativeLibraryName) {<br>    if (sLibraryLoaded) {<br>        return;<br>    }<br>    Log.i(TAG, &quot;Loading native library: &quot; + nativeLibraryName);<br>    try {<br>        System.loadLibrary(nativeLibraryName);<br>    } catch (UnsatisfiedLinkError e) {<br>        Log.e(TAG, &quot;Unable to load &quot; + nativeLibraryName);<br>        return;<br>    }<br>    sLibraryLoaded = true;<br>}</pre><p>Going back to the constructor of JxrAdapter, we can see that several instances are being initialized there.</p><pre>private JxrPlatformAdapterAxr(<br>        Activity activity,<br>        ScheduledExecutorService executor,<br>        XrExtensions extensions,<br>        @Nullable ImpressApi impressApi,<br>        EntityManager entityManager,<br>        PerceptionLibrary perceptionLibrary,<br>        @Nullable SplitEngineSubspaceManager subspaceManager,<br>        @Nullable ImpSplitEngineRenderer renderer,<br>        Node rootSceneNode,<br>        Node taskWindowLeashNode,<br>        boolean useSplitEngine) {<br>    mActivity = activity;<br>    mExecutor = executor;<br>    mExtensions = extensions;<br><br>    mLazySpatialStateProvider =<br>            () -&gt;<br>                    mSpatialState.updateAndGet(<br>                            oldSpatialState -&gt; {<br>                                if (oldSpatialState == null) {<br>                                    oldSpatialState = mExtensions.getSpatialState(activity);<br>                                }<br>                                return oldSpatialState;<br>                            });<br>    setSpatialStateCallback();<br><br>    mSoundPoolExtensionsWrapper =<br>            new SoundPoolExtensionsWrapperImpl(<br>                    extensions.getXrSpatialAudioExtensions().getSoundPoolExtensions());<br>    mAudioTrackExtensionsWrapper =<br>            new AudioTrackExtensionsWrapperImpl(<br>                    extensions.getXrSpatialAudioExtensions().getAudioTrackExtensions(),<br>                    entityManager);<br>    mMediaPlayerExtensionsWrapper =<br>            new MediaPlayerExtensionsWrapperImpl(<br>                    extensions.getXrSpatialAudioExtensions().getMediaPlayerExtensions());<br>    mEntityManager = entityManager;<br>    mPerceptionLibrary = perceptionLibrary;<br>    mTaskWindowLeashNode = taskWindowLeashNode;<br>    mNullSkyboxResourceFuture = loadExrImageByAssetName(&quot;images/black_skybox.exr&quot;);<br>    mEnvironment =<br>            new SpatialEnvironmentImpl(<br>                    activity,<br>                    extensions,<br>                    rootSceneNode,<br>                    mLazySpatialStateProvider,<br>                    mNullSkyboxResourceFuture,<br>                    useSplitEngine);<br>    mActivitySpace =<br>            new ActivitySpaceImpl(<br>                    rootSceneNode,<br>                    extensions,<br>                    entityManager,<br>                    mLazySpatialStateProvider,<br>                    executor);<br>    mEntityManager.addSystemSpaceActivityPose(mActivitySpace);<br>    mHeadActivityPose =<br>            new HeadActivityPoseImpl(<br>                    mActivitySpace,<br>                    (AndroidXrEntity) getActivitySpaceRootImpl(),<br>                    perceptionLibrary);<br>    mEntityManager.addSystemSpaceActivityPose(mHeadActivityPose);<br>    mPerceptionSpaceActivityPose =<br>            new PerceptionSpaceActivityPoseImpl(<br>                    mActivitySpace, (AndroidXrEntity) getActivitySpaceRootImpl());<br>    mEntityManager.addSystemSpaceActivityPose(mPerceptionSpaceActivityPose);<br>    mCameraActivityPoses.add(<br>            new CameraViewActivityPoseImpl(<br>                    CameraViewActivityPose.CAMERA_TYPE_LEFT_EYE,<br>                    mActivitySpace,<br>                    (AndroidXrEntity) getActivitySpaceRootImpl(),<br>                    perceptionLibrary));<br>    mCameraActivityPoses.add(<br>            new CameraViewActivityPoseImpl(<br>                    CameraViewActivityPose.CAMERA_TYPE_RIGHT_EYE,<br>                    mActivitySpace,<br>                    (AndroidXrEntity) getActivitySpaceRootImpl(),<br>                    perceptionLibrary));<br>    mCameraActivityPoses.forEach(mEntityManager::addSystemSpaceActivityPose);<br>    mUseSplitEngine = useSplitEngine;<br>    mOpenXrReferenceSpaceType = extensions.getOpenXrWorldSpaceType();<br><br>    mMainPanelEntity =<br>            new MainPanelEntityImpl(<br>                    activity, taskWindowLeashNode, extensions, entityManager, executor);<br>    mMainPanelEntity.setParent(mActivitySpace);<br><br>    // TODO:b/377918731 - Move this logic into factories and inject SE into the constructor<br>    if (impressApi == null) {<br>        // TODO: b/370116937) - Check against useSplitEngine as well and don&#39;t load this if<br>        //                      SplitEngine is disabled.<br>        mImpressApi = new ImpressApiImpl();<br>    } else {<br>        mImpressApi = impressApi;<br>    }<br><br>    if (useSplitEngine &amp;&amp; subspaceManager == null &amp;&amp; renderer == null) {<br>        ImpSplitEngine.SplitEngineSetupParams impApiSetupParams =<br>                new ImpSplitEngine.SplitEngineSetupParams();<br>        impApiSetupParams.jniLibraryName = SPLIT_ENGINE_LIBRARY_NAME;<br>        mSplitEngineRenderer = ImpSplitEngineRenderer.create(activity, impApiSetupParams);<br>        startRenderer();<br>        mSplitEngineSubspaceManager =<br>                new SplitEngineSubspaceManager(<br>                        mSplitEngineRenderer,<br>                        rootSceneNode,<br>                        taskWindowLeashNode,<br>                        SPLIT_ENGINE_LIBRARY_NAME);<br>        mImpressApi.setup(mSplitEngineRenderer.getView());<br>        mEnvironment.onSplitEngineReady(mSplitEngineSubspaceManager, mImpressApi);<br>    }<br>}</pre><p>While we can’t tell exactly what each part does, it’s clear that these are initialization tasks to support XR functionality.</p><blockquote>To fully understand the above, we need to explore what XrExtensions is and how it works. Since it’s also big part of Jetpack XR, I’ll dive into it next tie in a separate post.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1e388d3de59" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Spatial and Subspace in androidx.xr.compose]]></title>
            <link>https://quokkaman.medium.com/exploring-spatial-and-subspace-in-androidx-xr-compose-251c2088d76b?source=rss-14e3cc4acf91------2</link>
            <guid isPermaLink="false">https://medium.com/p/251c2088d76b</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-xr]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[jetpack]]></category>
            <category><![CDATA[androidx]]></category>
            <dc:creator><![CDATA[Quokkaman]]></dc:creator>
            <pubDate>Sun, 12 Jan 2025 05:02:04 GMT</pubDate>
            <atom:updated>2025-03-18T14:34:28.688Z</atom:updated>
            <content:encoded><![CDATA[<h4>By exploring andridx.xr.compose, let’s discover how Elevated UI is made possible</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*oajxWwv0UQ-S_chKDGqPAw.png" /></figure><p>Previously, we took a look at the Android XR Sample and learned how to work with Jetpack XR library. We discovered that Jetpack XR introduces new concepts like Subspace, SpatialRow, SpatialColumn, SpatialPanel and Orbiter. This time, i’ll deep dive into these concepts, exploring what Subspace is and how it’s implemented as an elevated UI.</p><p><a href="https://quokkaman.medium.com/exploring-the-android-xr-samples-86b7d4fb3711">Exploring the Android XR Samples</a></p><p>androidx.xr.compose’s source code is <a href="https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:xr/compose/compose/src/main/kotlin/androidx/xr/compose/"><strong>here</strong></a><strong>.</strong></p><p>First, let’s take a look at the package structure of androidx.xr.compose</p><pre>├── platform<br>│   ├── Activity.kt<br>│   ├── AndroidComposeSpatialElement.kt<br>│   ├── CompositionLocals.kt<br>│   ├── DialogManager.kt<br>│   ├── GlobalSnapshotManager.kt<br>│   ├── InternalSubspaceApi.kt<br>│   ├── LocalPanelEntity.kt<br>│   ├── LocalSession.kt<br>│   ├── Logger.kt<br>│   ├── SceneManager.kt<br>│   ├── SessionCallbackProvider.kt<br>│   ├── SpatialCapabilities.kt<br>│   ├── SpatialComposeElement.kt<br>│   ├── SpatialComposeScene.kt<br>│   ├── SpatialConfiguration.kt<br>│   ├── SpatialElement.kt<br>│   ├── SubspaceRecomposer.kt<br>│   └── WrappedComposition.kt<br>├── spatial<br>│   ├── ConstrainToModifier.kt<br>│   ├── ElevatedPanel.kt<br>│   ├── Orbiter.kt<br>│   ├── OutsideInputHandler.kt<br>│   ├── RememberCalculatePose.kt<br>│   ├── SpatialDialog.kt<br>│   ├── SpatialElevation.kt<br>│   ├── SpatialElevationLevel.kt<br>│   ├── SpatialPopup.kt<br>│   └── Subspace.kt<br>├── subspace<br>│   ├── RememberComposeView.kt<br>│   ├── RememberCoreEntity.kt<br>│   ├── RowColumnImpl.kt<br>│   ├── RowColumnMeasurePolicy.kt<br>│   ├── SpatialBox.kt<br>│   ├── SpatialColumn.kt<br>│   ├── SpatialLayoutSpacer.kt<br>│   ├── SpatialPanel.kt<br>│   ├── SpatialRow.kt<br>│   ├── SubspaceComposable.kt<br>│   ├── Volume.kt<br>│   ├── layout<br>│   │   ├── Alpha.kt<br>│   │   ├── CoreEntity.kt<br>│   │   ├── MathExt.kt<br>│   │   ├── Measurable.kt<br>│   │   ├── MeasurePolicy.kt<br>│   │   ├── MeasureResult.kt<br>│   │   ├── MeasureScope.kt<br>│   │   ├── Movable.kt<br>│   │   ├── Offset.kt<br>│   │   ├── OnGloballyPositionedModifier.kt<br>│   │   ├── Padding.kt<br>│   │   ├── ParentLayoutParamsModifier.kt<br>│   │   ├── Placeable.kt<br>│   │   ├── Resizable.kt<br>│   │   ├── Rotate.kt<br>│   │   ├── Scale.kt<br>│   │   ├── SemanticsModifier.kt<br>│   │   ├── Size.kt<br>│   │   ├── SpatialAlignment.kt<br>│   │   ├── SpatialShape.kt<br>│   │   ├── SubspaceLayout.kt<br>│   │   ├── SubspaceLayoutCoordinates.kt<br>│   │   ├── SubspaceModifier.kt<br>│   │   ├── SubspaceRootMeasurePolicy.kt<br>│   │   └── TestTag.kt<br>│   └── node<br>│       ├── ComposeSubspaceNode.kt<br>│       ├── SubspaceLayoutModifierNode.kt<br>│       ├── SubspaceLayoutModifierNodeCoordinator.kt<br>│       ├── SubspaceLayoutNode.kt<br>│       ├── SubspaceModifierElement.kt<br>│       ├── SubspaceModifierNodeChain.kt<br>│       ├── SubspaceNodeApplier.kt<br>│       ├── SubspaceOwner.kt<br>│       ├── SubspaceSemanticsModifierNode.kt<br>│       └── SubspaceSemanticsNode.kt<br>└── unit<br>    ├── CoreConversions.kt<br>    ├── DpVolumeSize.kt<br>    ├── IntVolumeSize.kt<br>    ├── Meter.kt<br>    └── VolumeConstraints.kt</pre><p>SpatialRow, SpatialColumn and SpatialPanel belongs to the subspace package, while Orbiter is part of spatial package. This distinction represents the existence of two different types of spatial api.</p><p>If we compare SpatialPanel and Orbiter, It’s easy to see that subspace package is intended for SubSpaceComposable, while the spatial package does not require SubspaceComposable.</p><pre>/**<br> * Creates a [SpatialPanel] representing a 2D plane in 3D space in which an application can fill<br> * content.<br> *<br> * @param view Content view to be displayed within the SpatialPanel.<br> * @param modifier SubspaceModifiers to apply to the SpatialPanel.<br> * @param name A name for the SpatialPanel, useful for debugging.<br> * @param shape The shape of this Spatial Panel.<br> */<br>@Composable<br>@SubspaceComposable<br>@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX)<br>public fun SpatialPanel(<br>    view: View,<br>    modifier: SubspaceModifier = SubspaceModifier,<br>    name: String = defaultSpatialPanelName(),<br>    shape: SpatialShape = SpatialPanelDefaults.shape,<br>) {<br>    SpatialPanel(modifier, name, view, shape) {}<br>}</pre><pre>/**<br> * A composable that creates an orbiter along the top or bottom edges of a view.<br> *<br> * @param position The edge of the orbiter. Use [OrbiterEdge.Top] or [OrbiterEdge.Bottom].<br> * @param offset The offset of the orbiter based on the outer edge of the orbiter.<br> * @param alignment The alignment of the orbiter. Use [Alignment.CenterHorizontally] or<br> *   [Alignment.Start] or [Alignment.End].<br> * @param settings The settings for the orbiter.<br> * @param shape The shape of this Orbiter when it is rendered in 3D space.<br> * @param content The content of the orbiter.<br> *<br> * Example:<br> * ```<br> * Orbiter(position = OrbiterEdge.Top, offset = 10.dp) {<br> *   Text(&quot;This is a top edge Orbiter&quot;)<br> * }<br> * ```<br> */<br>@Composable<br>@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX)<br>public fun Orbiter(<br>    position: OrbiterEdge.Horizontal,<br>    offset: Dp = 0.dp,<br>    alignment: Alignment.Horizontal = Alignment.CenterHorizontally,<br>    settings: OrbiterSettings = OrbiterDefaults.orbiterSettings,<br>    shape: SpatialShape = OrbiterDefaults.shape,<br>    content: @Composable () -&gt; Unit,<br>)</pre><p>Lets follow the Spatial package first, as defining a new composable with @SubspaceComposable seems more complex than simply using the same Composable.</p><h3>Spatial Package</h3><p>The spatial package contains fewer files than the subspace package.</p><pre>├── spatial<br>│   ├── ConstrainToModifier.kt<br>│   ├── ElevatedPanel.kt<br>│   ├── Orbiter.kt<br>│   ├── OutsideInputHandler.kt<br>│   ├── RememberCalculatePose.kt<br>│   ├── SpatialDialog.kt<br>│   ├── SpatialElevation.kt<br>│   ├── SpatialElevationLevel.kt<br>│   ├── SpatialPopup.kt<br>│   └── Subspace.kt</pre><p>Without SubSpace, the other components are delegated to ElevatedPanel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*M-ZDCTpKCHAVadHgFwL-qA.png" /></figure><p>This time, we’ll skip diving into each spatial components like Orbiter, SpatialDialog, SpatialElevation, and SpatialPopup. Instead we’ll focus on ElevatedPanel, as it is key to understanding how elevation works.</p><pre>/**<br> * This is the base panel underlying the implementations of SpatialElevation, SpatialPopup, and<br> * SpatialDialog. It allows creating a panel at a specific size and [Pose].<br> */<br>@Composable<br>internal fun ElevatedPanel(<br>    contentSize: IntSize,<br>    shape: SpatialShape = ElevatedPanelDefaults.shape,<br>    pose: Pose? = null,<br>    content: @Composable () -&gt; Unit,<br>) {<br>    val session = checkNotNull(LocalSession.current) { &quot;session must be initialized&quot; }<br>    val parentPanelEntity = LocalPanelEntity.current ?: session.mainPanelEntity<br>    val density = LocalDensity.current<br>    var panelEntity by remember { mutableStateOf&lt;PanelEntity?&gt;(null) }<br>    val meterSize = contentSize.toMeterSize(density)<br><br>    val view = rememberComposeView {<br>        CompositionLocalProvider(LocalPanelEntity provides panelEntity) {<br>            Box(Modifier.alpha(if (pose == null) 0.0f else 1.0f)) { content() }<br>        }<br>    }<br><br>    DisposableEffect(Unit) {<br>        panelEntity =<br>            session.createPanelEntity(<br>                view = view,<br>                surfaceDimensionsPx = meterSize.toCorePixelDimensions(density),<br>                dimensions = meterSize.toCoreMeterDimensions(),<br>                name = &quot;ElevatedPanel:${view.id}&quot;,<br>            )<br>        onDispose {<br>            panelEntity?.dispose()<br>            panelEntity = null<br>        }<br>    }<br><br>    LaunchedEffect(pose) {<br>        if (pose != null) {<br>            panelEntity?.setPose(pose)<br>        }<br>    }<br><br>    LaunchedEffect(contentSize) {<br>        val width = contentSize.width.toFloat()<br>        val height = contentSize.height.toFloat()<br><br>        panelEntity?.setSize(Dimensions(width = width, height = height, depth = 0f))<br>        if (shape is SpatialRoundedCornerShape) {<br>            panelEntity?.setCornerRadius(<br>                Meter.fromPixel(shape.computeCornerRadius(width, height, density), density).value<br>            )<br>        }<br>    }<br><br>    LaunchedEffect(parentPanelEntity) { panelEntity?.setParent(parentPanelEntity) }<br>}</pre><p>This code is bit a comple, so let’s break it down step by step.</p><p>The session and parentPanelEntity are provided by LocalSession and LocalPanelEntity.</p><pre>val session = checkNotNull(LocalSession.current) { &quot;session must be initialized&quot; }<br>val parentPanelEntity = LocalPanelEntity.current ?: session.mainPanelEntity</pre><p>The view is created using rememberComposeView.</p><pre>val view = rememberComposeView {<br>    CompositionLocalProvider(LocalPanelEntity provides panelEntity) {<br>        Box(Modifier.alpha(if (pose == null) 0.0f else 1.0f)) { content() }<br>    }<br>}</pre><p><a href="https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:xr/compose/compose/src/main/kotlin/androidx/xr/compose/subspace/RememberComposeView.kt;l=43?q=rememberComposeView&amp;sq=&amp;ss=androidx%2Fplatform%2Fframeworks%2Fsupport">subspace/RememberComposeView.kt</a> creates a ComposeView.</p><pre>/**<br> * Create a [ComposeView] that is applicable to the local context.<br> *<br> * This handles propagating the composition context and ensures that savable state is remembered.<br> */<br>@Composable<br>@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX)<br>public fun rememberComposeView(content: @Composable () -&gt; Unit): ComposeView {<br>    val localId = rememberSaveable { UUID.randomUUID() }<br>    val context = LocalContext.current<br>    val parentView = LocalView.current<br>    val compositionContext = rememberCompositionContext()<br><br>    return remember {<br>            ComposeView(context).apply {<br>                id = android.R.id.content<br>                setViewTreeLifecycleOwner(parentView.findViewTreeLifecycleOwner())<br>                setViewTreeViewModelStoreOwner(parentView.findViewTreeViewModelStoreOwner())<br>                setViewTreeSavedStateRegistryOwner(parentView.findViewTreeSavedStateRegistryOwner())<br>                // Dispose of the Composition when the view&#39;s LifecycleOwner is destroyed<br>                setParentCompositionContext(compositionContext)<br>                // Set unique id for AbstractComposeView. This allows state restoration for the<br>                // state<br>                // defined inside the SpatialElevation via rememberSaveable()<br>                setTag(<br>                    androidx.compose.ui.R.id.compose_view_saveable_id_tag,<br>                    &quot;ComposeView:$localId&quot;<br>                )<br><br>                // Enable children to draw their shadow by not clipping them<br>                clipChildren = false<br>            }<br>        }<br>        .apply {<br>            setContent(content)<br>            DisposableEffect(this) { onDispose { disposeComposition() } }<br>        }<br>}</pre><p>We can infer that elevated UI components are placed on each new ComposeView.</p><p>PanelEntity is created through session. Since PanelEntity contains information about the elevated UI, we can deduce that it serves as the API for managing the elevated UI.</p><pre>var panelEntity by remember { mutableStateOf&lt;PanelEntity?&gt;(null) }<br>val meterSize = contentSize.toMeterSize(density)<br>// ...<br>DisposableEffect(Unit) {<br>    panelEntity =<br>        session.createPanelEntity(<br>            view = view,<br>            surfaceDimensionsPx = meterSize.toCorePixelDimensions(density),<br>            dimensions = meterSize.toCoreMeterDimensions(),<br>            name = &quot;ElevatedPanel:${view.id}&quot;,<br>        )<br>    onDispose {<br>        panelEntity?.dispose()<br>        panelEntity = null<br>    }<br>}</pre><p>This PanelEntiy will be updated if the position or content size changes due to recomposition. It seems we can set some various properties using Entity::setPose, Entity::setSize, and Entity::setCornerRadius.</p><pre>LaunchedEffect(pose) {<br>    if (pose != null) {<br>        panelEntity?.setPose(pose)<br>    }<br>}<br><br>LaunchedEffect(contentSize) {<br>    val width = contentSize.width.toFloat()<br>    val height = contentSize.height.toFloat()<br><br>    panelEntity?.setSize(Dimensions(width = width, height = height, depth = 0f))<br>    if (shape is SpatialRoundedCornerShape) {<br>        panelEntity?.setCornerRadius(<br>            Meter.fromPixel(shape.computeCornerRadius(width, height, density), density).value<br>        )<br>    }<br>}</pre><p>The create PanelEntity will be a child of parentPanelEntity, so we can infer that there is a hierarchy of entites.</p><pre>LaunchedEffect(parentPanelEntity) { panelEntity?.setParent(parentPanelEntity) }</pre><p>We’ve found the new concept of Entity, which is part of androidx.xr.scenecore. For now, we’re focusing sorely on androidx.xr.compose, so we’ll dive deeper into Session and Entity next time.</p><p>Now, let’s move on to the subspace package.</p><h3>Subspace Package</h3><pre>├── subspace<br>│   ├── RememberComposeView.kt<br>│   ├── RememberCoreEntity.kt<br>│   ├── RowColumnImpl.kt<br>│   ├── RowColumnMeasurePolicy.kt<br>│   ├── SpatialBox.kt<br>│   ├── SpatialColumn.kt<br>│   ├── SpatialLayoutSpacer.kt<br>│   ├── SpatialPanel.kt<br>│   ├── SpatialRow.kt<br>│   ├── SubspaceComposable.kt<br>│   ├── Volume.kt<br>│   ├── layout</pre><p>SpatialBox, SpatialRow, SpatialColumn, and SpatialPanel are delegated to SubspaceLayout, so we’ll focus on SubspaceLayout for now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZnpkO-aZRDCMsgqQWra0IA.png" /></figure><p>Oh, SubspaceLayout is a new ComposNode with ComposeSubspaceNode and SubspaceNodeApplier.<br>Understanding ComposeNode requires some knowledge of compose internals. Since It’s a complex system, if you’re not familar with Compose Internals, I recommend reading “<a href="https://leanpub.com/composeinternalskor">Jetpack Compose Internals</a>”.</p><pre>/**<br> * [SubspaceLayout] is the main core component for layout for &quot;leaf&quot; nodes. It can be used to<br> * measure and position zero children.<br> *<br> * The measurement, layout and intrinsic measurement behaviours of this layout will be defined by<br> * the [measurePolicy] instance. See [MeasurePolicy] for more details.<br> *<br> * @param modifier SubspaceModifier to apply during layout.<br> * @param name a name for the ComposeSubspaceNode. This can be useful for debugging.<br> * @param measurePolicy a policy defining the measurement and positioning of the layout.<br> */<br>@Suppress(&quot;NOTHING_TO_INLINE&quot;)<br>@SubspaceComposable<br>@Composable<br>@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX)<br>public fun SubspaceLayout(<br>    modifier: SubspaceModifier = SubspaceModifier,<br>    name: String = defaultSubspaceLayoutName(),<br>    measurePolicy: MeasurePolicy,<br>) {<br>    ComposeNode&lt;ComposeSubspaceNode, SubspaceNodeApplier&gt;(<br>        factory = ComposeSubspaceNode.Constructor,<br>        update = {<br>            set(measurePolicy, SetMeasurePolicy)<br>            set(modifier, SetModifier)<br>            set(name, SetName)<br>        },<br>    )<br>}</pre><p>Creating a ComposeNode for Subspace is quiet complex, so I’ll dice into it next time. I beleieve it’s a good practice for building a custom Compose UI system through a library.</p><h3>Summary</h3><p>We explored the <strong>subspace</strong> and <strong>spatial</strong> APIs in androidx.xr.compose. We found tha the API in the<strong> spatial </strong>package is intended for <strong>common composable</strong> function, whild the <strong>subspace</strong> package is designed for a <strong>new compose UI system for subspace</strong>. Because it’s quite complex, we can dive into details, but we can understand the difference between them.</p><p>We also discovered a new concept, <strong>Entity</strong>, which is part of androidx.xr.scenecore, through ElevatedPanel in the spatial package. we can infer that <strong>androidx.xr.scenecore is a lower-level library </strong>compared to androidx.xr.compose, and it serves as the API for elevated UI.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=251c2088d76b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>