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.
First of all, the Application's onCreate() is irrelevant in your use case because you can't have a thread running in the background when it was first initiated in a non service code.
Also, I would recommend using Google Cloud Messaging instead of creating your own mechanism. It would be best for the device's battery life and much less code for you to handle.
If you do want to implement that chat completely on your own, Service is your only choice. You can also combine it with a singleton, but I wouldn't recommend that approach. You can use broadcasts and BroadcastReceiver for communicating between your Service and Activity, I think it is easier than a Bound Service since bounding to the service is asynchronous and it creates a lot of mess compared to simple broadcasting.
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.
You can combine first way and third way like:
Create Sockets in your Application and declare them as static. So you can maintain and access them every where in you application. Don't forget to create separate Threads to perform the network operations, you can use ThreadPool to manage those Thread. If you want to update your UI from those Thread you can use Handler and Message to communication with UI Thread
Before you create your own implementation of a socket.io client, you should give this library a chance: https://github.com/socketio/socket.io-client-java
I use it in one of my projects to communicate with a node.js server which is working pretty fine. Actually, all of your suggestions are correct and mostly depend on what you want to achieve. However, one context is always available: the application context. Therefore you should keep a singleton instance in the Application class and get it by getApplicationContext().
Online status of the user: here you should create a background service which is listening constantly for the users state. As there are not many information, this should be okay and should not drain the battery too much. Additionally you can send a flag if there are new information available and only if there is something new, you start another thread, which is receiving the new data. This keeps the data low.
Chat: the chat data is transfered only when the app is active. So, this should be done in an activity.
Both the service and the activity can access the singleton instance of the socket.io client from the application context. As long as you do not process any complex data on the main thread everything is fine. So, wrap your calls into separate thread and only start them when they are actually needed.
Related
I am an iOS developer and recently started Android development. Currently I need the application to perform a repeating check regarding a remote resource (a JSON file) in the background, which I would like to:
App finished launching
Initiate scheduled repeating task in Application subclass
Application will be noticed if there are any changes in the remote JSON file and handle it accordingly
After doing some research I found that there seems to have many ways to achieve this, while I can rule out some of them, I can't really tell the differences between the rest and which I should use.
I've found that to perform a scheduled repeating task, I can use the following classes:
ScheduledThreadPoolExecutor
IntentService
AlarmManager
Runnable (with postInBackgroundDelayed / DelayedRunnable, or maybe ScheduledExecutorService?)
And I've ruled out the use of:
ScheduledThreadPoolExecutor, I've read that this is best used when multiple worker threads are needed, which in my case I only need one
AlarmManager, this will be executed even when the app is not running, while I only need the task to be performed when the app is running
And for the rest, which are IntentService and Runnable, from my understanding so far:
IntentService, needed to be started and stopped manually, tasks are invoked by sending an Intent to the service, and then the result is broadcasted
Runnable, like the block used in Objective-C, a specific segment of code to be executed at appropriate time
Other than these are there any other differences between them? Is my understanding correct? Are them both appropriate for my task? It it is the case, are there any considerations before choosing which one to use?
Thanks!
For creating long-running background task in Android, you should create a Service in your application.
Services are executed on the main thread of the application, with the highest priority as Activity, and continue to run even if the user exits the application.
Services have the following types :
Started Services
Foreground Services
Bound Services
Intent Services
In implementation of the services, you should create another thread, using for example ScheduledThreadPoolExecuter and delegate the work you want to accomplish to that thread.
For your requirement, you can create a simple service, extending the Service class, and in the onStart() method, create your thread to do the desired work for you.
I'm building a fairly simple data tracking app. Using a runnable, every 5 seconds my app checks how much data the user has consumed and updates the UI.
The app works well, and the runnable keeps going even when the app is not in the foreground, but when the app is closed, it stops.
I've never used a service before, and after reading some documentation, I'm still unsure if that's what I need. I need to be able to update the UI, and depending on the data amount, start an asynctask to update a server.
Right now this part is happening from the runnable, but from what I've read about services, it seems like interacting with the UI is difficult.
I was originally hoping that I could somehow just prevent the app from ever being killed. It's going to be used on a private system, so there's no concern of the user 'getting annoyed' that the app can't be closed, but I can't figure out how to pull it off.
Thanks in advance for any information!
Note: I didn't post any code because I didn't think it was relevant here, but I'd be happy to upon request.
Is this the correct situation to use a service?
Yes.
from what I've read about services, it seems like interacting with the UI is difficult.
It's not that hard. The easiest solution would be to use an EventBus.
Another solution without a library: The Activity binds to the Service in onCreate. The Service returns a Binder. The Activity passes a Listener to that Binder. The Service calls the listener as soon as the UI needs to be updated.
I'm trying to implement an android app where I can send commands to a server that controls a robot. The problem is quite "simple": I would like to keep a connection and communicate with the thread-service-task to send messages to the server, and get the responses to update UI and keep the user with the related information from the robot sensor.
So, what should be my decision? I know its probably duplicated. But I didnt find my same problem, cause I want to extend the question:
Is there any way to run a background process on an activity, change activity and keep it going? (Activity or fragment, I would go for fragments in the future).
Thanks in advance for any help!
The best solution for this is probably a Service.
A very good article on Services, including how to communicate with a background service via either Intents or broadcast events can be found at http://www.vogella.com/tutorials/AndroidServices/article.html
One typical model for your situation is to use:
Service for long running communication (taking "orders" from a queue
BroadcastReceiver to be notified about asynchronous events handled by Service
Activity to handle UI
One reference to consider looking at is here
Here is a Reference Code that uses an Android App , Arduino to Control a Bot. You can see its Structure thats what i have used in my robot as well. AsynkTasks wont be a good option in this aspect. Using a Service is a goodIdea for Long Running Communication
https://code.google.com/p/mover-bot/
Here is a Live Demo of This Android Controlled Robot.
Mover Bot
Do your work in Background and notify the result to UI thread.
Go through this for more detailed overview.
AsyncTask
It is a helper class around Thread and Handler for making threading and easy for you. Just do your task in background and publish result in UI thread.
http://developer.android.com/reference/android/os/AsyncTask.html
Thread
Use basic concept of threading in java, create your own thread pool do your task and publish your result in UI thread using handler. Mainlly, used when you need more longer running task while your ui is visible (for simple background task asynctask). It will take time in implementation but provide you more control over task management.
https://developer.android.com/training/multiple-threads/create-threadpool.html
Service
Services are used when you have more longer running task and also you want your ui to be independent from your task.
Here in your case i would prefer you should use a service for communication and use binder or broadcast manager for reflecting change in UI.
http://developer.android.com/guide/components/services.html
All I’m really looking for here is a little guidance. I’m trying to create my first official android app. I’m new to java/droid but not programming. Over the past month I’ve created quite a number of little experimental activities, services, threads and whatnot and they all function as planned. So now I’m trying to tie is all together but not having much luck.
In a new project I’ve compiled the guts into 'my.main.package' which runs a service that is constantly crunching data that other clients/apps can use… Well that’s my plan. For example, in this service is a custom thread/loop timer that is constantly counting. What would be the best way for any other apps to get a constant feed of this timer and other data as a listener could within its own sandbox and in the least taxing way possible?
I’m assuming one must implement aidl for IPC but I’m not sure if its needed and/or necessary as data from my.main.package is only outgoing, i.e. other apps only need receive/listen. I understand there needs to be some form of message handling or parcelable marshalling going on and possible permissions with aidl but I got to thinking that encoding/decoding a parcel or sending a message every millisecond would be very taxing. Is aidl the only way to go or is there a way to broadcast data as you can intent?
Any help would be greatly appreciated!
In a new project I’ve compiled the guts into 'my.main.package' which runs a service that is constantly crunching data that other clients/apps can use
A service should only be running when it is actively delivering value to the user. Users think that developers who create services that run all of the time are idiots and attack their apps with task killers, force-stops from the Settings app, etc.
Perhaps your description is just depicting your app in a poor light, but "a service that is constantly crunching data" is an anti-pattern. These are phones and tablets, not servers.
What would be the best way for any other apps to get a constant feed of this timer and other data as a listener could within its own sandbox and in the least taxing way possible?
The best way is for them not to be separate apps in the first place.
For example, in this service is a custom thread/loop timer that is constantly counting.
This is not adding value to the user.
I’m assuming one must implement aidl for IPC but I’m not sure if its needed and/or necessary as data from my.main.package is only outgoing, i.e. other apps only need receive/listen.
A remote service using AIDL is one way of doing IPC. It is not the only way. It is not even the most common way. You can also:
send a broadcast Intent
have the client send a Messenger to the service, and the service sends messages to the client via that Messenger
have the service update a ContentProvider, and have clients register a ContentObserver on the ContentProvider
I understand there needs to be some form of message handling or parcelable marshalling going on and possible permissions with aidl but I got to thinking that encoding/decoding a parcel or sending a message every millisecond would be very taxing.
IPC is "very taxing" in general. Hence, IPC should be avoided wherever possible.
In fact, IPC with AIDL is the only & the most effective way to do your requirements, I think. If you need one demo, you can take a look here. It's a simple example I wrote to learn AIDL & Binder on Android. Hope it could give you some brief for starting.
A very simple question:
I know that Android applications run in the background when they are closed. Is it possible for my application to keep working while it is in the background? For example, maintaining a timer in the application to automatically perform a function every hour?
Thanks!
Use services for doing tasks in background. more info is here http://developer.android.com/guide/topics/fundamentals/services.html.
An alarm service should meet your needs; here's an example.
To run things in the background (or outside of the main application thread) there are a few options. To do something very quick in the background the easiest way is to use an AsyncTask. It sounds like you are wanting to implement a bit more than an AsyncTask would handle though. For more longterm tasks that you want to run behind the scenes you probably want a Service.
You can have services that run, do what they are supposed to do and then exit, and you can have ones that keep running. Services have a lot of depth. You could use the AlarmService that is linked above by another user, however another approach would be to just make a simple service and use a TimerTask http://developer.android.com/reference/java/util/TimerTask.htm
Remember though, when you are doing things in the Service, they will be being done on the Main Thread, which could slow down other programs, so any logic over long periods of time needs to be accomplished in an AsyncTask.