You can use the liveViewManager module to create a local live view and implement its entire lifecycle (including creation, update, and ending). Note that you can create a live view only when your app is running in the foreground and the user is actively using the app, thereby establishing a service contract. In addition, updating or ending a live view locally requires your app process to remain running. Therefore, we recommend that after creating a live view locally, you use Push Kit to update or end the live view.
Live View Kit provides sample code for the entire live view lifecycle in 13 scenarios, including ride-hailing, instant delivery, air travel, rail travel, queuing, meal pickup, live score, shared rental, timing, workout, navigation, clock-in/out, and express delivery. If you want to experience the effect before developing a live view, please refer to the Live View Kit sample code.
Location-based live view reminders are supported in the clock-in/out and express delivery scenarios starting from 6.1.0(23).
Import liveViewManager to your project, create a live view control class (for example, LiveViewController), and construct the isLiveViewEnabled() method to check whether the live view feature (Settings > Apps & services > App name > Live view) is enabled. You must enable the live view feature before creating a live view. The sample code is as follows:
import { liveViewManager } from '@kit.LiveViewKit';
export class LiveViewController {
public static async isLiveViewEnabled(): Promise<boolean> {
return await liveViewManager.isLiveViewEnabled();
}
} There are five live view templates based on the extension area: progress visualization template, emphasized text template, left-right text template, live scores template, and navigation template.
Call the liveViewManager.startLiveView API to create a live view. The input parameter of this API is a live view instance (liveViewManager.LiveView).
The progress visualization template is applicable to scenarios such as ride-hailing and food delivery.

Starting from version 6.0.2(22), the live view widget can display the dynamic weather background of rain or snow when the progress visualization template is used.


The sample code is as follows:
After building LiveViewController, initialize it in the code and call the LiveViewController.startLiveView() method.
import { liveViewManager } from '@kit.LiveViewKit';
import { Logger } from '../LogUtil';
import { ContextUtil } from '../ContextUtil';
import { BusinessError } from '@kit.BasicServicesKit';
export class ProgressLiveViewController {
public async startLiveView(): Promise<boolean> {
// Check whether the live view feature is enabled.
if (!await ProgressLiveViewController.isLiveViewEnabled()) {
Logger.warn('startLiveView, live view is disabled.');
return false;
}
// Create a live view.
try {
const defaultView = await ProgressLiveViewController.buildDefaultView();
if (!defaultView) {
Logger.warn('buildDefaultView Failed.');
return false;
}
Logger.info('Request startLiveView req: %{public}s', JSON.stringify(defaultView));
const result = await liveViewManager.startLiveView(defaultView);
Logger.info('Request startLiveView result: %{public}s', JSON.stringify(result));
return true;
} catch (e) {
const err: BusinessError = e as BusinessError;
Logger.error('Request startLiveView error: %{public}d %{public}s', err.code, err.message);
return false;
}
}
// ...
private static async buildDefaultView(): Promise<liveViewManager.LiveView> {
return {
// Construct a live view request body.
id: 106, // Live view ID, which is generated by you.
event: 'DELIVERY', // Application scenario of the live view. The value DELIVERY indicates instant delivery (food delivery and fresh produce).
isMute: false,
liveViewData: {
primary: {
title: 'Rider is on the way',
content: [
{ text: ' m' },
{ text: '300 ', textColor: '#FF0A59F7' },
{ text: 'away | ' },
{ text: '3 ', textColor: '#FF0A59F7' },
{ text: 'min' }
], // If textColor is set for some objects in the array, its values for all these objects must be the same. If textColor is not set for an object in the array, the default text color #FF000000 will be used.
keepTime: 0,
clickAction: await ContextUtil.buildWantAgent('GuideCode'),
layoutData: {
layoutType: liveViewManager.LayoutType.LAYOUT_TYPE_PROGRESS,
weatherInfo: {
weatherType: liveViewManager.WeatherType.WEATHER_TYPE_HEAVY_RAIN, // weatherType indicates the weather type. WEATHER_TYPE_HEAVY_RAIN indicates heavy rain, and WEATHER_TYPE_HEAVY_SNOW indicates heavy snow.
locationType: liveViewManager.WeatherLocationType.LOCATION_TYPE_LOCAL
},
progress: 40,
color: '#FF317AF7',
backgroundColor: '#f7819ae0',
indicatorType: liveViewManager.IndicatorType.INDICATOR_TYPE_UP,
indicatorIcon: 'icon_rider.png', // Progress indicator icon. The value is a file name under /resources/rawfile or an image.PixelMap object.
lineType: liveViewManager.LineType.LINE_TYPE_DOTTED_LINE,
nodeIcons: ['icon_order.png', 'icon_store_white.png', 'icon_finish.png'] // Icon of each node in the progress bar. The value of each element is a file name under /resources/rawfile or an image.PixelMap object.
}
}
}
};
}
private static async isLiveViewEnabled(): Promise<boolean> {
let result: boolean = false;
try {
result = await liveViewManager.isLiveViewEnabled();
} catch (e) {
const err: BusinessError = e as BusinessError;
Logger.error('Request isLiveViewEnabled error: %{public}d %{public}s', err.code, err.message);
}
Logger.info('Request isLiveViewEnabled result: %{public}s', result);
return result;
}
} import { common, Want, WantAgent, wantAgent } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { Logger } from './LogUtil';
export class ContextUtil {
public static wantUrl: string | undefined;
public static liveViewId: number;
public static applicationContext: common.ApplicationContext;
public static async buildWantAgent(page: string, liveViewId: number = -1): Promise<Want> {
const wantAgentInfo: wantAgent.WantAgentInfo = {
wants: [
{
bundleName: ContextUtil.applicationContext.applicationInfo.name,
abilityName: 'EntryAbility',
parameters: {
page: page,
liveViewId: liveViewId
},
} as Want
],
actionType: wantAgent.OperationType.START_ABILITIES,
requestCode: 0,
actionFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
};
try {
const agent: WantAgent = await wantAgent.getWantAgent(wantAgentInfo);
Logger.info('getWantAgent success! wantAgent: %{public}s', JSON.stringify(agent));
return agent;
} catch (e) {
const err: BusinessError = e as BusinessError;
Logger.error('getWantAgent failed! err: %{public}d %{public}s', err.code, err.message);
throw e as Error;
}
}
} The emphasized text template is applicable to scenarios such as meal pickup and queuing.

Starting from version 6.0.2(22), the live view widget can display the dynamic weather background of rain or snow when the emphasized text template is used.


The sample code is as follows:
After building LiveViewController, initialize it in the code and call the LiveViewController.startLiveView() method.
import { liveViewManager } from '@kit.LiveViewKit';
import { Logger } from '../LogUtil';
import { ContextUtil } from '../ContextUtil';
import { BusinessError } from '@kit.BasicServicesKit';
export class PickupLiveViewController {
public async startLiveView(): Promise<boolean> {
// Check whether the live view feature is enabled.
if (!await PickupLiveViewController.isLiveViewEnabled()) {
Logger.warn('startLiveView, live view is disabled.');
return false;
}
// Create a live view.
try {
const defaultView = await PickupLiveViewController.buildDefaultView();
if (!defaultView) {
Logger.warn('buildDefaultView Failed.');
return false;
}
Logger.info('Request startLiveView req: %{public}s', JSON.stringify(defaultView));
const result = await liveViewManager.startLiveView(defaultView);
Logger.info('Request startLiveView result: %{public}s', JSON.stringify(result));
return true;
} catch (e) {
const err: BusinessError = e as BusinessError;
Logger.error('Request startLiveView error: %{public}d %{public}s', err.code, err.message);
return false;
}
}
// ...
private static async buildDefaultView(): Promise<liveViewManager.LiveView> {
return {
// Construct a live view request body.
id: 105, // Live view ID, which is generated by you.
event: 'PICK_UP', // Application scenario of the live view. The value PICK_UP indicates meal pickup.
isMute: false,
liveViewData: {
primary: {
title: 'Meal ready',
content: [
{ text: 'Pick up at' },
{ text: ' XXX', textColor: '#FF0A59F7' },
{ text: '' }
],
keepTime: 0,
clickAction: await ContextUtil.buildWantAgent('GuideCode'),
layoutData: {
layoutType: liveViewManager.LayoutType.LAYOUT_TYPE_PICKUP,
weatherInfo: {
weatherType: liveViewManager.WeatherType.WEATHER_TYPE_HEAVY_SNOW, // weatherType indicates the weather type. WEATHER_TYPE_HEAVY_RAIN indicates heavy rain, and WEATHER_TYPE_HEAVY_SNOW indicates heavy snow.
locationType: liveViewManager.WeatherLocationType.LOCATION_TYPE_LOCAL
},
title: 'Pickup code',
content: '72988',
underlineColor: '#FF0A59F7',
descPic: 'coffee.png' // Product description image on the right of the extension area. The value is a file name under /resources/rawfile or an image.PixelMap object.
}
}
}
};
}
private static async isLiveViewEnabled(): Promise<boolean> {
let result: boolean = false;
try {
result = await liveViewManager.isLiveViewEnabled();
} catch (e) {
const err: BusinessError = e as BusinessError;
Logger.error('Request isLiveViewEnabled error: %{public}d %{public}s', err.code, err.message);
}
Logger.info('Request isLiveViewEnabled result: %{public}s', result);
return result;
}
} import { common, Want, WantAgent, wantAgent } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { Logger } from './LogUtil';
export class ContextUtil {
public static wantUrl: string | undefined;
public static liveViewId: number;
public static applicationContext: common.ApplicationContext;
public static async buildWantAgent(page: string, liveViewId: number = -1): Promise<Want> {
const wantAgentInfo: wantAgent.WantAgentInfo = {
wants: [
{
bundleName: ContextUtil.applicationContext.applicationInfo.name,
abilityName: 'EntryAbility',
parameters: {
page: page,
liveViewId: liveViewId
},
} as Want
],
actionType: wantAgent.OperationType.START_ABILITIES,
requestCode: 0,
actionFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
};
try {
const agent: WantAgent = await wantAgent.getWantAgent(wantAgentInfo);
Logger.info('getWantAgent success! wantAgent: %{public}s', JSON.stringify(agent));
return agent;
} catch (e) {
const err: BusinessError = e as BusinessError;
Logger.error('getWantAgent failed! err: %{public}d %{public}s', err.code, err.message);
throw e as Error;
}
}
} The left-right text template is applicable to scenarios such as rail and air travel.

Starting from version 6.0.0(20), the live view widget supports displaying dynamic weather backgrounds such as rain and snow, as well as atmospheric backgrounds like sunset and moon-viewing when the left-right text template is used.

The sample code is as follows:
After building LiveViewController, initialize it in the code and call the LiveViewController.startLiveView() method.
import { liveViewManager } from '@kit.LiveViewKit';
import { Logger } from '../LogUtil';
import { ContextUtil } from '../ContextUtil';
import { BusinessError } from '@kit.BasicServicesKit';
export class FlightLiveViewController {
public async startLiveView(): Promise<boolean> {
// Check whether the live view feature is enabled.
if (!await FlightLiveViewController.isLiveViewEnabled()) {
Logger.warn('startLiveView, live view is disabled.');
return false;
}
// Create a live view.
try {
const defaultView = await FlightLiveViewController.buildDefaultView();
if (!defaultView) {
Logger.warn('buildDefaultView Failed.');
return false;
}
Logger.info('Request startLiveView req: %{public}s', JSON.stringify(defaultView));
const result = await liveViewManager.startLiveView(defaultView);
Logger.info('Request startLiveView result: %{public}s', JSON.stringify(result));
return true;
} catch (e) {
const err: BusinessError = e as BusinessError;
Logger.error('Request startLiveView error: %{public}d %{public}s', err.code, err.message);
return false;
}
}
// ...
private static async buildDefaultView(): Promise<liveViewManager.LiveView> {
return {
id: 103, // Live view ID, which is generated by you.
event: 'FLIGHT', // Application scenario of the live view. The value FLIGHT indicates flight.
isMute: false,
liveViewData: {
primary: {
title: 'Planned departure',
content: [
{ text: 'Gate' },
{ text: '32', textColor: '#FF0A59F7' },
{ text: ' | Seat' },
{ text: ' 17H', textColor: '#FF0A59F7' }
], // If textColor is set for some objects in the array, its values for all these objects must be the same. If textColor is not set for an object in the array, the default text color #FF000000 will be used.
keepTime: 0,
clickAction: await ContextUtil.buildWantAgent('GuideCode'),
/**
* When the backgroundType parameter passed to the live view widget is set to the moon-viewing flight or sunset flight atmospheric background,
* and a special weather condition such as rain or snow is passed through WeatherInfo, the widget will prioritize displaying the weather background.
* For all other non-special weather conditions, the widget will display the moon-viewing or sunset flight atmospheric background.
*/
backgroundType: liveViewManager.BackgroundType.SYS_BACKGROUND_FLIGHT_SUNSET,
layoutData: {
layoutType: liveViewManager.LayoutType.LAYOUT_TYPE_FLIGHT,
weatherInfo: {
/**
* weatherType indicates the weather type.
* WEATHER_TYPE_RAIN indicates rain, WEATHER_TYPE_LIGHT_RAIN indicates light rain, WEATHER_TYPE_MODERATE_RAIN indicates moderate rain, and WEATHER_TYPE_HEAVY_RAIN indicates heavy rain.
* WEATHER_TYPE_SNOW indicates snow, WEATHER_TYPE_LIGHT_SNOW indicates light snow, WEATHER_TYPE_MODERATE_SNOW indicates moderate snow, and WEATHER_TYPE_HEAVY_SNOW indicates heavy snow.
*/
weatherType: liveViewManager.WeatherType.WEATHER_TYPE_LIGHT_RAIN,
locationType: liveViewManager.WeatherLocationType.LOCATION_TYPE_DESTINATION,
highTemperature: 30,
lowTemperature: -10
},
firstTitle: '09:00',
firstContent: 'Shanghai Hongqiao',
lastTitle: '14:20',
lastContent: 'Hankou',
spaceIcon: 'icon_plane.png', // Spacing icon in the middle of the extension area. The value is a file name under /resources/rawfile or an image.PixelMap object.
isHorizontalLineDisplayed: false,
additionalText: 'The preceding information is for reference only.' // Content at the bottom of the extension area, which can be used only for the left-right text template.
}
}
}
};
}
private static async isLiveViewEnabled(): Promise<boolean> {
let result: boolean = false;
try {
result = await liveViewManager.isLiveViewEnabled();
} catch (e) {
const err: BusinessError = e as BusinessError;
Logger.error('Request isLiveViewEnabled error: %{public}d %{public}s', err.code, err.message);
}
Logger.info('Request isLiveViewEnabled result: %{public}s', result);
return result;
}
} import { common, Want, WantAgent, wantAgent } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { Logger } from './LogUtil';
export class ContextUtil {
public static wantUrl: string | undefined;
public static liveViewId: number;
public static applicationContext: common.ApplicationContext;
public static async buildWantAgent(page: string, liveViewId: number = -1): Promise<Want> {
const wantAgentInfo: wantAgent.WantAgentInfo = {
wants: [
{
bundleName: ContextUtil.applicationContext.applicationInfo.name,
abilityName: 'EntryAbility',
parameters: {
page: page,
liveViewId: liveViewId
},
} as Want
],
actionType: wantAgent.OperationType.START_ABILITIES,
requestCode: 0,
actionFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
};
try {
const agent: WantAgent = await wantAgent.getWantAgent(wantAgentInfo);
Logger.info('getWantAgent success! wantAgent: %{public}s', JSON.stringify(agent));
return agent;
} catch (e) {
const err: BusinessError = e as BusinessError;
Logger.error('getWantAgent failed! err: %{public}d %{public}s', err.code, err.message);
throw e as Error;
}
}
} The live scores template is applicable to sports event scenarios.

The sample code is as follows:
After building LiveViewController, initialize it in the code and call the LiveViewController.startLiveView() method.
import { liveViewManager } from '@kit.LiveViewKit';
import { Logger } from '../LogUtil';
import { ContextUtil } from '../ContextUtil';
import { BusinessError } from '@kit.BasicServicesKit';
export class ScoreLiveViewController {
public async startLiveView(): Promise<boolean> {
// Check whether the live view feature is enabled.
if (!await ScoreLiveViewController.isLiveViewEnabled()) {
Logger.warn('startLiveView, live view is disabled.');
return false;
}
// Create a live view.
try {
const defaultView = await ScoreLiveViewController.buildDefaultView();
if (!defaultView) {
Logger.warn('buildDefaultView Failed.');
return false;
}
Logger.info('Request startLiveView req: %{public}s', JSON.stringify(defaultView));
const result = await liveViewManager.startLiveView(defaultView);
Logger.info('Request startLiveView result: %{public}s', JSON.stringify(result));
return true;
} catch (e) {
const err: BusinessError = e as BusinessError;
Logger.error('Request startLiveView error: %{public}d %{public}s', err.code, err.message);
return false;
}
}
// ...
private static async buildDefaultView(): Promise<liveViewManager.LiveView> {
return {
// Construct a live view request body.
id: 108, // Live view ID, which is generated by you.
event: 'SCORE', // Application scenario of the live view. The value SCORE indicates live scores.
isMute: false,
liveViewData: {
primary: {
title: 'The 4th quarter',
content: [
{ text: 'XX', textColor: '#FF0A59F7' },
{ text: ' VS ' },
{ text: 'XX', textColor: '#FF0A59F7' },
{ text: ' | ' },
{ text: 'Game 5', textColor: '#FF0A59F7' }
],
keepTime: 0,
clickAction: await ContextUtil.buildWantAgent('GuideCode'),
layoutData: {
layoutType: liveViewManager.LayoutType.LAYOUT_TYPE_SCORE,
hostName: 'Team A',
hostIcon: 'score_firefox.png',
hostScore: '110',
guestName: 'Team B',
guestIcon: 'score_m.png',
guestScore: '102',
competitionDesc: [
{ text: '●', textColor: '#FFFF0000' },
{ text: 'Q4' }
],
competitionTime: '02:16',
isHorizontalLineDisplayed: true
}
}
}
};
}
private static async isLiveViewEnabled(): Promise<boolean> {
let result: boolean = false;
try {
result = await liveViewManager.isLiveViewEnabled();
} catch (e) {
const err: BusinessError = e as BusinessError;
Logger.error('Request isLiveViewEnabled error: %{public}d %{public}s', err.code, err.message);
}
Logger.info('Request isLiveViewEnabled result: %{public}s', result);
return result;
}
} import { common, Want, WantAgent, wantAgent } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { Logger } from './LogUtil';
export class ContextUtil {
public static wantUrl: string | undefined;
public static liveViewId: number;
public static applicationContext: common.ApplicationContext;
public static async buildWantAgent(page: string, liveViewId: number = -1): Promise<Want> {
const wantAgentInfo: wantAgent.WantAgentInfo = {
wants: [
{
bundleName: ContextUtil.applicationContext.applicationInfo.name,
abilityName: 'EntryAbility',
parameters: {
page: page,
liveViewId: liveViewId
},
} as Want
],
actionType: wantAgent.OperationType.START_ABILITIES,
requestCode: 0,
actionFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
};
try {
const agent: WantAgent = await wantAgent.getWantAgent(wantAgentInfo);
Logger.info('getWantAgent success! wantAgent: %{public}s', JSON.stringify(agent));
return agent;
} catch (e) {
const err: BusinessError = e as BusinessError;
Logger.error('getWantAgent failed! err: %{public}d %{public}s', err.code, err.message);
throw e as Error;
}
}
} Location-based live view reminders are applicable to scenarios such as clock-in/out and express delivery.
Starting from version 6.1.0(23), registering location-based live view reminders triggered with a delay is supported. After registering a live view triggered by geofence conditions, the live view can be created or ended when any of the following conditions is met:
Enter the geofence.
Exit the geofence.
Enter the geofence and stay for a duration longer than geofence.delayTime (delayed trigger time).
Exit the geofence and stay for a duration longer than geofence.delayTime (delayed trigger time).
After building LiveViewController, initialize it in the code and call the LiveViewController.startLiveViewByTrigger() method to add a live view triggered by geofence conditions.
The sample code is as follows:
import { liveViewManager } from '@kit.LiveViewKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { ContextUtil } from '../ContextUtil';
import { Logger } from '../LogUtil';
import { Model } from '../model';
import { GeofenceRightsUtil } from './GeofenceRightsUtil';
export class GeofenceExpressController {
private static defaultView: liveViewManager.LiveView | undefined = undefined;
private static trigger: liveViewManager.Trigger | undefined = undefined;
private static underLineColor: string = '#FF0A59F7';
private static capsuleColor: string = '#FF308977';
public static async startLiveViewExpress(model: Model): Promise<string> {
let checkRightsResult = await GeofenceRightsUtil.checkRights();
if (checkRightsResult != '') {
return checkRightsResult;
}
try {
// Create a live view for express delivery.
GeofenceExpressController.defaultView = await GeofenceExpressController.buildExpressLiveView();
// Construct the trigger conditions for live view reminders.
GeofenceExpressController.trigger = await GeofenceExpressController.buildDefaultTrigger(model);
let createResult = await GeofenceExpressController.startLiveViewByTrigger();
if (createResult != 0) {
return await ContextUtil.applicationContext.resourceManager
.getStringValue($r('app.string.Create_failed').id);
}
return await ContextUtil.applicationContext.resourceManager
.getStringValue($r('app.string.Create_success').id);
} catch (e) {
return await ContextUtil.applicationContext.resourceManager
.getStringValue($r('app.string.Create_failed').id);
}
}
private static async startLiveViewByTrigger(): Promise<number> {
if (!GeofenceExpressController.defaultView || !GeofenceExpressController.trigger) {
Logger.warn('startLiveViewByTrigger, buildDefaultView or buildDefaultTrigger failed.')
return -1;
}
// Register a live view whose creation is triggered with a delay based on geofence conditions.
try {
Logger.info('Request startLiveViewByTrigger req liveView: %{public}s, trigger: %{public}s',
JSON.stringify(GeofenceExpressController.defaultView), JSON.stringify(GeofenceExpressController.trigger));
const result = await liveViewManager.startLiveViewByTrigger(GeofenceExpressController.defaultView,
GeofenceExpressController.trigger);
Logger.info('Request startLiveViewByTrigger result: %{public}s', JSON.stringify(result));
return result.resultCode;
} catch (e) {
const err: BusinessError = e as BusinessError;
Logger.error('Request startLiveView error: %{public}d %{public}s', err.code, err.message);
return -1;
}
}
private static async buildExpressLiveView(): Promise<liveViewManager.LiveView | undefined> {
try {
return {
id: 11, // Live view ID, which is generated by you.
event: 'EXPRESS', // Application scenario of the live view. The value EXPRESS indicates express delivery.
sequence: 1, // Sequence number.
isMute: false,
liveViewData: {
primary: {
title: await ContextUtil.applicationContext.resourceManager.getStringValue($r('app.string.Express_title')
.id),
content: [
{
text: await ContextUtil.applicationContext.resourceManager.getStringValue($r('app.string.Express_content')
.id),
}
],
keepTime: 0,
clickAction: await ContextUtil.buildWantAgent('Geofence'),
extensionData: {
type: liveViewManager.ExtensionType.EXTENSION_TYPE_ICON,
pic: 'express.png',
clickAction: await ContextUtil.buildWantAgent('Geofence', 11)
},
layoutData: {
layoutType: liveViewManager.LayoutType.LAYOUT_TYPE_PICKUP,
title: await ContextUtil.applicationContext.resourceManager.getStringValue($r('app.string.Express_layoutData_title')
.id),
content: await ContextUtil.applicationContext.resourceManager.getStringValue($r('app.string.Express_layoutData_content')
.id),
underlineColor: GeofenceExpressController.underLineColor,
// Product description image on the right of the extension area. The value is a file name under /resources/rawfile or an image.PixelMap object.
descPic: 'pick.png',
},
},
capsule: {
type: liveViewManager.CapsuleType.CAPSULE_TYPE_TEXT,
status: 1,
icon: 'pick.png',
backgroundColor: GeofenceExpressController.capsuleColor,
title: await ContextUtil.applicationContext.resourceManager.getStringValue($r('app.string.Express_layoutData_title')
.id),
content: await ContextUtil.applicationContext.resourceManager.getStringValue($r('app.string.Express_layoutData_content')
.id),
}
}
}
} catch (e) {
Logger.error('buildDefaultView failed:' + JSON.stringify(e))
return undefined;
}
}
private static async buildDefaultTrigger(model: Model): Promise<liveViewManager.Trigger | undefined> {
try {
return {
// Construct the geofence trigger conditions for a live view reminder.
type: liveViewManager.TriggerType.TRIGGER_TYPE_GEOFENCE,
displayTime: 900,
condition: {
// Geofence trigger condition: A device enters the 500-meter radius around the specified coordinate point.
longitude: model.longitude,
latitude: model.latitude,
coordinateSystemType: liveViewManager.CoordinateSystemType.COORDINATE_TYPE_GCJ02,
monitorEvent: liveViewManager.MonitorEvent.MONITOR_TYPE_ENTRY,
radius: 500,
delayTime: 0
}
}
} catch (e) {
Logger.error('buildDefaultTrigger failed:' + JSON.stringify(e))
return undefined;
}
}
} import { liveViewManager } from '@kit.LiveViewKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { ContextUtil } from '../ContextUtil';
import { Logger } from '../LogUtil';
import { geoLocationManager } from '@kit.LocationKit';
export class GeofenceRightsUtil {
// Check the permissions.
public static async checkRights(): Promise<string> {
try {
// Check whether the live view feature is enabled.
if (!await GeofenceRightsUtil.isLiveViewEnabled()) {
Logger.warn('checkRights, Live view not enabled.')
return await ContextUtil.applicationContext.resourceManager
.getStringValue($r('app.string.Live_view_enabled').id);
}
// Check whether the live view geofence feature is enabled.
if (!await GeofenceRightsUtil.isGeofenceTriggerEnabled()) {
Logger.warn('checkRights, Geofence not enabled.')
return await ContextUtil.applicationContext.resourceManager
.getStringValue($r('app.string.Live_view_geofence_enabled').id);
}
// Check whether the GPS feature is enabled.
if (!GeofenceRightsUtil.isLocationEnabled()) {
Logger.warn('checkRights, GPS not enabled.')
return await ContextUtil.applicationContext.resourceManager
.getStringValue($r('app.string.Gps_enabled').id);
}
} catch (e) {
const err: BusinessError = e as BusinessError;
Logger.error('checkRights error: %{public}d %{public}s', err.code, err.message);
return await ContextUtil.applicationContext.resourceManager
.getStringValue($r('app.string.Create_success').id);
}
return '';
}
private static async isLiveViewEnabled(): Promise<boolean> {
let result: boolean = false;
try {
result = await liveViewManager.isLiveViewEnabled();
} catch (e) {
const err: BusinessError = e as BusinessError;
Logger.error('isLiveViewEnabled error: %{public}d %{public}s', err.code, err.message);
}
Logger.info('isLiveViewEnabled result: %{public}s', result);
return result;
}
private static async isGeofenceTriggerEnabled(): Promise<boolean> {
let result: boolean = false;
try {
result = await liveViewManager.isGeofenceTriggerEnabled();
} catch (e) {
const err: BusinessError = e as BusinessError;
Logger.error('isGeofenceTriggerEnabled error: %{public}d %{public}s', err.code, err.message);
}
Logger.info('isGeofenceTriggerEnabled result: %{public}s', result);
return result;
}
private static isLocationEnabled(): boolean {
let result: boolean = false;
try {
result = geoLocationManager.isLocationEnabled();
} catch (e) {
const err: BusinessError = e as BusinessError;
Logger.error('isLocationEnabled error: %{public}d %{public}s', err.code, err.message);
}
Logger.info('isLocationEnabled result: %{public}s', result);
return result;
}
} import { common, Want, WantAgent, wantAgent } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { Logger } from './LogUtil';
export class ContextUtil {
public static wantUrl: string | undefined;
public static liveViewId: number;
public static applicationContext: common.ApplicationContext;
public static async buildWantAgent(page: string, liveViewId: number = -1): Promise<Want> {
const wantAgentInfo: wantAgent.WantAgentInfo = {
wants: [
{
bundleName: ContextUtil.applicationContext.applicationInfo.name,
abilityName: 'EntryAbility',
parameters: {
page: page,
liveViewId: liveViewId
},
} as Want
],
actionType: wantAgent.OperationType.START_ABILITIES,
requestCode: 0,
actionFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
};
try {
const agent: WantAgent = await wantAgent.getWantAgent(wantAgentInfo);
Logger.info('getWantAgent success! wantAgent: %{public}s', JSON.stringify(agent));
return agent;
} catch (e) {
const err: BusinessError = e as BusinessError;
Logger.error('getWantAgent failed! err: %{public}d %{public}s', err.code, err.message);
throw e as Error;
}
}
} Call the LiveViewController.stopLiveViewByTrigger() method to add a live view whose termination is triggered by geofence conditions.
The sample code is as follows:
import { liveViewManager } from '@kit.LiveViewKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { ContextUtil } from '../ContextUtil';
import { Logger } from '../LogUtil';
import { Model } from '../model';
import { GeofenceRightsUtil } from './GeofenceRightsUtil';
export class GeofenceFlightEndController {
private static defaultView: liveViewManager.LiveView | undefined = undefined;
private static trigger: liveViewManager.Trigger | undefined = undefined;
private static underLineColor: string = '#FF0A59F7';
private static capsuleColor: string = '#FF308977';
public static async stopLiveViewFlightEnds(model: Model): Promise<string> {
let checkRightsResult = await GeofenceRightsUtil.checkRights();
if (checkRightsResult != '') {
return checkRightsResult;
}
try {
// Construct a live view struct.
GeofenceFlightEndController.defaultView = await GeofenceFlightEndController.buildFlightLiveView();
// Create a live view.
let createResult = await GeofenceFlightEndController.startLiveView();
if (createResult != 0) {
return await ContextUtil.applicationContext.resourceManager
.getStringValue($r('app.string.Create_failed').id);
}
if (GeofenceFlightEndController.defaultView) {
if (GeofenceFlightEndController.defaultView.sequence) {
GeofenceFlightEndController.defaultView.sequence += 1;
}
GeofenceFlightEndController.defaultView.liveViewData.primary.title =
await ContextUtil.applicationContext.resourceManager
.getStringValue($r('app.string.Flight_travel_end_title').id);
GeofenceFlightEndController.defaultView.liveViewData.primary.content = [
{
text: await ContextUtil.applicationContext.resourceManager.getStringValue($r('app.string.Flight_travel_end_content')
.id)
},
];
}
// Construct a geofence condition.
GeofenceFlightEndController.trigger = await GeofenceFlightEndController.buildTrigger(model);
// Register a live view whose termination is triggered with a delay based on geofence conditions.
let stopTriggerLiveView = await GeofenceFlightEndController.stopLiveViewByTrigger();
// ...
return await ContextUtil.applicationContext.resourceManager
.getStringValue($r('app.string.Create_success').id);
} catch (e) {
const err: BusinessError = e as BusinessError;
Logger.error('Request startLiveView error: %{public}d %{public}s', err.code, err.message);
return await ContextUtil.applicationContext.resourceManager
.getStringValue($r('app.string.Create_failed').id);
}
}
private static async startLiveView(): Promise<number> {
if (!GeofenceFlightEndController.defaultView) {
Logger.warn('startLiveViewByTrigger, buildDefaultView failed.')
return -1;
}
try {
// Create a live view.
// ...
const result = await liveViewManager.startLiveView(GeofenceFlightEndController.defaultView);
// ...
return result.resultCode;
} catch (e) {
const err: BusinessError = e as BusinessError;
Logger.error('Request startLiveView error: %{public}d %{public}s', err.code, err.message);
return -1;
}
}
private static async stopLiveViewByTrigger(): Promise<number> {
if (!GeofenceFlightEndController.defaultView || !GeofenceFlightEndController.trigger) {
Logger.warn('startLiveViewByTrigger, buildDefaultView or buildDefaultTrigger failed.')
return -1;
}
try {
// Register a live view whose termination is triggered with a delay based on geofence conditions.
// ...
const result = await liveViewManager.stopLiveViewByTrigger(GeofenceFlightEndController.defaultView,
GeofenceFlightEndController.trigger);
// ...
return result.resultCode;
} catch (e) {
const err: BusinessError = e as BusinessError;
Logger.error('Request startLiveView error: %{public}d %{public}s', err.code, err.message);
return -1;
}
}
private static async buildFlightLiveView(): Promise<liveViewManager.LiveView | undefined> {
try {
return {
id: 14, // Live view ID, which is generated by you.
event: 'FLIGHT', // Application scenario of the live view. The value FLIGHT indicates flight.
sequence: 1, // Sequence number.
isMute: false,
liveViewData: {
primary: {
title: await ContextUtil.applicationContext.resourceManager.getStringValue($r('app.string.Luggage_prompt_title')
.id),
content: [
{
text: await ContextUtil.applicationContext.resourceManager.getStringValue($r('app.string.Luggage_prompt_content1')
.id)
},
{
text: await ContextUtil.applicationContext.resourceManager.getStringValue($r('app.string.Luggage_prompt_content2')
.id),
textColor: GeofenceFlightEndController.underLineColor
},
],
keepTime: 15,
clickAction: await ContextUtil.buildWantAgent('Geofence'),
extensionData: {
type: liveViewManager.ExtensionType.EXTENSION_TYPE_ICON,
pic: 'flight.png',
clickAction: await ContextUtil.buildWantAgent('Geofence')
},
layoutData: {
layoutType: liveViewManager.LayoutType.LAYOUT_TYPE_FLIGHT,
firstTitle: await ContextUtil.applicationContext.resourceManager.getStringValue($r('app.string.Flight_depart_layout_first_title')
.id),
firstContent: await ContextUtil.applicationContext.resourceManager.getStringValue($r('app.string.Flight_depart_layout_first_content')
.id),
lastTitle: await ContextUtil.applicationContext.resourceManager.getStringValue($r('app.string.Flight_depart_layout_last_title')
.id),
lastContent: await ContextUtil.applicationContext.resourceManager.getStringValue($r('app.string.Flight_depart_layout_last_content')
.id),
spaceIcon: 'icon_plane.png'
},
},
capsule: {
type: liveViewManager.CapsuleType.CAPSULE_TYPE_TEXT,
status: 1,
title: await ContextUtil.applicationContext.resourceManager
.getStringValue($r('app.string.Luggage_prompt_capsule_title').id),
content: await ContextUtil.applicationContext.resourceManager
.getStringValue($r('app.string.Flight_arrived_capsule_content').id),
icon: 'capsule_flight.png',
backgroundColor: GeofenceFlightEndController.capsuleColor,
}
}
}
} catch (e) {
// ...
return undefined;
}
}
private static async buildTrigger(model: Model): Promise<liveViewManager.Trigger | undefined> {
try {
return {
type: liveViewManager.TriggerType.TRIGGER_TYPE_GEOFENCE,
displayTime: 900,
condition: {
longitude: model.longitude,
latitude: model.latitude,
coordinateSystemType: liveViewManager.CoordinateSystemType.COORDINATE_TYPE_GCJ02,
monitorEvent: liveViewManager.MonitorEvent.MONITOR_TYPE_LEAVE,
radius: 500,
delayTime: 0
}
}
} catch (e) {
// ...
return undefined;
}
}
} import { liveViewManager } from '@kit.LiveViewKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { ContextUtil } from '../ContextUtil';
import { Logger } from '../LogUtil';
import { geoLocationManager } from '@kit.LocationKit';
export class GeofenceRightsUtil {
// Check the permissions.
public static async checkRights(): Promise<string> {
try {
// Check whether the live view feature is enabled.
if (!await GeofenceRightsUtil.isLiveViewEnabled()) {
Logger.warn('checkRights, Live view not enabled.')
return await ContextUtil.applicationContext.resourceManager
.getStringValue($r('app.string.Live_view_enabled').id);
}
// Check whether the live view geofence feature is enabled.
if (!await GeofenceRightsUtil.isGeofenceTriggerEnabled()) {
Logger.warn('checkRights, Geofence not enabled.')
return await ContextUtil.applicationContext.resourceManager
.getStringValue($r('app.string.Live_view_geofence_enabled').id);
}
// Check whether the GPS feature is enabled.
if (!GeofenceRightsUtil.isLocationEnabled()) {
Logger.warn('checkRights, GPS not enabled.')
return await ContextUtil.applicationContext.resourceManager
.getStringValue($r('app.string.Gps_enabled').id);
}
} catch (e) {
const err: BusinessError = e as BusinessError;
Logger.error('checkRights error: %{public}d %{public}s', err.code, err.message);
return await ContextUtil.applicationContext.resourceManager
.getStringValue($r('app.string.Create_success').id);
}
return '';
}
private static async isLiveViewEnabled(): Promise<boolean> {
let result: boolean = false;
try {
result = await liveViewManager.isLiveViewEnabled();
} catch (e) {
const err: BusinessError = e as BusinessError;
Logger.error('isLiveViewEnabled error: %{public}d %{public}s', err.code, err.message);
}
Logger.info('isLiveViewEnabled result: %{public}s', result);
return result;
}
private static async isGeofenceTriggerEnabled(): Promise<boolean> {
let result: boolean = false;
try {
result = await liveViewManager.isGeofenceTriggerEnabled();
} catch (e) {
const err: BusinessError = e as BusinessError;
Logger.error('isGeofenceTriggerEnabled error: %{public}d %{public}s', err.code, err.message);
}
Logger.info('isGeofenceTriggerEnabled result: %{public}s', result);
return result;
}
private static isLocationEnabled(): boolean {
let result: boolean = false;
try {
result = geoLocationManager.isLocationEnabled();
} catch (e) {
const err: BusinessError = e as BusinessError;
Logger.error('isLocationEnabled error: %{public}d %{public}s', err.code, err.message);
}
Logger.info('isLocationEnabled result: %{public}s', result);
return result;
}
} import { common, Want, WantAgent, wantAgent } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { Logger } from './LogUtil';
export class ContextUtil {
public static wantUrl: string | undefined;
public static liveViewId: number;
public static applicationContext: common.ApplicationContext;
public static async buildWantAgent(page: string, liveViewId: number = -1): Promise<Want> {
const wantAgentInfo: wantAgent.WantAgentInfo = {
wants: [
{
bundleName: ContextUtil.applicationContext.applicationInfo.name,
abilityName: 'EntryAbility',
parameters: {
page: page,
liveViewId: liveViewId
},
} as Want
],
actionType: wantAgent.OperationType.START_ABILITIES,
requestCode: 0,
actionFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
};
try {
const agent: WantAgent = await wantAgent.getWantAgent(wantAgentInfo);
Logger.info('getWantAgent success! wantAgent: %{public}s', JSON.stringify(agent));
return agent;
} catch (e) {
const err: BusinessError = e as BusinessError;
Logger.error('getWantAgent failed! err: %{public}d %{public}s', err.code, err.message);
throw e as Error;
}
}
}

The template parameters for the capsule form are fixed and are irrelevant to the template type selected during live view creation. The following types of capsules can be created: text capsules, timer capsules, and progress capsules. For details, please refer to CapsuleData.
In addition to the widget form of live views, you also need to consider the display effect of live views in the capsule form. If you want to create a capsule simultaneously when creating a live view, include the liveViewData.capsule parameter required by the capsule in the liveViewManager.LiveView struct. (Different capsule types require different parameters.) The sample code is as follows:
import { liveViewManager } from '@kit.LiveViewKit';
import { Logger } from '../LogUtil';
import { ContextUtil } from '../ContextUtil';
import { BusinessError } from '@kit.BasicServicesKit';
export class LiveViewCapsuleController {
public async startLiveView(): Promise<boolean> {
// Check whether the live view feature is enabled.
if (!await LiveViewCapsuleController.isLiveViewEnabled()) {
Logger.warn('startLiveView, live view is disabled.');
return false;
}
// Create a live view.
try {
const defaultView = await LiveViewCapsuleController.buildDefaultView();
if (!defaultView) {
Logger.warn('buildDefaultView Failed.');
return false;
}
Logger.info('Request startLiveView req: %{public}s', JSON.stringify(defaultView));
const result = await liveViewManager.startLiveView(defaultView);
Logger.info('Request startLiveView result: %{public}s', JSON.stringify(result));
return true;
} catch (e) {
const err: BusinessError = e as BusinessError;
Logger.error('Request startLiveView error: %{public}d %{public}s', err.code, err.message);
return false;
}
}
// ...
private static async buildDefaultView(): Promise<liveViewManager.LiveView> {
return {
// Construct a live view request body.
id: 101, // Live view ID, which is generated by you.
event: 'TAXI', // Application scenario of the live view. The value TAXI indicates ride-hailing.
isMute: false,
liveViewData: {
primary: {
title: 'Driver will arrive in 5 minutes',
content: [
{ text: 'White' },
{ text: ' | ' },
{ text: 'Hu AXXXXXX', textColor: '#FF0A59F7' }
],
keepTime: 0,
clickAction: await ContextUtil.buildWantAgent('GuideCode'),
layoutData: {
layoutType: liveViewManager.LayoutType.LAYOUT_TYPE_PROGRESS,
progress: 30,
color: '#ff0959F8',
backgroundColor: '#ffc9d7e4',
indicatorType: liveViewManager.IndicatorType.INDICATOR_TYPE_UP,
// Progress indicator icon. The value is a file name under /resources/rawfile or an image.PixelMap object.
indicatorIcon: 'taxi-transport-icon.png',
lineType: liveViewManager.LineType.LINE_TYPE_NORMAL_SOLID_LINE,
// Icon of each node in the progress bar. The value of each element is a file name under /resources/rawfile or an image.PixelMap object.
nodeIcons: ['icon_order.png', 'icon_finish.png']
}
},
// Live view capsule parameters.
capsule: {
type: liveViewManager.CapsuleType.CAPSULE_TYPE_TEXT,
status: 1,
icon: 'capsule_taxi.png', // Capsule icon. The value is a file name under /resources/rawfile or an image.PixelMap object.
backgroundColor: '#ff0959F8',
title: 'On Way',
content: '3min'
}
}
};
}
private static async isLiveViewEnabled(): Promise<boolean> {
let result: boolean = false;
try {
result = await liveViewManager.isLiveViewEnabled();
} catch (e) {
const err: BusinessError = e as BusinessError;
Logger.error('Request isLiveViewEnabled error: %{public}d %{public}s', err.code, err.message);
}
Logger.info('Request isLiveViewEnabled result: %{public}s', result);
return result;
}
} import { common, Want, WantAgent, wantAgent } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { Logger } from './LogUtil';
export class ContextUtil {
public static wantUrl: string | undefined;
public static liveViewId: number;
public static applicationContext: common.ApplicationContext;
public static async buildWantAgent(page: string, liveViewId: number = -1): Promise<Want> {
const wantAgentInfo: wantAgent.WantAgentInfo = {
wants: [
{
bundleName: ContextUtil.applicationContext.applicationInfo.name,
abilityName: 'EntryAbility',
parameters: {
page: page,
liveViewId: liveViewId
},
} as Want
],
actionType: wantAgent.OperationType.START_ABILITIES,
requestCode: 0,
actionFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
};
try {
const agent: WantAgent = await wantAgent.getWantAgent(wantAgentInfo);
Logger.info('getWantAgent success! wantAgent: %{public}s', JSON.stringify(agent));
return agent;
} catch (e) {
const err: BusinessError = e as BusinessError;
Logger.error('getWantAgent failed! err: %{public}d %{public}s', err.code, err.message);
throw e as Error;
}
}
} 
A cover screen live view is used to display brief live view information on the cover screen of flip devices, allowing users to conveniently view updates while the device is folded.
If you need to create the cover screen live view simultaneously when creating a live view, include the liveViewData.external parameter in the liveViewManager.LiveView struct. The sample code is as follows:
import { liveViewManager } from '@kit.LiveViewKit';
import { Logger } from '../LogUtil';
import { ContextUtil } from '../ContextUtil';
import { BusinessError } from '@kit.BasicServicesKit';
export class LiveViewExternalController {
public async startLiveView(): Promise<boolean> {
// Check whether the live view feature is enabled.
if (!await LiveViewExternalController.isLiveViewEnabled()) {
Logger.warn('startLiveView, live view is disabled.');
return false;
}
// Create a live view.
try {
const defaultView = await LiveViewExternalController.buildDefaultView();
if (!defaultView) {
Logger.warn('buildDefaultView Failed.');
return false;
}
Logger.info('Request startLiveView req: %{public}s', JSON.stringify(defaultView));
const result = await liveViewManager.startLiveView(defaultView);
Logger.info('Request startLiveView result: %{public}s', JSON.stringify(result));
return true;
} catch (e) {
const err: BusinessError = e as BusinessError;
Logger.error('Request startLiveView error: %{public}d %{public}s', err.code, err.message);
return false;
}
}
// ...
private static async buildDefaultView(): Promise<liveViewManager.LiveView> {
return {
// Construct a live view request body.
id: 102, // Live view ID, which is generated by you.
event: 'FLIGHT', // Application scenario of the live view. The value FLIGHT indicates flight.
isMute: false,
liveViewData: {
primary: {
title: 'Flight XXX has checked in',
content: [
{ text: 'Gate', },
{ text: '27 17:45', textColor: '#FFFF9C4F' },
{ text: 'Boarding now' }
], // If textColor is set for some objects in the array, its values for all these objects must be the same. If textColor is not set for an object in the array, the default text color #FF000000 will be used.
keepTime: 0,
clickAction: await ContextUtil.buildWantAgent('GuideCode'),
layoutData: {
layoutType: liveViewManager.LayoutType.LAYOUT_TYPE_FLIGHT,
firstTitle: '18:15',
firstContent: 'Shanghai',
lastTitle: '20:30',
lastContent: 'Chengdu',
spaceIcon: 'icon_plane.png', // Spacing icon in the middle of the extension area. The value is a file name under /resources/rawfile or an image.PixelMap object.
isHorizontalLineDisplayed: true,
additionalText: 'The preceding information is for reference only.' // Content at the bottom of the extension area, which can be used only for the left-right text template.
}
},
external: {
title: 'Checked in',
content: [
{ text: 'Gate' },
{ text: '27\n', textColor: '#FFFF9C4F' },
{ text: '17:45', textColor: '#FFFF9C4F' },
{ text: 'Boarding now' }
],
type: liveViewManager.ExternalType.BACKGROUND_PICTURE, // Background style of the live view on the cover screen.
backgroundPicture: 'airplane.png' // Background image of the live view on the cover screen. The value is a file name under /resources/rawfile or an image.PixelMap object.
}
}
};
}
private static async isLiveViewEnabled(): Promise<boolean> {
let result: boolean = false;
try {
result = await liveViewManager.isLiveViewEnabled();
} catch (e) {
const err: BusinessError = e as BusinessError;
Logger.error('Request isLiveViewEnabled error: %{public}d %{public}s', err.code, err.message);
}
Logger.info('Request isLiveViewEnabled result: %{public}s', result);
return result;
}
} import { common, Want, WantAgent, wantAgent } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { Logger } from './LogUtil';
export class ContextUtil {
public static wantUrl: string | undefined;
public static liveViewId: number;
public static applicationContext: common.ApplicationContext;
public static async buildWantAgent(page: string, liveViewId: number = -1): Promise<Want> {
const wantAgentInfo: wantAgent.WantAgentInfo = {
wants: [
{
bundleName: ContextUtil.applicationContext.applicationInfo.name,
abilityName: 'EntryAbility',
parameters: {
page: page,
liveViewId: liveViewId
},
} as Want
],
actionType: wantAgent.OperationType.START_ABILITIES,
requestCode: 0,
actionFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
};
try {
const agent: WantAgent = await wantAgent.getWantAgent(wantAgentInfo);
Logger.info('getWantAgent success! wantAgent: %{public}s', JSON.stringify(agent));
return agent;
} catch (e) {
const err: BusinessError = e as BusinessError;
Logger.error('getWantAgent failed! err: %{public}d %{public}s', err.code, err.message);
throw e as Error;
}
}
} The live view timer is applicable to scenarios such as queuing and ticket snatching.
To use a live view timer, you need to configure the timer field in the liveViewManager.LiveView struct and use the ${placeholder.timer} placeholder in the text fields that support it.
For example, when you use the ${placeholder.timer} placeholder in the text content of the fixed area, the system will automatically replace it with the real-time value of the live view timer.

The sample code is as follows:
After building LiveViewController, initialize it in the code and call the LiveViewController.startLiveView() method.
import { liveViewManager } from '@kit.LiveViewKit';
import { Logger } from '../LogUtil';
import { ContextUtil } from '../ContextUtil';
import { BusinessError } from '@kit.BasicServicesKit';
export class QueueLiveViewController {
public async startLiveView(): Promise<boolean> {
// Check whether the live view feature is enabled.
if (!await QueueLiveViewController.isLiveViewEnabled()) {
Logger.warn('startLiveView, live view is disabled.');
return false;
}
// Create a live view.
try {
const defaultView = await QueueLiveViewController.buildDefaultView();
if (!defaultView) {
Logger.warn('buildDefaultView Failed.');
return false;
}
Logger.info('Request startLiveView req: %{public}s', JSON.stringify(defaultView));
const result = await liveViewManager.startLiveView(defaultView);
Logger.info('Request startLiveView result: %{public}s', JSON.stringify(result));
return true;
} catch (e) {
const err: BusinessError = e as BusinessError;
Logger.error('Request startLiveView error: %{public}d %{public}s', err.code, err.message);
return false;
}
}
// ...
private static async buildDefaultView(): Promise<liveViewManager.LiveView> {
return {
// Construct a live view request body.
id: 107, // Live view ID, which is generated by you.
event: 'QUEUE', // Application scenario of the live view. The value QUEUE indicates queuing.
isMute: false,
timer: {
time: 300000,
isCountdown: false,
isPaused: false
},
liveViewData: {
primary: {
title: '4 people ahead | A32',
content: [
{ text: 'Waited ' },
{ text: ' ${placeholder.timer}', textColor: '#ff10c1f7' },
{ text: 'min | Remaining time: > 30 minutes' }
],
keepTime: 0,
clickAction: await ContextUtil.buildWantAgent('GuideCode'),
layoutData: {
layoutType: liveViewManager.LayoutType.LAYOUT_TYPE_PROGRESS,
progress: 40,
color: '#FF317AF7',
backgroundColor: '#f7819ae0',
indicatorType: liveViewManager.IndicatorType.INDICATOR_TYPE_UNDISPLAYED,
lineType: liveViewManager.LineType.LINE_TYPE_DOTTED_LINE,
nodeIcons: ['icon_order.png', 'icon_finish.png']
}
}
}
};
}
private static async isLiveViewEnabled(): Promise<boolean> {
let result: boolean = false;
try {
result = await liveViewManager.isLiveViewEnabled();
} catch (e) {
const err: BusinessError = e as BusinessError;
Logger.error('Request isLiveViewEnabled error: %{public}d %{public}s', err.code, err.message);
}
Logger.info('Request isLiveViewEnabled result: %{public}s', result);
return result;
}
} import { common, Want, WantAgent, wantAgent } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { Logger } from './LogUtil';
export class ContextUtil {
public static wantUrl: string | undefined;
public static liveViewId: number;
public static applicationContext: common.ApplicationContext;
public static async buildWantAgent(page: string, liveViewId: number = -1): Promise<Want> {
const wantAgentInfo: wantAgent.WantAgentInfo = {
wants: [
{
bundleName: ContextUtil.applicationContext.applicationInfo.name,
abilityName: 'EntryAbility',
parameters: {
page: page,
liveViewId: liveViewId
},
} as Want
],
actionType: wantAgent.OperationType.START_ABILITIES,
requestCode: 0,
actionFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
};
try {
const agent: WantAgent = await wantAgent.getWantAgent(wantAgentInfo);
Logger.info('getWantAgent success! wantAgent: %{public}s', JSON.stringify(agent));
return agent;
} catch (e) {
const err: BusinessError = e as BusinessError;
Logger.error('getWantAgent failed! err: %{public}d %{public}s', err.code, err.message);
throw e as Error;
}
}
} Call wantAgent.getWantAgent() to construct the parameter values for the action to be triggered upon live view tapping. Currently, the live view supports the following actions:
After calling liveViewManager.isLiveViewEnabled() to verify that the live view feature is enabled, you can call updateLiveView of liveViewManager to update the live view and call stopLiveView to end the live view. You need to modify the corresponding parameters in the request body when updating the live view. The sample code is as follows:
import { liveViewManager } from '@kit.LiveViewKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { ContextUtil } from './ContextUtil';
import { ImageUtil } from './ImageUtil'
import { Logger } from './LogUtil';
export class PickLiveViewController {
private static defaultView: liveViewManager.LiveView | undefined = undefined;
private static contentColor: string = '#FF0A59F7';
private static underLineColor: string = '#FF0A59F7';
private static capsuleColor: string = '#FF308977';
public async startLiveView(): Promise<boolean> {
// Check whether the live view feature is enabled.
if (!await PickLiveViewController.isLiveViewEnabled()) {
return false;
}
// Construct a live view object.
PickLiveViewController.defaultView = await PickLiveViewController.buildDefaultView();
if (!PickLiveViewController.defaultView) {
return false;
}
// Create a live view.
try {
const result = await liveViewManager.startLiveView(PickLiveViewController.defaultView);
} catch (e) {
const err: BusinessError = e as BusinessError;
return false;
}
return true;
}
public async updateLiveView(): Promise<boolean> {
try {
// Check whether the live view feature is enabled.
if (!PickLiveViewController.defaultView) {
return false;
}
// Modify the live view content.
PickLiveViewController.defaultView.isMute = false;
PickLiveViewController.defaultView.liveViewData.primary.title =
await ContextUtil.applicationContext.resourceManager
.getStringValue($r('app.string.Pick_wait_primary_title').id);
PickLiveViewController.defaultView.liveViewData.primary.content = [
{
text: await ContextUtil.applicationContext.resourceManager
.getStringValue($r('app.string.Pick_wait_primary_content').id)
}
];
PickLiveViewController.defaultView.liveViewData.primary.layoutData = {
layoutType: liveViewManager.LayoutType.LAYOUT_TYPE_PICKUP,
title: await ContextUtil.applicationContext.resourceManager
.getStringValue($r('app.string.Pick_wait_layout_title').id),
content: await ContextUtil.applicationContext.resourceManager
.getStringValue($r('app.string.Pick_wait_layout_content').id),
underlineColor: PickLiveViewController.underLineColor,
descPic: 'coffee.png'
};
PickLiveViewController.defaultView.liveViewData.capsule = {
type: liveViewManager.CapsuleType.CAPSULE_TYPE_TEXT,
status: 1,
icon: 'capsule_to_pick.png',
backgroundColor: PickLiveViewController.capsuleColor,
title: await ContextUtil.applicationContext.resourceManager
.getStringValue($r('app.string.Pick_wait_capsule_title').id)
}
// Update the live view.
const result = await liveViewManager.updateLiveView(PickLiveViewController.defaultView);
return true;
} catch (e) {
const err: BusinessError = e as BusinessError;
return false;
}
}
public async stopLiveView(): Promise<void> {
try {
// Check whether the live view feature is enabled.
if (!await PickLiveViewController.isLiveViewEnabled() || !PickLiveViewController.defaultView) {
return;
}
// Modify the live view content.
PickLiveViewController.defaultView.liveViewData.primary.title =
await ContextUtil.applicationContext.resourceManager
.getStringValue($r('app.string.Pick_finished_primary_title').id);
PickLiveViewController.defaultView.liveViewData.primary.content = [
{
text: await ContextUtil.applicationContext.resourceManager
.getStringValue($r('app.string.Pick_finished_primary_content1').id)
},
{
text: await ContextUtil.applicationContext.resourceManager
.getStringValue($r('app.string.Pick_finished_primary_content2').id)
}
];
PickLiveViewController.defaultView.liveViewData.primary.layoutData = {
layoutType: liveViewManager.LayoutType.LAYOUT_TYPE_PICKUP,
title: await ContextUtil.applicationContext.resourceManager.getStringValue($r('app.string.Pick_finished_primary_layout_title')
.id),
content: await ContextUtil.applicationContext.resourceManager.getStringValue($r('app.string.Pick_finished_primary_layout_content')
.id),
underlineColor: PickLiveViewController.underLineColor,
descPic: 'icon_store.png'
}
// End the live view.
const result = await liveViewManager.stopLiveView(PickLiveViewController.defaultView);
} catch (e) {
const err: BusinessError = e as BusinessError;
Logger.error('Request stopLiveView error: %{public}d %{public}s', err.code, err.message);
}
}
private static async isLiveViewEnabled(): Promise<boolean> {
// Check whether the live view feature is enabled.
let result: boolean = false;
try {
result = await liveViewManager.isLiveViewEnabled();
} catch (e) {
const err: BusinessError = e as BusinessError;
Logger.error('Request isLiveViewEnabled error: %{public}d %{public}s', err.code, err.message);
}
return result;
}
private static async buildDefaultView(): Promise<liveViewManager.LiveView | undefined> {
try {
return {
id: 10, // Live view ID, which is generated by you.
event: 'PICK_UP', // Application scenario of the live view. The value PICK_UP indicates meal pickup.
liveViewData: {
primary: {
title: await ContextUtil.applicationContext.resourceManager
.getStringValue($r('app.string.Delivery_default_primary_title').id),
content: [
{
text: await ContextUtil.applicationContext.resourceManager.getStringValue($r('app.string.Delivery_default_primary_content1')
.id),
textColor: PickLiveViewController.contentColor
},
{
text: ' ' +
await ContextUtil.applicationContext.resourceManager.getStringValue($r('app.string.Delivery_default_primary_content2')
.id)
}
], // If textColor is set for some objects in the array, its values for all these objects must be the same. If textColor is not set for an object in the array, the default text color #FF000000 will be used.
keepTime: 15,
clickAction: await ContextUtil.buildWantAgent('PickUp'),
extensionData: {
// Auxiliary area.
type: liveViewManager.ExtensionType.EXTENSION_TYPE_ICON,
pic: await ImageUtil.getNetworkPicture('', 'icon_merchant.png'),
clickAction: await ContextUtil.buildWantAgent('PickUp')
},
layoutData: {
// Extension area.
layoutType: liveViewManager.LayoutType.LAYOUT_TYPE_PICKUP,
title: await ContextUtil.applicationContext.resourceManager.getStringValue($r('app.string.Delivery_default_layout_title')
.id),
content: await ContextUtil.applicationContext.resourceManager.getStringValue($r('app.string.Delivery_default_layout_content')
.id),
underlineColor: PickLiveViewController.underLineColor,
descPic: 'coffee.png'
},
},
capsule: {
// Live view capsule.
type: liveViewManager.CapsuleType.CAPSULE_TYPE_TEXT,
status: 1,
icon: 'capsule_purse.png',
backgroundColor: PickLiveViewController.capsuleColor,
title: await ContextUtil.applicationContext.resourceManager.getStringValue($r('app.string.Delivery_default_capsule_title')
.id)
}
}
}
} catch (e) {
return undefined;
}
}
} import { common, Want, WantAgent, wantAgent } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { Logger } from './LogUtil';
export class ContextUtil {
public static wantUrl: string | undefined;
public static liveViewId: number;
public static applicationContext: common.ApplicationContext;
public static async buildWantAgent(page: string, liveViewId: number = -1): Promise<Want> {
const wantAgentInfo: wantAgent.WantAgentInfo = {
wants: [
{
bundleName: ContextUtil.applicationContext.applicationInfo.name,
abilityName: 'EntryAbility',
parameters: {
page: page,
liveViewId: liveViewId
},
} as Want
],
actionType: wantAgent.OperationType.START_ABILITIES,
requestCode: 0,
actionFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
};
try {
const agent: WantAgent = await wantAgent.getWantAgent(wantAgentInfo);
Logger.info('getWantAgent success! wantAgent: %{public}s', JSON.stringify(agent));
return agent;
} catch (e) {
const err: BusinessError = e as BusinessError;
Logger.error('getWantAgent failed! err: %{public}d %{public}s', err.code, err.message);
throw e as Error;
}
}
} For details about the parameters, please refer to Live View Kit ArkTS API Reference.
This section describes the entire process of creating, updating, and ending a live view locally. For details about how an app ends a live view locally, please refer to Live View Lifecycle. You may also use Push Kit to remotely create, update, and end live view messages.