Demystifying HarmonyOS NEXT: A Deep Dive Into the Architecture, ArkUI, and Distributed Core

작성자

카테고리:

← 피드로
DEV Community · uknowWho · 2026-09-05 개발(SW)

Under-the-hood breakdown of Huawei’s “Pure HarmonyOS” SDK for engineers and architects.

For the past decade, mobile operating system architecture has been dominated by two paradigms: Android’s JVM-based, garbage-collected model, and iOS’s Darwin/Mach kernel with Swift/Objective-C. Huawei’s HarmonyOS NEXT introduces a third path.

Often referred to as “Pure HarmonyOS,” this iteration completely drops AOSP (Android Open Source Project) compatibility. It is a microkernel-based, distributed operating system built from the ground up around a custom AOT compiler and a declarative UI framework.

If you are a senior engineer or architect, looking at the HarmonyOS SDK can feel disorienting. The terminology shifts from Activities to UIAbilities, from ViewGroups to ArkUI, and from Java/Kotlin to ArkTS.

To truly master this ecosystem, we must strip away the IDE abstractions and marketing terminology. Let’s reconstruct the HarmonyOS NEXT SDK from the silicon up — the Feynman way — to understand exactly how the machine breathes.

  1. The Core Engine: How Does HarmonyOS Execute Code Without a JVM? Press enter or click to view image in full size

Android translates Java/Kotlin into Dalvik bytecode, which runs on the Android Runtime (ART) virtual machine atop a Linux kernel. HarmonyOS NEXT takes a fundamentally different path, utilizing the ArkCompiler and the Ark Runtime.

JavaScript and TypeScript are dynamically typed. A virtual machine spends massive amounts of CPU cycle time inferring types and managing garbage collection. This overhead is unacceptable for a high-performance OS UI layer.

ArkTS is a strict subset of TypeScript. It explicitly bans any, dynamic property addition, and eval. Why? Because the ArkCompiler is an AOT (Ahead-of-Time) compiler.

When you trigger a build in DevEco Studio:

1.The ArkTS code is statically parsed.
2.Because the compiler possesses absolute type certainty (due to strict typing), it translates ArkTS directly into C/C++ data structures.
3.These structures are compiled down to native ARM machine code.
The Under-the-Hood Insight:
When you write @State count: number = 0;, you are not creating a JavaScript variable at runtime. You are allocating a statically sized memory block in native C++. The UI reads this memory block directly. There is no interpreter, no JVM, and no dynamic type inference at runtime.

  1. ArkUI Internals: How Does Declarative State Actually Trigger Re-renders?

In legacy imperative UI frameworks (like older Android), developers hold a reference to a TextView and mutate it directly (textView.setText("...")). This creates severe state synchronization issues.

ArkUI uses a Declarative Re-render Model. But how does the OS know when to redraw? Let’s look under the hood of the @State decorator.

When you write the following ArkTS code:

typescript
@Component
struct MyComponent {
@State count: number = 0;
}

Enter fullscreen mode Exit fullscreen mode

During the AOT compilation phase, the ArkCompiler performs code rewriting. It transforms that struct into an imperative C++ class resembling this:

class MyComponentState {
int count;
void setCount(int val) {
if (this->count != val) {
this->count = val;
MarkDirty(this); // ←- The Core Mechanism
}
 }
  };

Enter fullscreen mode Exit fullscreen mode

When you execute this.count++ in ArkTS, you are actually calling the generated native setCount() method.

setCount() detects the value change and flags the UI component as “Dirty”.
The ArkUI rendering engine runs a Diffing Algorithm on the next Vsync (vertical sync) frame, locating the dirty component.
It re-executes thebuild() function strictly for that component.
It diffs the new virtual tree against the old tree. Upon finding that only the Text node’s string changed, it sends a native draw command to the rendering engine to repaint that specific screen rectangle.

The Under-the-Hood Insight:

@State is not merely a variable; it is a compiler-enforced getter/setter trap. Mutating it triggers a localized, garbage-collection-free tree-diff. You never touch the UI directly; you only mutate state, and the compiler intercepts the mutation to schedule a highly targeted repaint.

  1. The Stage Model: What Replaces the Android Activity? HarmonyOS replaces the monolithic Activity with the Stage Model. Think of it as a theatrical production:
  • UIAbility: The stage manager. It handles the window, lifecycle, and user interaction.

  • ExtensionAbility: The backstage crew. It handles background music, push notifications, and UI-less services.

  • WindowStage: The physical stage. The UIAbility holds a WindowStage, and you load your ArkUI pages into it.
    Under the hood, HarmonyOS is heavily process-isolated. Your UI runs in one process, while a background music ExtensionAbility might run in another. They communicate strictly via IPC (Inter-Process Communication).

When you launch an app:

1.The system spawns the App process.
2.It instantiates AbilityContext(the system API bridge).
3.It creates UIAbility and calls onCreate().
4.It creates the WindowStage and passes it to onWindowStageCreate().
5.loadContent('pages/Index') commands the ArkUI engine to parse Index.ets, build the component tree, and attach it to the window’s rendering surface.

The Under-the-Hood Insight:
The OS is agnostic to your pages. It only manages the WindowStage. You can swap pages in and out of the WindowStage like changing TV channels. The OS solely needs to know when the window gains or loses focus to allocate or revoke GPU/CPU resources.

  1. NAPI: How Does ArkTS Safely Communicate with C/C++? ArkTS runs in the Ark Runtime (managing UI, state, and memory safely). C/C++ runs natively. If ArkTS could arbitrarily write to C++ memory, the OS would crash instantly due to pointer mismanagement.

HarmonyOS solves this using NAPI (Node-API derivative). It acts as a strict, secure border checkpoint.

When you import a native library into ArkTS:

import entry from 'libentry.so';
entry.add(2, 3);

Here is the exact execution sequence under the hood:

Marshalling: ArkTS packages the numbers 2 and 3 into a secure napi_env structure.

Thread Context: NAPI ensures the call occurs on the correct ArkTS thread (or handles thread-safe transitions).

C++ Execution: The C++ function Add is invoked. It extracts the numbers using NAPI tools (napi_get_value_double).

Unmarshalling: C++ creates a new napi_value for the result (5).
Return: The Ark Runtime unwraps this and passes it back to ArkTS.

The Under-the-Hood Insight:
NAPI operates on “blind boxes.” ArkTS passes a sealed box to C++. C++ cannot see inside without utilizing NAPI extraction tools. C++ places the result in a new box and passes it back. This guarantees absolute type safety and memory isolation, preventing garbage collector conflicts and memory leaks.

  1. The Distributed Soft Bus: How Does Cross-Device Sync Actually Work? The defining feature of HarmonyOS is its distributed nature, powered by the Distributed Soft Bus.

Standard networking is highly inefficient for local device meshes: Device A connects to Wi-Fi, discovers Device B’s IP, opens a TCP socket, formats JSON payloads, sends, and Device B parses them.

The Soft Bus makes a phone, a tablet, and a smart TV act as if they are one single machine with multiple displays.

Under the hood:

Discovery: Devices broadcast their capabilities on the local network via a highly optimized proprietary protocol.
Authentication: They establish an encrypted peer-to-peer (P2P) tunnel, often utilizing Wi-Fi Direct or BLE.
Virtualization: The OS creates a “Virtual Device” layer.
When you write to the Distributed KV Store in ArkTS:

await store.put('color', 'red');

Under the hood, this does not merely write to a local SQLite database.

1.The KV Store SDK passes the key-value pair to the Soft Bus.
2.The Soft Bus serializes it into a compact binary packet.
3.It pushes the packet over the P2P tunnel to the paired device.
4.The remote device’s Soft Bus receives it and updates its local KV Store.
5.The remote device’s @StorageLink interceptor catches the change and triggers a UI re-render.
The Under-the-Hood Insight:

You are not writing network code. You are writing local code, and the OS silently intercepts your disk writes, replicating them over the network to sibling devices. “Cross-device” development is reduced to a local memory map.

6. Concurrency: Why Can’t ArkTS Run Heavy Loops on the Main Thread?
ArkUI is strictly single-threaded. It runs on the Main Thread. If you execute a blocking for loop, you starve the Vsync signal, and the UI drops to 0 frames per second.

HarmonyOS provides two mechanisms to escape the main thread:

  1. Worker Threads (@kit.ArkTS) Think of this as renting a separate warehouse. You create a ThreadWorker. The OS spawns a true native OS thread and creates a completely separate Ark Runtime instance for it. They communicate via postMessage.
  • Cost: Spawning a worker requires memory and time. It is inefficient for short, frequent tasks.
  • TaskPool (@kit.ArkTS) Think of this as an intelligent Uber Pool. The OS maintains a hidden pool of pre-warmed threads. When you call taskpool.execute(heavyFunc), the OS finds an idle thread, runs the function, returns the result, and keeps the thread alive for the next task.

The Under-the-Hood Insight:

In HarmonyOS, memory is never shared between the UI thread and a Worker. If you pass an object to a Worker, it is deep-copied (serialized) across the thread boundary to maintain thread safety and prevent GC deadlocks. TaskPool optimizes this by allowing transferable objects (like ArrayBuffers), where memory ownership is transferred rather than duplicated.

  1. The Build System: What Happens When You Press “Run”? Android relies on Gradle. HarmonyOS utilizes Hvigor (a build system built on Node.js, highly optimized in TypeScript).

When you build a HarmonyOS application:

  1. Resource Collection: Hvigor parses resources/ (strings, images) and compiles them into a binary resources.index file for O(1) lookup at runtime.
  2. ArkTS Compilation: ArkCompiler parses .ets files. It strips away UI decorators (@Component, @builder) and translates them into imperative C++ struct definitions and rendering logic.
  3. Native Build: If the project includes C++ (NAPI), CMake is invoked to compile .cpp files into .so libraries for the target architecture (e.g., arm64-v8a).
  4. Packaging: Everything is zipped into a .hap (Harmony Ability Package).
  5. Signing: The HAP is cryptographically signed using your developer certificate, ensuring the OS kernel permits execution.

Conclusion: The Grand Unification
If we were to summarize the HarmonyOS NEXT architecture in a single thought:

“You are writing in a strictly typed language (ArkTS) so the compiler can translate your words directly into machine code. You never explicitly tell the screen what to draw; you only mutate state, and the OS intercepts those mutations to draw for you. If you need to perform heavy computation, you hand it to a background thread, packing the data securely to send it across. And underneath it all, the OS is secretly wired so that your phone, tablet, and TV operate as a single brain with multiple windows.”

HarmonyOS NEXT represents a paradigm shift from VM-based, object-oriented mobile development to AOT-compiled, declarative, distributed architecture. By understanding the getter/setter traps of @State, the strict isolation of NAPI, and the seamless replication of the Soft Bus, engineers can stop writing code blindly and begin speaking the OS’s native language.

References & Official Documentation
HarmonyOS Developer Portal:
ArkTS Language Reference:
ArkUI Declarative Framework:
Stage Model Overview:
NAPI (Native API) Guide: developer.harmonyos.com/en/develop/ndk/
Distributed Data Sync:

원문에서 계속 ↗