介紹
本篇Codelab基于柵格布局、設備管理和多端協同,實現一次開發,多端部署的分布式新聞客戶端頁面。主要包含以下功能:
- 展示新聞列表以及左右滑動切換新聞Tab。
- 點擊新聞展示新聞詳情頁。
- 點擊新聞詳情頁底部的分享按鈕,發現周邊處在同一無線網絡下的設備并進行可信認證連接。
- 可信認證后,再次點擊分享按鈕,選擇已連接的設備進行跨設備啟動UIAbility。
最終效果圖如下:
相關概念
- [柵格布局]:一種通用的輔助定位工具,解決多尺寸多設備的動態布局問題。
- [設備管理]:模塊提供分布式設備管理能力。
- [跨設備啟動UIAbility]:多端上的不同UIAbility/ServiceExtensionAbility同時運行、或者交替運行實現完整的業務。
- [Tabs組件]:通過頁簽進行內容視圖切換的容器組件,每個頁簽對應一個內容視圖。
相關權限
本篇Codelab使用了設備管理及跨設備實現多端協同能力,需要手動替換full-SDK,并在配置文件module.json5文件requestPermissions屬性中添加如下權限:
- [分布式設備認證組網權限]:ohos.permission.ACCESS_SERVICE_DM。
- [設備間的數據交換權限]:ohos.permission.DISTRIBUTED_DATASYNC。
約束與限制
- 本篇Codelab部分能力依賴于系統API,需下載full-SDK并替換DevEco Studio自動下載的public-SDK。具體操作可參考指南[《如何替換full-SDK》]。
- 本篇Codelab使用的部分API僅系統應用可用,需要提升應用等級。
環境搭建
軟件要求
- [DevEco Studio]版本:DevEco Studio 4.0 Beta2。
- OpenHarmony SDK版本:API version 10。
- 鴻蒙開發文檔指導:[
qr23.cn/AKFP8k
]
硬件要求
- 開發板類型:[潤和RK3568開發板]。
- OpenHarmony系統:4.0 Beta1。
環境搭建
完成本篇Codelab我們首先要完成開發環境的搭建,本示例以RK3568開發板為例,參照以下步驟進行:
- [獲取OpenHarmony系統版本]:標準系統解決方案(二進制)。以4.0 Beta1版本為例:
- 搭建燒錄環境。
- [完成DevEco Device Tool的安裝]
- [完成RK3568開發板的燒錄]
- 搭建開發環境。
- 開始前請參考[工具準備],完成DevEco Studio的安裝和開發環境配置。
- 開發環境配置完成后,請參考[使用工程向導]創建工程(模板選擇“Empty Ability”)。
- 工程創建完成后,選擇使用[真機進行調測]。
代碼結構解讀
本篇Codelab只對核心代碼進行講解,對于完整代碼,我們會在gitee中提供。
├──entry/src/main/ets // 代碼區
│ ├──common
│ │ ├──constants
│ │ │ └──CommonConstants.ets // 常量類
│ │ └──utils
│ │ └──Logger.ets // 日志工具類
│ ├──entryability
│ │ └──EntryAbility.ets // 程序入口類
│ ├──model
│ │ └──RemoteDeviceModel.ets // 設備管理類
│ ├──pages
│ │ ├──Index.ets // 新聞列表頁
│ │ └──NewsDetail.ets // 新聞詳情頁
│ ├──view
│ │ ├──DetailFooter.ets // 詳情頁頁腳
│ │ ├──DetailHeadContent.ets // 新聞詳情
│ │ ├──DeviceListDialog.ets // 設備列表彈窗
│ │ ├──NewsList.ets // 新聞列表
│ │ └──NewsTab.ets // 新聞頁簽
│ └──viewmodel
│ └──NewsDataModel.ets // 新聞數據處理
└──entry/src/main/resources // 資源文件目錄
構建新聞列表頁
新聞列表頁由頁簽區域和新聞列表區域組成,頁簽區域為自定義布局TabBuilder,新聞列表區域為Tabs組件嵌套List組件,并適配不同尺寸設備對應的柵格。新聞列表頁能夠左右滑動或點擊頁簽切換新聞Tab,并設置點擊新聞跳轉至新聞詳情頁。
// NewsTab.ets
@Component
export default struct NewsTab {
@State currentIndex: number = 0;
@State currentBreakpoint: string = CommonConstants.BREAKPOINT_SM;
private newsItems: NewsData[] = [];
// 自定義頁簽欄
@Builder TabBuilder(title: Resource, index: number) {
Row() {
Text(title)
.fontSize(this.currentIndex === index ? $r('app.float.lager_font_size') : $r('app.float.middle_font_size'))
.fontWeight(this.currentIndex === index ? CommonConstants.FONT_WEIGHT_500 : FontWeight.Normal)
.fontColor(this.currentIndex === index ? $r('app.color.tab_font_select') : $r('app.color.font_color_gray'))
}
.layoutWeight(1)
.margin({
right: $r('app.float.news_tab_margin_right'),
left: (this.currentBreakpoint === CommonConstants.BREAKPOINT_SM && index === 0) ?
$r('app.float.news_tab_margin_left') : 0
})
.height(this.currentIndex === index ? $r('app.float.news_tab_current_height') : $r('app.float.news_tab_height'))
}
build() {
...
Tabs() {
ForEach(CommonConstants.ALL_TITLE, (title: string, index: number) = > {
TabContent() {
// 新聞內容列表
NewsList({ newsItems: NewsDataModel.getNewsByType(this.newsItems, title) })
}
.tabBar(this.TabBuilder(NewsDataModel.getTypeByStr(title), index))
}, (title: string, index: number) = > index + JSON.stringify(title))
}
.barHeight($r('app.float.news_tab_bar_height'))
.barWidth(CommonConstants.FULL_COMPONENT)
.barMode(this.currentBreakpoint === CommonConstants.BREAKPOINT_SM ? BarMode.Scrollable : BarMode.Fixed)
.onChange((index: number) = > {
this.currentIndex = index;
})
...
}
}
// NewsList.ets
@Component
export default struct NewsList {
private newsItems: NewsData[] = [];
build() {
List() {
ForEach(this.newsItems, (item: NewsData, index: number) = > {
ListItem() {
// 柵格布局
GridRow({
columns: {
sm: CommonConstants.FOUR_COLUMN,
md: CommonConstants.EIGHT_COLUMN,
lg: CommonConstants.TWELVE_COLUMN
},
breakpoints: {
value: [
CommonConstants.SMALL_DEVICE_TYPE,
CommonConstants.MIDDLE_DEVICE_TYPE,
CommonConstants.LARGE_DEVICE_TYPE
]
},
gutter: { x: $r('app.float.grid_row_gutter') }
}) {
GridCol({
span: {
sm: CommonConstants.FOUR_COLUMN,
md: CommonConstants.EIGHT_COLUMN,
lg: CommonConstants.EIGHT_COLUMN
},
offset: {
sm: CommonConstants.ZERO_COLUMN,
md: CommonConstants.ZERO_COLUMN,
lg: CommonConstants.TWO_COLUMN
}
}) {
NewsItem({ newsItem: item, isLast: index === this.newsItems.length - 1 })
}
}
}
}, (item: NewsData, index: number) = > index + JSON.stringify(item))
}
.height(CommonConstants.FULL_COMPONENT)
}
}
[](https://gitee.com/openharmony/codelabs/tree/master/Distributed/DistributedNewsClient#%E6%9E%84%E5%BB%BA%E6%96%B0%E9%97%BB%E8%AF%A6%E6%83%85%E9%A1%B5)構建新聞詳情頁
[](https://gitee.com/openharmony/codelabs/tree/master/Distributed/DistributedNewsClient#%E6%96%B0%E9%97%BB%E8%AF%A6%E6%83%85%E9%A1%B5)新聞詳情頁
新聞詳情頁由新聞內容區域和頁腳區域組成,其中新聞內容區域為Scroll組件嵌套柵格組件展示新聞詳情,頁腳區域為柵格布局,包含TextInput組件和三個按鈕圖標。
// DetailHeadContent.ets
build() {
Column() {
...
// 可滾動的容器組件
Scroll() {
// 柵格布局
GridRow({
columns: {
sm: CommonConstants.FOUR_COLUMN,
md: CommonConstants.EIGHT_COLUMN,
lg: CommonConstants.TWELVE_COLUMN
},
breakpoints: {
value: [
CommonConstants.SMALL_DEVICE_TYPE,
CommonConstants.MIDDLE_DEVICE_TYPE,
CommonConstants.LARGE_DEVICE_TYPE
]
},
gutter: { x: $r('app.float.grid_row_gutter') }
}) {
GridCol({
span: {
sm: CommonConstants.FOUR_COLUMN,
md: CommonConstants.EIGHT_COLUMN,
lg: CommonConstants.EIGHT_COLUMN
},
offset: {
sm: CommonConstants.ZERO_COLUMN,
md: CommonConstants.ZERO_COLUMN,
lg: CommonConstants.TWO_COLUMN
}
}) {
...
}
...
}
}
.padding({
bottom: $r('app.float.news_detail_padding_bottom')
})
.scrollBar(BarState.Off)
}
.margin({
left: $r('app.float.news_detail_margin'),
right: $r('app.float.news_detail_margin')
})
.height(CommonConstants.FULL_COMPONENT)
.alignItems(HorizontalAlign.Start)
}
// DetailFooter.ets
build() {
Column() {
// 分割線
Divider()
.color($r('app.color.detail_divider_color'))
.width(CommonConstants.FULL_COMPONENT)
// 柵格布局
GridRow({
columns: {
sm: CommonConstants.FOUR_COLUMN,
md: CommonConstants.EIGHT_COLUMN,
lg: CommonConstants.TWELVE_COLUMN
},
breakpoints: {
value: [
CommonConstants.SMALL_DEVICE_TYPE,
CommonConstants.MIDDLE_DEVICE_TYPE,
CommonConstants.LARGE_DEVICE_TYPE
]
},
gutter: { x: $r('app.float.grid_row_gutter') }
}) {
GridCol({
span: {
sm: CommonConstants.FOUR_COLUMN,
md: CommonConstants.EIGHT_COLUMN,
lg: CommonConstants.EIGHT_COLUMN
},
offset: {
sm: CommonConstants.ZERO_COLUMN,
md: CommonConstants.ZERO_COLUMN,
lg: CommonConstants.TWO_COLUMN
}
}) {
...
}
.margin({
left: this.currentBreakpoint === CommonConstants.BREAKPOINT_SM ? $r('app.float.footer_margin_sm') :
$r('app.float.footer_margin_other'),
right: this.currentBreakpoint === CommonConstants.BREAKPOINT_SM ? $r('app.float.footer_margin_sm') :
$r('app.float.footer_margin_other')
})
}
.backgroundColor($r('app.color.bg_color_gray'))
.height($r('app.float.footer_height'))
.width(CommonConstants.FULL_COMPONENT)
.onBreakpointChange((breakpoints) = > {
...
})
}
}
分享按鈕彈窗
頁腳點擊分享按鈕,彈出自定義彈窗DeviceListDialog,用于多端協同拉起應用。DeviceListDialog由兩個標題欄和兩個List組件構成,其中List組件使用ForEach循環渲染設備數據。
// DeviceListDialog.ets
build() {
Column() {
Row() {
...
}
.height($r('app.float.choose_device_row_height'))
.width(CommonConstants.FULL_COMPONENT)
.padding({
left: $r('app.float.dialog_padding'),
right: $r('app.float.dialog_padding')
})
// 信任設備列表
List() {
ForEach(this.trustedDeviceList, (item: deviceManager.DeviceInfo, index: number) = > {
ListItem() {
...
}
}, (item: deviceManager.DeviceInfo) = > JSON.stringify(item.deviceId))
}
Row() {
...
}
.height($r('app.float.choose_device_row_height'))
.width(CommonConstants.FULL_COMPONENT)
.padding({
left: $r('app.float.dialog_padding'),
right: $r('app.float.dialog_padding')
})
// 發現設備列表
List() {
ForEach(this.discoverDeviceList, (item: deviceManager.DeviceInfo, index: number) = > {
ListItem() {
...
}
}, (item: deviceManager.DeviceInfo) = > JSON.stringify(item.deviceId))
}
Row() {
...
}
.height($r('app.float.dialog_button_row_height'))
.padding({
top: $r('app.float.dialog_button_padding_top'),
bottom: $r('app.float.dialog_button_padding_bottom'),
left: $r('app.float.dialog_padding'),
right: $r('app.float.dialog_padding')
})
.width(CommonConstants.FULL_COMPONENT)
}
.borderRadius($r('app.float.dialog_border_radius'))
.backgroundColor($r('app.color.device_dialog_background'))
.width(CommonConstants.FULL_COMPONENT)
}
多端協同拉起應用
創建設備管理器
應用創建時創建一個設備管理器實例,注冊設備狀態監聽和獲取信任的設備列表。其中deviceManager類需使用full-SDK。
// EntryAbility.ets
onCreate(want: Want) {
...
// 創建設備管理器
RemoteDeviceModel.createDeviceManager(this.context);
}
// RemoteDeviceModel.ets
async createDeviceManager(context: common.UIAbilityContext): Promise< void > {
if (this.deviceManager !== undefined) {
return;
}
await new Promise((resolve: (value: Object | PromiseLike< Object >) = > void, reject:
((reason?: RejectError) = > void)) = > {
deviceManager.createDeviceManager(context.abilityInfo.bundleName, (err, value) = > {
if (err) {
reject(err);
logger.error('createDeviceManager failed.');
return;
}
this.deviceManager = value;
// 注冊設備狀態監聽
this.registerDeviceStateListener();
// 獲取信任設備列表
this.getTrustedDeviceList();
resolve(value);
})
})
}
發現設備
用戶點擊新聞詳情頁底部的分享按鈕,調用startDeviceDiscovery()方法,發現周邊處在同一無線網絡下的設備并添加設備至已發現的設備列表。
// RemoteDeviceModel.ets
startDeviceDiscovery(): void {
if (this.deviceManager === undefined) {
logger.error('deviceManager has not initialized');
this.showToast($r('app.string.no_device_manager'));
return;
}
this.deviceManager.on('deviceFound', (data) = > {
if (data === null) {
return;
}
// 監聽設備發現
this.deviceFound(data);
})
this.deviceManager.on('discoverFail', (data) = > {
logger.error(`discoverFail data = ${JSON.stringify(data)}`);
})
this.deviceManager.on('serviceDie', () = > {
logger.error('serviceDie');
})
let info: deviceManager.SubscribeInfo = {
subscribeId: SUBSCRIBE_ID,
mode: CommonConstants.INFO_MODE,
medium: 0,
freq: CommonConstants.INFO_FREQ,
isSameAccount: false,
isWakeRemote: true,
capability: 0
};
// 添加設備至發現列表
this.discoverList = [];
AppStorage.setOrCreate(CommonConstants.DISCOVER_DEVICE_LIST, this.discoverList);
try {
this.deviceManager.startDeviceDiscovery(info);
} catch (err) {
logger.error(`startDeviceDiscovery failed error = ${JSON.stringify(err)}`);
}
}
進行可信認證連接
在已發現的設備列表中選擇設備,調用authenticateDevice()方法進行可信認證,輸入PIN碼,連接設備,將設備改為信任狀態,添加至已信任設備列表。
// RemoteDeviceModel.ets
authenticateDevice(device: deviceManager.DeviceInfo, context: common.UIAbilityContext): void {
if (this.deviceManager === undefined) {
logger.error('deviceManager has not initialized');
this.showToast($r('app.string.no_device_manager'));
return;
}
for (let i: number = 0; i < this.discoverList.length; i++) {
if (this.discoverList[i].deviceId !== device.deviceId) {
continue;
}
let extraInfo: AuthExtraInfoInterface = {
targetPkgName: context.abilityInfo.bundleName,
appName: context.applicationInfo.name,
appDescription: context.applicationInfo.description,
business: CommonConstants.ZERO
};
let authParam: deviceManager.AuthParam = {
'authType': CommonConstants.ONE,
'extraInfo': extraInfo
};
try {
// 可信認證
this.deviceManager.authenticateDevice(device, authParam, (err) = > {
if (err) {
logger.error(`authenticateDevice error. Code is ${err.code}, message is ${err.message}`);
return;
}
})
} catch (err) {
logger.error(`authenticateDevice failed error = ${JSON.stringify(err)}`);
}
}
}
跨設備啟動UIAbility
可信認證后,用戶再次點擊分享按鈕,選擇已信任設備列表中的設備,調用startAbilityContinuation()方法進行拉起應用,在另一設備中觸發aboutToAppear()方法渲染當前的新聞詳情頁,實現跨設備啟動UIAbility。
// DeviceListDialog.ets
function startAbilityContinuation(deviceId: string, newsId: string, context: common.UIAbilityContext): void {
let want: Want = {
deviceId: deviceId,
bundleName: context.abilityInfo.bundleName,
abilityName: CommonConstants.ABILITY_NAME,
parameters: {
newsId: newsId
}
};
// 拉起應用
context.startAbility(want).catch((err: Error) = > {
Logger.error(`startAbilityContinuation failed error = ${JSON.stringify(err)}`);
prompt.showToast({
message: $r('app.string.start_ability_continuation_error')
});
})
}
// NewsDetail.ets
aboutToAppear() {
let newsId: string | undefined = AppStorage.get< string >('wantNewsId');
if (newsId === undefined) {
this.newsData = (router.getParams() as Record< string, NewsData >)['newsItem'];
return;
}
// 讀取跨設備傳遞的參數信息
this.newsData = this.newsItems.filter((item: NewsData) = > (item.newsId === newsId))[0];
}
審核編輯 黃宇
-
分布式
+關注
關注
1文章
924瀏覽量
74610 -
鴻蒙
+關注
關注
57文章
2392瀏覽量
43050 -
HarmonyOS
+關注
關注
79文章
1982瀏覽量
30574 -
OpenHarmony
+關注
關注
25文章
3744瀏覽量
16577
發布評論請先 登錄
相關推薦
評論