新聞中心
介紹通過(guò)startAbility()啟動(dòng)Service以及對(duì)應(yīng)的停止方法。

創(chuàng)新互聯(lián)專(zhuān)注于田陽(yáng)網(wǎng)站建設(shè)服務(wù)及定制,我們擁有豐富的企業(yè)做網(wǎng)站經(jīng)驗(yàn)。 熱誠(chéng)為您提供田陽(yáng)營(yíng)銷(xiāo)型網(wǎng)站建設(shè),田陽(yáng)網(wǎng)站制作、田陽(yáng)網(wǎng)頁(yè)設(shè)計(jì)、田陽(yáng)網(wǎng)站官網(wǎng)定制、成都微信小程序服務(wù),打造田陽(yáng)網(wǎng)絡(luò)公司原創(chuàng)品牌,更為您提供田陽(yáng)網(wǎng)站排名全網(wǎng)營(yíng)銷(xiāo)落地服務(wù)。
- 啟動(dòng)Service
Ability為開(kāi)發(fā)者提供了 startAbility() 方法來(lái)啟動(dòng)另外一個(gè) Ability。因?yàn)镾ervice也是 Ability 的一種,開(kāi)發(fā)者同樣可以通過(guò)將 Intent 傳遞給該方法來(lái)啟動(dòng) Service。不僅支持啟動(dòng)本地 Service,還支持啟動(dòng)遠(yuǎn)程 Service。
開(kāi)發(fā)者可以通過(guò)構(gòu)造包含 DeviceId、BundleName 與 AbilityName 的 Operation 對(duì)象來(lái)設(shè)置目標(biāo) Service 信息。這三個(gè)參數(shù)的含義如下:
- DeviceId:表示設(shè)備 ID。如果是本地設(shè)備,則可以直接留空;如果是遠(yuǎn)程設(shè)備,可以通過(guò) ohos.distributedschedule.interwork.DeviceManager 提供的 getDeviceList 獲取設(shè)備列表,詳見(jiàn)《 API 參考》。
- BundleName:表示包名稱(chēng)。
- AbilityName:表示待啟動(dòng)的 Ability 名稱(chēng)。
啟動(dòng)本地設(shè)備 Service 的代碼示例如下:
Intent intent = new Intent();
Operation operation = new Intent.OperationBuilder()
.withDeviceId("")
.withBundleName("com.huawei.hiworld.himusic")
.withAbilityName("com.huawei.hiworld.himusic.entry.ServiceAbility")
.build();
intent.setOperation(operation);
startAbility(intent);啟動(dòng)遠(yuǎn)程設(shè)備 Service 的代碼示例如下:
Operation operation = new Intent.OperationBuilder()
.withDeviceId("deviceId")
.withBundleName("com.huawei.hiworld.himusic")
.withAbilityName("com.huawei.hiworld.himusic.entry.ServiceAbility")
.withFlags(Intent.FLAG_ABILITYSLICE_MULTI_DEVICE) // 設(shè)置支持分布式調(diào)度系統(tǒng)多設(shè)備啟動(dòng)的標(biāo)識(shí)
.build();
Intent intent = new Intent();
intent.setOperation(operation);
startAbility(intent);執(zhí)行上述代碼后,Ability 將通過(guò) startAbility() 方法來(lái)啟動(dòng) Service。
- 如果 Service 尚未運(yùn)行,則系統(tǒng)會(huì)先調(diào)用 onStart()來(lái)初始化 Service,再回調(diào) Service 的 onCommand() 方法來(lái)啟動(dòng) Service。
- 如果 Service 正在運(yùn)行,則系統(tǒng)會(huì)直接回調(diào) Service 的 onCommand() 方法來(lái)啟動(dòng) Service。
- 停止 Service
Service 一旦創(chuàng)建就會(huì)一直保持在后臺(tái)運(yùn)行,除非必須回收內(nèi)存資源,否則系統(tǒng)不會(huì)停止或銷(xiāo)毀 Service。開(kāi)發(fā)者可以在 Service 中通過(guò) terminateAbility() 停止本 Service 或在其他 Ability 調(diào)用 stopAbility() 來(lái)停止 Service。
停止 Service 同樣支持停止本地設(shè)備 Service 和停止遠(yuǎn)程設(shè)備 Service,使用方法與啟動(dòng) Service 一樣。一旦調(diào)用停止 Service 的方法,系統(tǒng)便會(huì)盡快銷(xiāo)毀 Service。
文章標(biāo)題:創(chuàng)新互聯(lián)鴻蒙OS教程:鴻蒙OS啟動(dòng)Service
當(dāng)前地址:http://www.5511xx.com/article/djpcpps.html


咨詢(xún)
建站咨詢(xún)
