How to get data from service to activity

后端 未结 4 1936
-上瘾入骨i
-上瘾入骨i 2020-11-27 04:11

In my app I have an activity and a service... The service will broadcast messages gathered from data from GPS... The Activity should receive the broadcast messages and updat

4条回答
  •  甜味超标
    2020-11-27 04:36

    A good way to have it is using Handler. Create a innerClass in your activity that extends Handler and Override the handleMessage method.

    Then, in your ServiceReceiver class, create a handler variable and a constructor like:

    public ServiceReceiver(Handler handler){
       this.handler = handler;
    }
    

    So, in your activity, create your custom handler and pass it to your service. So, when you wants to put some data to your activity, you can put handler.sendMessage() in your Service (it will call handleMessage of your innerClass).

提交回复
热议问题