Android开发--Service和Activity通过广播传递消息
生活随笔
收集整理的這篇文章主要介紹了
Android开发--Service和Activity通过广播传递消息
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Android的Service也運行在主線程,但是在服務里面是沒法直接調用更改UI,如果需要服務傳遞消息給Activity,通過廣播是其中的一種方法:
一、在服務里面發送廣播
通過intent傳送數據、通過setAction 設置Activity接收廣播時要過濾的動作名
Intent intent = new Intent();intent.putExtra("key", "test");intent.setAction("location.reportsucc");sendBroadcast(intent);
二、在Activity中創建內部類做為廣播接收器,需實現BroadcastReceiver
//內部類,實現BroadcastReceiverpublic class LocationReceiver extends BroadcastReceiver {//必須要重載的方法,用來監聽是否有廣播發送 @Overridepublic void onReceive(Context context, Intent intent) {String intentAction = intent.getAction();if (intentAction.equals("location.reportsucc")) {}}}三、在Activity創建時注冊廣播接收器,
filter.addAction值必須和服務里面注冊的Action名稱一致 @Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_home);locationReceiver = new LocationReceiver();IntentFilter filter = new IntentFilter();filter.addAction("location.reportsucc");registerReceiver(locationReceiver, filter);}四、最后記住在不需要廣播接收器的時候,卸載廣播接收器。例如在Activity銷毀時卸載廣播接收器
@Overrideprotected void onDestroy() {unregisterReceiver(locationReceiver);super.onDestroy();}
?
總結:通過發送廣播,是一種實現了服務和活動之間互相通信的方式。
轉載于:https://www.cnblogs.com/tangchun/p/9305135.html
總結
以上是生活随笔為你收集整理的Android开发--Service和Activity通过广播传递消息的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: springBoot单元测试-模拟MVC
- 下一篇: IDEA项目搭建七——使用Feign简化