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

前端 未结 3 1234
感情败类
感情败类 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:09

    If you need tight coupling between your activity using bindService(), the way you communicate depends on who is originating the communication.

    If the Service is originating (due to say an Alarm that has some new information to share), it would typically send a broadcast.

    If the Activity is originating (due to say your example "go fetch something from server"), it could be handled asynchronously using AsyncTask or similar. That is, you could fetch from the server in the AsyncTask.doInBackground(), and post the results back to the activity in AsyncTask.onPostExecute. This scenario be a bit more complicated if the requested operation is expected to take a very long time - in which case I would de-couple it, and send a broadcast back from the Service instead.

提交回复
热议问题