### Implement Event Hub Pattern with TypeScript Source: https://context7.com/harmonyos-dev/harmonyos-codelabs/llms.txt Defines and uses custom event IDs for inter-component communication using the event emitter. This example shows how to define event constants and emit/subscribe to events for color changes. ```typescript // events.ts - Define event constants export const EV_COLOR_CHANGE = 1; export const EV_BRIGHT_CHANGE = 2; export const EV_IMMERSE_CHANGE = 3; export const EV_FLOAT_WINDOW = 4; // Publisher component import hub from "@ohos.events.emitter"; import { EV_COLOR_CHANGE } from "../events"; hub.emit({ eventId: EV_COLOR_CHANGE }, { data: { color: '#FF0000' } }) // Subscriber in Ability import hub from '@ohos.events.emitter'; import {EV_COLOR_CHANGE} from '../events'; hub.on({eventId: EV_COLOR_CHANGE}, (data) => { const color = data.data['color']; windowStage.getMainWindowSync().setWindowBackgroundColor(color); }); ``` -------------------------------- ### Load and Control Web Pages with TypeScript WebView Source: https://context7.com/harmonyos-dev/harmonyos-codelabs/llms.txt This snippet demonstrates how to integrate web content into a HarmonyOS application using the `Web` component and `WebviewController`. It allows loading URLs from a search input and displays the web page within the application. Dependencies include '@ohos.web.webview'. ```typescript import webView from '@ohos.web.webview'; @Entry @Component struct Index { @State url: string = "https://www.baidu.com/" controller: webView.WebviewController = new webView.WebviewController() build() { Column() { Search({value: this.url}) .onSubmit((value) => { this.url = value this.controller.loadUrl(value) }) .searchButton("Load") .width("100%") Web({ src: this.url, controller: this.controller}) .width("100%") .height("100%") } } } ``` -------------------------------- ### HarmonyOS Stage Model: Manage Window Background Color Source: https://context7.com/harmonyos-dev/harmonyos-codelabs/llms.txt Demonstrates how to manage the window background color in HarmonyOS Stage Model applications. It uses event-driven communication between the UI and Ability layers to apply color changes. Requires the '@ohos.window' and '@ohos.events.emitter' modules. ```typescript // EntryAbility.ts - Window background color management import UIAbility from '@ohos.app.ability.UIAbility'; import window from '@ohos.window'; import hub from '@ohos.events.emitter'; import {EV_COLOR_CHANGE, EV_BRIGHT_CHANGE} from '../events'; export default class EntryAbility extends UIAbility { onWindowStageCreate(windowStage: window.WindowStage) { windowStage.loadContent('pages/Index', (err, data) => { if (err.code) { hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? ''); return; } }); // Listen for color change events from UI hub.on({eventId: EV_COLOR_CHANGE}, (data) => { windowStage.getMainWindowSync().setWindowBackgroundColor(data.data['color']); }); // Listen for brightness change events hub.on({eventId: EV_BRIGHT_CHANGE}, (data) => { windowStage.getMainWindowSync().setWindowBrightness(data.data['bright'] / 10, (err) => { if (err.code) { hilog.error(0x0000, 'EV_BRIGHT_CHANGE', 'Failed to set the window brightness. Cause: %{public}s', JSON.stringify(err) ?? ''); return; } hilog.info(0x0000, 'EV_BRIGHT_CHANGE', 'Succeeded in setting the window brightness'); }); }); } } // Index.ets - UI emits events import hub from "@ohos.events.emitter"; import { EV_COLOR_CHANGE, EV_BRIGHT_CHANGE } from "../events"; @Entry @Component struct Index { @State bright: number = 5; build() { Column() { Button("Red") .onClick(() => { hub.emit({ eventId: EV_COLOR_CHANGE }, { data: { color: '#FF0000' } }) }) Button("Brightness+") .onClick(() => { this.bright += 1 if (this.bright > 10) this.bright = 10 hub.emit({ eventId: EV_BRIGHT_CHANGE }, { data: { bright: this.bright } }) }) } } } ``` -------------------------------- ### Create and Destroy Floating Windows with TypeScript Source: https://context7.com/harmonyos-dev/harmonyos-codelabs/llms.txt Demonstrates how to create and destroy floating windows using the TYPE_FLOAT window type in HarmonyOS. It utilizes the `window.createWindow` and `windowClass.destroyWindow` methods. Event handling is managed through a hub. ```typescript import {EV_FLOAT_WINDOW} from '../events'; let windowClass: window.Window | null = null; hub.on({eventId: EV_FLOAT_WINDOW}, (data) => { if (data.data["create"]) { window.createWindow({ name: 'my float window', windowType: window.WindowType.TYPE_FLOAT, ctx: this.context }, (err, data) => { if (err.code) { hilog.error(0x0000, 'EV_FLOAT_WINDOW', 'Failed to create the float window. Cause: %{public}s', JSON.stringify(err) ?? ''); return; } windowClass = data; hilog.info(0x0000, 'EV_FLOAT_WINDOW', 'Succeeded in creating the float window'); }); } else { windowClass?.destroyWindow((err, data) => { if (err.code) { hilog.error(0x0000, 'testTag', 'Failed to destroy the float window. Cause: %{public}s', JSON.stringify(err) ?? ''); return; } windowClass = null; }); } }); // Index.ets Button("Open Float Window") .onClick(() => { hub.emit({ eventId: EV_FLOAT_WINDOW }, { data: { floatWindow: true, create: true } }) }) Button("Close Float Window") .onClick(() => { hub.emit({ eventId: EV_FLOAT_WINDOW }, { data: { floatWindow: false, create: false } }) }) ``` -------------------------------- ### Navigate to Dial Screen with TypeScript Source: https://context7.com/harmonyos-dev/harmonyos-codelabs/llms.txt Navigates to the system dialer with a pre-filled phone number without requiring special permissions. Uses the '@ohos.telephony.call' module to initiate the call. ```typescript import call from '@ohos.telephony.call' @Entry @Component struct Index { @State phoneNum: string = "13888888888" build() { Column() { TextInput({ placeholder: "Enter phone number", text: this.phoneNum }) .onChange((text) => { this.phoneNum = text }) .fontSize(50) .fontWeight(FontWeight.Bold) Button("Make Call") .onClick(() => { // Jump to dial screen - no permissions required call.makeCall(this.phoneNum) }) } } } ``` -------------------------------- ### Configure Permissions in module.json5 Source: https://context7.com/harmonyos-dev/harmonyos-codelabs/llms.txt Configures application permissions for telephony and other system features within the module.json5 file. This JSON5 snippet specifies read call log and place call permissions. ```json5 { "module": { "name": "entry", "type": "entry", "mainElement": "EntryAbility", "deviceTypes": ["phone", "tablet"], "requestPermissions": [ { "name": "ohos.permission.READ_CALL_LOG", }, { "name": "ohos.permission.PLACE_CALL", } ], "abilities": [ { "name": "EntryAbility", "srcEntry": "./ets/entryability/EntryAbility.ts", "exported": true, "skills": [ { "entities": ["entity.system.home"], "actions": ["action.system.home"] } ] } ] } } ``` -------------------------------- ### Monitor Signal Strength with TypeScript Source: https://context7.com/harmonyos-dev/harmonyos-codelabs/llms.txt Monitors cellular signal strength changes in real-time using a telephony observer. It registers a callback for 'signalInfoChange' events and displays the signal type, level, and dBm. Requires the '@ohos.telephony.observer' module. ```typescript import observer from '@ohos.telephony.observer' @Entry @Component struct Index { @State signalStrength: string[] = [] onSignalChange(signalInfo) { this.signalStrength = signalInfo.map(it => `Type: ${it.signalType}, Level: ${it.signalLevel}, Dbm: ${it.dBm}` ) } aboutToAppear() { try { observer.on('signalInfoChange', this.onSignalChange); } catch (e) { console.error(e) } } aboutToDisappear() { try { observer.off('signalInfoChange', this.onSignalChange) } catch (e) { console.error(e) } } build() { Column() { ForEach(this.signalStrength, (it) => { Text(it) }) } } } ``` -------------------------------- ### Publish Picture Notification using TypeScript Source: https://context7.com/harmonyos-dev/harmonyos-codelabs/llms.txt Publishes a notification with an embedded image. It loads an image from resources and creates a PixelMap for the notification content. Requires the '@ohos.multimedia.image' module. ```typescript import image from '@ohos.multimedia.image'; Button("Send Picture Notification") .onClick(async () => { // Load image from resources const raw = await getContext().resourceManager.getMediaContent($r("app.media.icon").id); const pixelMap = await image.createPixelMap(raw, { size: {width: 114, height: 114}, pixelFormat: 3 }); NotificationManager.publish({ id: 4, content: { contentType: NotificationManager.ContentType.NOTIFICATION_CONTENT_PICTURE, picture: { title: "Picture Notification", text: "This is a picture notification", additionalText: "Additional text for picture notification", briefText: "Brief description of picture notification", expandedTitle: "Expanded title for picture notification", picture: pixelMap, } } }, (err) => { if (err) { console.error(`Failed to publish notification. Code is ${err.code}, message is ${err.message}`); return; } console.info('Succeeded in publishing notification.'); }); }); ``` -------------------------------- ### Publish Basic Text Notification with TypeScript Source: https://context7.com/harmonyos-dev/harmonyos-codelabs/llms.txt This code shows how to publish a basic text notification in HarmonyOS using the `NotificationManager`. It includes setting the notification ID, content type, title, text, and additional text. The `NotificationManager.publish` method is used for this purpose. ```typescript import NotificationManager from '@ohos.notificationManager'; @Entry @Component struct Index { build() { Column() { Button("Send Basic Notification") .onClick(() => { NotificationManager.publish({ id: 1, content: { contentType: NotificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, normal: { title: "Basic Text Notification", text: "This is a basic text notification", additionalText: "Additional text for basic notification" } } }); }); } } } ``` -------------------------------- ### Publish Multiline Text Notification with TypeScript Source: https://context7.com/harmonyos-dev/harmonyos-codelabs/llms.txt This code snippet illustrates how to publish a multiline text notification in HarmonyOS. It formats the notification content as a list of lines, suitable for displaying multiple pieces of information concisely. Uses `NotificationManager.publish` with `NOTIFICATION_CONTENT_MULTILINE` content type. ```typescript Button("Send Multiline Notification") .onClick(() => { NotificationManager.publish({ id: 3, content: { contentType: NotificationManager.ContentType.NOTIFICATION_CONTENT_MULTILINE, multiLine: { title: "Multiline Text Notification", text: "This is a multiline text notification", briefText: "Brief description of multiline notification", longTitle: "Additional title for multiline notification", lines: [ "First line of multiline notification", "Second line of multiline notification", "Third line of multiline notification", ] } } }); }); ``` -------------------------------- ### HarmonyOS Stage Model: Toggle Immersive Mode Source: https://context7.com/harmonyos-dev/harmonyos-codelabs/llms.txt Shows how to enable or disable immersive mode in HarmonyOS Stage Model applications, which hides or shows system bars. It utilizes event emission and reception for toggling the immersive state. Relies on '@ohos.events.emitter' and window management APIs. ```typescript // EntryAbility.ts import {EV_IMMERSE_CHANGE} from '../events'; hub.on({eventId: EV_IMMERSE_CHANGE}, (data) => { hilog.info(0x0000, 'EV_IMMERSE_CHANGE', 'Received immerse change event: %{public}s', JSON.stringify(data) ?? ''); // Empty array hides system bars, ['status', 'navigation'] shows them windowStage.getMainWindowSync().setWindowSystemBarEnable( data.data['immerse'] ? [] : ['status', 'navigation'] ); }); // Index.ets Button("Enable Immersive") .onClick(() => { hub.emit({ eventId: EV_IMMERSE_CHANGE }, { data: { immerse: true } }) }) Button("Disable Immersive") .onClick(() => { hub.emit({ eventId: EV_IMMERSE_CHANGE }, { data: { immerse: false } }) }) ``` -------------------------------- ### Publish Long Text Notification with TypeScript Source: https://context7.com/harmonyos-dev/harmonyos-codelabs/llms.txt Demonstrates how to create and publish a long text notification in HarmonyOS. This allows for expandable notifications with a detailed expanded view. It utilizes `NotificationManager.publish` with `NOTIFICATION_CONTENT_LONG_TEXT` content type, including expanded title and brief text. ```typescript Button("Send Long Text Notification") .onClick(() => { NotificationManager.publish({ id: 2, content: { contentType: NotificationManager.ContentType.NOTIFICATION_CONTENT_LONG_TEXT, longText: { title: "Long Text Notification", text: "This is a long text notification", additionalText: "Additional text for long notification", longText: "This is the expanded long text content that appears when user expands the notification", briefText: "Brief description of long text notification", expandedTitle: "Expanded title when notification is expanded", } } }); }); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.