鴻蒙元服務(wù)開(kāi)發(fā)實(shí)例:桌面卡片上的電動(dòng)自行車助手E-Bike
想了解更多關(guān)于開(kāi)源的內(nèi)容,請(qǐng)?jiān)L問(wèn):
一、元服務(wù)E-Bike簡(jiǎn)介
E-Bike是一款基于HarmonyOS開(kāi)發(fā)的元服務(wù),以萬(wàn)能卡片的形式給騎行提供便捷服務(wù),主要功能包括:
- 車輛狀態(tài)信息獲?。河脩艨稍谠?wù)內(nèi)連接電動(dòng)自行車(真機(jī)和自行車自備),查看車輛位置、剩余電量、續(xù)航里程以及累計(jì)騎行里程。
- 包括響鈴找車功能:按鈕可觸發(fā)車輛鳴響,便于快速確認(rèn)車輛具體位置(真機(jī)和自行車自備)。
- 用戶可通過(guò)右上角按鈕添加2x2或2x4卡片,在桌面可直接查看車輛狀態(tài)信息。
鴻蒙元服務(wù)開(kāi)發(fā)實(shí)例:桌面卡片上的電動(dòng)自行車助手E-Bike-開(kāi)源基礎(chǔ)軟件社區(qū)
二、環(huán)境搭建
首先需要完成HarmonyOS開(kāi)發(fā)環(huán)境搭建。E-Bike是元服務(wù),且為端云一體化開(kāi)發(fā)模式,新建工程可可參照如圖步驟進(jìn)行(注意該模式下APP為Stage模型)。
鴻蒙元服務(wù)開(kāi)發(fā)實(shí)例:桌面卡片上的電動(dòng)自行車助手E-Bike-開(kāi)源基礎(chǔ)軟件社區(qū)
鴻蒙元服務(wù)開(kāi)發(fā)實(shí)例:桌面卡片上的電動(dòng)自行車助手E-Bike-開(kāi)源基礎(chǔ)軟件社區(qū)
軟件要求
- DevEco Studio版本:DevEco Studio 3.1 Release及以上版本。
- HarmonyOS SDK版本:API version 9及以上版本。
硬件要求
- 設(shè)備類型:華為手機(jī)或運(yùn)行在DevEco Studio上的華為手機(jī)設(shè)備模擬器。
- HarmonyOS系統(tǒng):3.1.0 Developer Release及以上版本。
- 電動(dòng)自行車(獲取真實(shí)車輛數(shù)據(jù),車輛為作者自制)
環(huán)境搭建
安裝DevEco Studio,詳情請(qǐng)參考下載和安裝軟件。
設(shè)置DevEco Studio開(kāi)發(fā)環(huán)境,DevEco Studio開(kāi)發(fā)環(huán)境需要依賴于網(wǎng)絡(luò)環(huán)境,需要連接上網(wǎng)絡(luò)才能確保工具的正常使用,可以根據(jù)如下兩種情況來(lái)配置開(kāi)發(fā)環(huán)境:
- 如果可以直接訪問(wèn)Internet,只需進(jìn)行下載HarmonyOS SDK操作。
- 如果網(wǎng)絡(luò)不能直接訪問(wèn)Internet,需要通過(guò)代理服務(wù)器才可以訪問(wèn),請(qǐng)參考配置開(kāi)發(fā)環(huán)境。
開(kāi)發(fā)者可以參考以下鏈接,完成設(shè)備調(diào)試的相關(guān)配置:使用真機(jī)進(jìn)行調(diào)試使用模擬器進(jìn)行調(diào)試
三、代碼結(jié)構(gòu)解讀
本篇教程只對(duì)E-Bike實(shí)現(xiàn)的核心代碼進(jìn)行講解,對(duì)于完整代碼,會(huì)在源碼下載或gitee中提供。主要的程序框架如下:
entry\src\main\ets
│ ├─common–通用常量和數(shù)據(jù)
│ ├─entryability – EntryAbility.ts 程序入口
│ ├─entryformability–EntryFormAbility.ts卡片入口
│ ├─pages—Index.ts 應(yīng)用主頁(yè)
│ ├─services
│ ├─widget
│ │ └─pages—2x2 ArkTS卡片
│ └─widget24
│ └─pages—2x4卡片
└─resources —資源文件目錄
四、應(yīng)用主頁(yè)面UI和功能開(kāi)發(fā)
1、主頁(yè)面UI
新建工程后,在entry\src\main\ets\pages\Index.ts文件中已有一個(gè)模板案例,我們需要?jiǎng)h除其中的代碼,然后構(gòu)建自己的頁(yè)面。具體實(shí)現(xiàn)方法是:
- 刪除build() { }中的代碼。
- 使用Column、Flex、Row容器和Button、Image、Text組件構(gòu)建E-Bike布局。
- 在UI中加入邏輯判斷具體要顯示的UI組件。如響鈴找車的Image組件內(nèi)容由用戶的點(diǎn)擊狀態(tài)決定,點(diǎn)擊響鈴找車則Image切換為響鈴狀態(tài),反之亦然。
具體代碼實(shí)現(xiàn)框架如下:
@Entry @Component struct Index {
build() { Column({space:10})
{
// 背景圖
Image($r("app.media.Ebike"))
···
Flex()
{
// 響鈴找車
Column()
{
if(this.display_flag==1)
{
Image($r("app.media.ic_ring_on_filled"))
.height("55%")
.objectFit(ImageFit.Contain)
.interpolation(ImageInterpolation.High)
.onClick(() => { this.display_flag +=1; if(this.display_flag>2)
{
this.display_flag =1;
}
})
}
if(this.display_flag==2)
{
Image($r("app.media.ic_ring_off_filled"))
.height("55%")
.objectFit(ImageFit.Contain)
.interpolation(ImageInterpolation.High)
.onClick(() => { this.display_flag+=1; if(this.display_flag>2)
{
this.display_flag =1;
}
})
}
Text("響鈴找車")
···
}
// 獲取定位
Column()
{
Image($r("app.media.ic_statusbar_gps"))
····
})
Text(this.bike_location)
····
}
····
}.width("95%").height("10%")
// 電量 設(shè)置
Flex({ direction: FlexDirection.Row,justifyContent: FlexAlign.SpaceBetween,})
{
// 電量
Column() { Row()
{
Image($r("app.media.ic_power"))
···
// 電量值
Text(this.bike_power.toString() + '%')
···
}
Text("剩余電量")
···
}
···
// 設(shè)置
Column() { Image($r("app.media.ic_public_settings_filled"))
···
Text("車輛設(shè)置")
···
}···
}
// 騎行數(shù)據(jù)
Flex({ direction: FlexDirection.Column})
{
Row()
{
Text(" 累計(jì)騎行")
··· Blank()
Text("預(yù)計(jì)續(xù)航 ")
···
}
}
}
}
}
2、主頁(yè)功能開(kāi)發(fā)
主頁(yè)主要實(shí)現(xiàn)的功能包括:連接車輛、獲取需要展示的數(shù)據(jù)(車輛電量、位置、里程數(shù)據(jù)等)、將數(shù)據(jù)持久化便于頁(yè)面展示。
車輛與E-Bike通過(guò)Socket TCP協(xié)議方式連接。鑒于此部分依賴硬件,這里主要介紹E-Bike應(yīng)用層如何開(kāi)發(fā) Socket通信。實(shí)現(xiàn)如下:
Index.ets:
// 1. 首先要引入模塊,創(chuàng)建TCPSocket對(duì)象
import socket from '@ohos.net.socket'
// 創(chuàng)建一個(gè)TCPSocket連接,返回一個(gè)TCPSocket對(duì)象。
let tcp = socket.constructTCPSocketInstance();
tcpInit() {
// 2. 綁定IP地址和端口。
let bindAddress = { address: '192.168.xx.xx',
port: 1234, // 綁定端口,如1234
family: 1
};
tcp.bind(bindAddress, err => { if (err) {
console.log('bind fail'); return;
}
console.log('bind success');
}
// 3.其次是訂閱TCPSocket相關(guān)的訂閱事件,如on message,有數(shù)據(jù)傳入
tcp.on('connect', () => {
this.tcp_status = '連接ok'
prompt.showToast({message:this.tcp_status})
});
tcp.on('message', value => {
this.message_recv = this.resolveArrayBuffer(value.message)
prompt.showToast({message:this.message_recv})
});
tcp.on('close', () => {
prompt.showToast({message:"tcp close"})
});
}
// 4.連接到指定的IP地址和端口。 tcpConnect() {
tcp.getState().then((data) => {
if (data.isClose) { this.tcpInit()
}
// 連接
tcp.connect(
{address: { address: this.GetSetIP, port: this.localAddr.port, family: 1}, timeout: 2000}
).then(() => {
prompt.showToast({message:" tcp connect successful"})
}).catch((error) => { prompt.showToast({message:"tcp connect failed"})
})
})
}
// 5.發(fā)送數(shù)據(jù)
tcpSend() {
tcp.getState().then((data) =>
{ if (data.isConnected) {
// 發(fā)送消息
tcp.send(
{ data: this.message_send, }
).then(() => {
prompt.showToast({message:"send message successful"})
}).catch((error) => { prompt.showToast({message:"send failed"})
})
} else {
prompt.showToast({message:"tcp not connect"})
}
})
}
// 6. TCP連接操作界面通過(guò)設(shè)置按鈕控制,點(diǎn)擊設(shè)置按鈕即可彈出,可輸入車輛IP地址,確認(rèn)連接
if(this.show_setting==1)
{
Flex({ direction: FlexDirection.Row})
{
Row()
{
Text('車輛IP')
TextInput({ placeholder: '192.168.43.164'})
.onChange((value: string) => { this.InputIP = value
})
Button('連接').onClick(()=>
{
this.GetSetIP=this.InputIP;
this.tcpInit()
})
}
}
}
// 7.點(diǎn)擊組件,實(shí)現(xiàn)發(fā)送指令,并獲取對(duì)應(yīng)數(shù)據(jù),這里以電量為例:
Image($r("app.media.ic_power"))
.height("80%")
.objectFit(ImageFit.Contain)
.onClick(() => {
// this.bike_power = 99;
this.message_send = MSG_CMD.GET_BIKE_POWER this.tcpSend()
this.bike_power = this.message_recv;
})
/ 8.連接使用完畢后,主動(dòng)關(guān)閉。取消相關(guān)事件的訂閱。
setTimeout(() => {
tcp.close((err) => { console.log('close socket.')
});
tcp.off('message');
tcp.off('connect');
tcp.off('close');
}, 30 * 1000);
五、卡片開(kāi)發(fā)
1、卡片UI開(kāi)發(fā)
開(kāi)發(fā)卡片的目的是將自行車的數(shù)據(jù)展示在桌面上,讓用戶一目了然。用默認(rèn)模板創(chuàng)建工程時(shí),自動(dòng)創(chuàng)建了一張卡片,在form_config.json文件改動(dòng)配置為自動(dòng)刷新,支持2x2.
//form_config.json
"colorMode": "auto", "isDefault": true, "updateEnabled": false, "scheduledUpdateTime": "10:30",
"updateDuration": 1,
"defaultDimension": "2*2", "supportDimensions": [
"2*2"
]
為展示電量信息,且布局不同,由此需要?jiǎng)?chuàng)建一張2x4的卡片。操作如下:在main目錄下,點(diǎn)擊鼠標(biāo)右鍵 > New > Service Widget。
然后選擇Hello World卡片模板,點(diǎn)擊Next。
填寫卡片名字(如Widget24Card)、開(kāi)發(fā)語(yǔ)言(ArkTS和JS可選)、支持卡片規(guī)格(Support dimension 2x4)、關(guān)聯(lián)表單(Ability name)點(diǎn)擊Finish完成創(chuàng)建。修改配置為自動(dòng)刷新,支持2x4。
創(chuàng)建完卡片后,在ets文件目錄下顯示卡片目錄,然后開(kāi)發(fā)者使用ArkTS開(kāi)發(fā)卡片頁(yè)面。效果如圖所示:
鴻蒙元服務(wù)開(kāi)發(fā)實(shí)例:桌面卡片上的電動(dòng)自行車助手E-Bike-開(kāi)源基礎(chǔ)軟件社區(qū)
為兩張卡片開(kāi)發(fā)UI,resource資源共用。使用Flex容器開(kāi)發(fā)卡片,保證不同屏幕大小的顯示效果。同時(shí)為組件綁定事件,用戶可以主動(dòng)獲取數(shù)據(jù),具體UI布局代碼不再贅述,實(shí)現(xiàn)2x2和2x4效果如下
鴻蒙元服務(wù)開(kāi)發(fā)實(shí)例:桌面卡片上的電動(dòng)自行車助手E-Bike-開(kāi)源基礎(chǔ)軟件社區(qū)
2、卡片數(shù)據(jù)刷新
通過(guò)message事件刷新卡片內(nèi)容,在卡片頁(yè)面中可以通過(guò)postCardAction接口觸發(fā)message事件拉起FormExtensionAbility,然后由FormExtensionAbility刷新卡片內(nèi)容。下面是這種刷新方式更新電量的簡(jiǎn)單示例。在卡片頁(yè)面通過(guò)注冊(cè)電量圖標(biāo)Image組件的onClick點(diǎn)擊事件回調(diào),并在回調(diào)中調(diào)用postCardAction接口觸發(fā)事件至FormExtensionAbility。
// Widget24Card.ets:
let storage = new LocalStorage();
@Entry(storage) @Component
struct WidgetCard24 {
···
@LocalStorageProp('bike_power') bike_power: number = 50;
···
build() {
Row({space:5}) {
// 背景圖 電量
Column()
{
Row()
{
Image($r("app.media.ic_power"))
···
.onClick(() => { postCardAction(this, {
'action': 'message',
'params': { 'bike_power': 55
}
});
})
// 電量值
Text(`${this.bike_power}`+'%')//this.bike_power.toString()+'%')
···
}
···
}
}
}
// EntryFormAbility.ets:
import formBindingData from '@ohos.app.form.formBindingData';
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; import formProvider from '@ohos.app.form.formProvider';
export default class EntryFormAbility extends FormExtensionAbility {
find_bike: string = "app.media.ic_ring_off" bike_power: number = 55.6
display_flag : number = 1
bike_location: string = "長(zhǎng)安街1號(hào)"
bike_distance: number = 520
bike_duration: number = 479
my_font_size : number = 12
formData = {
'title': this.find_bike, 'bike_power': this.bike_power,
'bike_distance':this.bike_distance, 'bike_duration':this.bike_duration,
'bike_location':this.bike_location,
'detail': 'Detail Update Success.', // 和卡片布局中對(duì)應(yīng)
}
onFormEvent(formId, message) {
console.info(`FormAbility onEvent, formId = ${formId}, message:
${JSON.stringify(message)}`);
let formInfo = formBindingData.createFormBindingData(formData)
formProvider.updateForm(formId, formInfo).then((data) => {
console.info('FormAbility updateForm success.' + JSON.stringify(data));
}).catch((error) => {
console.error('FormAbility updateForm failed: ' + JSON.stringify(error));
})
}
...
}
實(shí)現(xiàn)效果如下圖:
鴻蒙元服務(wù)開(kāi)發(fā)實(shí)例:桌面卡片上的電動(dòng)自行車助手E-Bike-開(kāi)源基礎(chǔ)軟件社區(qū)
參考鏈接:元服務(wù)官網(wǎng)