新聞中心
介紹通過startAbility()啟動Service以及對應的停止方法。

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


咨詢
建站咨詢
