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

 //內部類,實現BroadcastReceiver
    public class LocationReceiver extends BroadcastReceiver {
        //必須要重載的方法,用來監聽是否有廣播發送
        @Override
        public void onReceive(Context context, Intent intent) {
            String intentAction = intent.getAction();
            if (intentAction.equals("location.reportsucc")) {
                
            }
        }
    }

  三、在Activity創建時注冊廣播接收器,

filter.addAction值必須和服務里面注冊的Action名稱一致
 @Override
    protected 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銷毀時卸載廣播接收器

  

    @Override
    protected void onDestroy() {
        unregisterReceiver(locationReceiver);
        super.onDestroy();
    }

 

    總結:通過發送廣播,是一種實現了服務和活動之間互相通信的方式。

    


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM