Using an Android Service to handle a network connection

前端 未结 3 1635
误落风尘
误落风尘 2021-01-03 03:21

I\'m working on an Android app that needs to maintain a network connection to a chat server. I understand that I can create a service to initiate the connection to the serve

3条回答
  •  春和景丽
    2021-01-03 04:02

    One common and useful approach is to register a broadcast receiver in your Activity, and have the Service send out notification events when it has useful data. I find this to be easier to manage than implementing a handler via a callback, mainly because it makes it easier and safer when there is a configuration change. If you pass a direct Activity-reference to the Service then you have to be very careful to clear it when the Activity is destroyed (during rotation, or backgrounding), otherwise you get a leak.

    With a Broadcast Receiver you still have to unregister when the Activity is being destroyed, however the Service never has a direct reference to the Activity so if you forget the Activity will not be leaked. It is also easier to have the Activity register to listen to a topic when it is created, since it never has to obtain a direct reference to the Service...

    Lars Vogel's article discusses this approach, it is definitely worth reading! http://www.vogella.com/tutorials/AndroidServices/article.html#using-receiver

提交回复
热议问题