Android Service interacting with multiple activities

前端 未结 2 2054
名媛妹妹
名媛妹妹 2020-12-09 06:08

I\'m trying to refactor/redesign an Android app. Currently, I\'ve one UI activity (Activity 1) that creates a DataThread. This thread is responsibl

相关标签:
2条回答
  • 2020-12-09 06:20

    I usually bind my service from the Application class and have some kind of controller class (like a "mediator" I guess...not sure how all these patterns are named) scoped in the application that handles communications between services and whatever the active Activity is.

    This would involve writing your own Application class and telling the Manifest to use this one. I went into more detail on this process in a previous thread:

    More efficient way of updating UI from Service than intents?

    You could keep track of the "currently active" Activity by sending the Application class a reference to itself in onResume (also explained in the example above). This can be accomplished by deriving your Activities from a common base class that has a way of getting your Application class (casting from getApplicationContext), and in this base class' onResume, send a ref of itself to the application. Then, you can register activities by name with your DataServiceController, for example, and send messages to the current Activity only if it's registered with the Controller to receive them.

    0 讨论(0)
  • 2020-12-09 06:35

    Definitely more than one activity can bind to your service. You will get an onBind() for each one that binds. Your service would then ideally handle the logic of interacting with multiple activities by identifying them using an ID or the intent (with your own IDs for each activities as extras) from onBind() in your service. You could then have the Service spawn off a background thread for each activity that binded to it.

    0 讨论(0)
提交回复
热议问题