W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
介紹通過startAbility()啟動Service以及對應的停止方法。
Ability為開發(fā)者提供了 startAbility() 方法來啟動另外一個 Ability。因為Service也是 Ability 的一種,開發(fā)者同樣可以通過將 Intent 傳遞給該方法來啟動 Service。不僅支持啟動本地 Service,還支持啟動遠程 Service。
開發(fā)者可以通過構造包含 DeviceId、BundleName 與 AbilityName 的 Operation 對象來設置目標 Service 信息。這三個參數(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);
啟動遠程設備 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) // 設置支持分布式調(diào)度系統(tǒng)多設備啟動的標識
.build();
Intent intent = new Intent();
intent.setOperation(operation);
startAbility(intent);
執(zhí)行上述代碼后,Ability 將通過 startAbility() 方法來啟動 Service。
Service 一旦創(chuàng)建就會一直保持在后臺運行,除非必須回收內(nèi)存資源,否則系統(tǒng)不會停止或銷毀 Service。開發(fā)者可以在 Service 中通過 terminateAbility() 停止本 Service 或在其他 Ability 調(diào)用 stopAbility() 來停止 Service。
停止 Service 同樣支持停止本地設備 Service 和停止遠程設備 Service,使用方法與啟動 Service 一樣。一旦調(diào)用停止 Service 的方法,系統(tǒng)便會盡快銷毀 Service。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: