Communicate with Activity from Service (LocalService) - Android Best Practices

前端 未结 3 1239
感情败类
感情败类 2020-12-05 07:39

Common scenario - Activity with a background Service to poll server.

The Service will run periodically via AlarmManager and also perform tasks for the Activity (user

3条回答
  •  甜味超标
    2020-12-05 08:07

    As written here

    When you want to communicate from service to an Activity or Fragment which did NOT started the service or to communicate from service to multiple activities/fragments then you can use Event Bus or Broadcast Intents since they can receive callback for an event in any activity or fragment wherever they are implemented.If you want to communicate from service to an activity/fragment which started the service then you can use Pending Intent or Messenger as they can be put into an Intent extra and passed to Service.

    Pending Intent

    We can use createPendingResult() which creates a new PendingIntent object which you can hand to service to use and to send result data back to your activity inside onActivityResult(int, int, Intent) callback.

    Event Bus

    You can have the service raise events which activities or fragments can listen for and respond to using Event Bus.

    Messenger

    Messenger is parcelable ,and can therefore be put into an Intent extra,so your activity can pass this Messenger to the service.Service will populate Message object with whatever data needs to be send.

    Broadcast Intents

    Service can send a broadcast which can be responded by the activity.

提交回复
热议问题