Service 與 Activity 之間的通信機(jī)制是如何實(shí)現(xiàn)的? service和activity的優(yōu)先級誰高
Kakaku優(yōu)選達(dá)人跨境問答2025-08-067790
Service 和 Activity 之間的通信機(jī)制是通過在 Service 中啟動一個 Intent,然后在 Activity 中通過接收這個 Intent 來與 Service 進(jìn)行通信。
- 在 Service 中啟動一個 Intent:
Intent intent = new Intent(this, MyService.class);
startService(intent);
- 在 Activity 中接收這個 Intent:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = getIntent();
if (intent != null) {
MyService service = intent.getService();
if (service != null) {
// 在這里使用服務(wù)提供的功能
}
}
}
這樣,當(dāng) Service 啟動時,它會創(chuàng)建一個 Intent,并在 Activity 中接收這個 Intent,從而實(shí)現(xiàn)了 Service 和 Activity 之間的通信。
本文內(nèi)容根據(jù)網(wǎng)絡(luò)資料整理,出于傳遞更多信息之目的,不代表金鑰匙跨境贊同其觀點(diǎn)和立場。
轉(zhuǎn)載請注明,如有侵權(quán),聯(lián)系刪除。