Issue
I am planning to implement Socket.io in android by this library for a chat based application. As far as I understood the library seems to be pretty good. I want to know how to maintain a single socket connection throughout the app all the time? Here I have listed out ways to achieve, in which I need the best and stable way.
Three ways
MainApplication Class extends Application
By this we have a good scope that the socket connection is maintained in the main thread( or application's life cycle) and whenever the socket instance is needed from the activity we can get it easily. But it's main thread which also the problem. It might block the main thread.
BoundService
By this way we can bind the service with the activities and we can simply use it. Doing in separate thread is the way to achieve IO/Network calls. But cross processing transfer is more expensive than directly accessing in same process.
Singleton
Maintaining connection in Singleton also makes sense. But we don't know when the instance is killed by process, because it doesn't work in activity life cycle.
If I makes sense please help me out. If not comment it out.
Edit
I have given the answer which is more suitable for me.
Solution
Service for Maintaining socket
connection
As per Ofek Ron mentioned Service
with BroadcaseReceiver
is a better idea than BoundService
. Because its a tedious process to maintain communication. And I also recommend pub/sub
way of broadcasting, like Otto
or EventBus
(I myself suggest Otto by Square, which is clean and brilliant api).
Pros of OTTO
1. Cleaner Api
2. You can subscribe and publish in/to any Activity
, Fragment
, Service
class.
3. Decoupling. (You have to couple as less as possible in your code).
And one more point is use START_STICKY
in the onStartCommand()
to start service after it is getting destroyed. See this reference.
MainApplication to start the service
It's best practice to start the service in the MainApplication
that extends Application
. Because the application will be killed when there is a memory constraint or user forcefully closes the app from the stack. So onStartCommand()
will not be called frequently like if we have implemented in Activity.
Implementing online status
You can implement online status simply by implementing Application.LifeCycleCallbacks
in the MainApplication
class, which has most of the life cycle callbacks of activity and will be notified in the callback. By that you can implement Online
status simply without any boiler plate codes. (If anyone need help here let me know).
Uploading or downloading images or files.
Best practice is to implement by IntentService
because it's running in the a separate thread. I promise which will give the best performance because it is handled by android itself, not like threads created by us.
Answered By - ImMathan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.