I’ve got a little gap in my knowledge here and I want to make sure I do it right before writing all the wrong code.
I have an Android app that extends Application to set up some core functions for a TCP client. There are a few different Activity screens that should interact with Application. What I’m stuck on, is what to do when a data packet is received by Application. I want to relay it to the currently-visible Activity, whatever it is.
Coming from a C# background, I’d just create an Event in the Application, and simply subscribe to that event when an Activity is created. But I’m getting confused with Java Listeners, Handlers, …
What’s the best way to go about that? Should I be doing a Service instead? (But I don’t really care if the TCP connection is killed when the app is not shown.)
I would go with a
LocalBroadcastManager(documentation) approach.Create one of those puppies in your
Applicationclass, and register/unregister yourActivityobjects inonStartandonStop. SeeContext.registerReceiver. Note that this requires usingIntents, which might be too restrictive/heavy-weight for your application; packing/unpacking data can be a chore.Alternatively, you don’t have to use any specific android class to do it–just keep track of what
Activityyour program is in by calls to yourApplicationinonStartandonStop. Might help clean your code if you make all of your activities-of-interest extend a subclass ofActivitythat contains this logic.