I'm new to Android development, i'm trying to port an IOS app to Android. Basically my App need to communicate with a server in real time with socket IO. It connect to the server and then handle the various message until the server finish to process the request.
In my IOS app i use a Singleton pattern to send the requests to my websocket server, and i use the same instance to delegate the server response.
In Android i was going to use the same pattern, with a callback object in my activity to redirect the user after getting a server response.
I need my app to keep the socket connection open until we got the right status from the server, even if the app goes in background.
Some people recommend using Service with Broadcast receiver instead of Singleton. Is it the best thing to do in my case ?
Using a Service is exactly what I have done for very similar purposes (doing socket communication for Bluetooth and TCP/IP applications) and think you'll certainly want to be using a Service if the communication should continue even when the user has closed the application.
A Service is essentially a means to run code on the UI thread (but of course you can then start off other threads within it) but without a user interface, unlike an Activity which has a UI associated with it.
If you were to try to do this in a static singleton class as you propose as an alternative, then I think the problem would be that you wouldn't have very good control over the lifecycle of it. If the user navigates away from the application, then my understanding is that it's up to the framework when it chooses to remove the process and all the static objects along with it. For this reason, if you have singleton classes populated with data and you exit your application and then later come back to the application, you may or may not find that the 'old' singleton instances are still around. For this reason, in my application (which uses a very large amount of global state) I've resorted to holding my singletons' actual instances in an extension of the .Application class, to (hopefully) better control their lifecycle.
With a Service you have a well-defined lifecycle with appropriate lifecycle callbacks (onCreate(), onDestroy(), etc.) just as you do with an Activity.
Yes, definitely use a Service. From the docs:
A Service is an application component representing either an application's desire to perform a longer-running operation while not interacting with the user
While using a singleton might work for a while, your application would be prone to being killed by the operating system when it goes into the background unless you have a Service. If you're more comfortable with the singleton pattern, you could implement it in a singleton and then just tie it to a Service simply to maintain its lifecycle, but that seems more of a mess than it's worth. Note that you shouldn't do network operations on the UI thread and by default a Service runs on the UI thread. You'll need to spin up another thread to do your work.
I don't see anything in your post that demands a BroadcastReceiver, though perhaps there may be some network related broadcast intents that might be useful like android.net.ConnectivityManager.CONNECTIVITY_ACTION.
Related
If I make a call to an external web service and the user rotates the device, the Activity will restart (I know you can handle it yourself but this is not recommended). I know I can preserve the state using onRetainNonConfigurationInstance().
The question I have is what happens to the inflight network IO after the Activity restarts? Does it continue, is it suspended or killed?
I am rather new to Android (iOS person) so the restarting Activity is rather odd.
Some network calls we make could be restarted, but checking out for a purchase is not one of them. How do I handle this so that purchases still work correctly? Assume I would use Asynctask (though I realize there are other choices such as Executors).
For network calls that need to maintain across activity restarts (e.g. purchase), consider using a service instead of doing it inside the activity.
If your connection is defined as instance variable inside the activity it will be destroyed/killed when the activity restarts.
Another alternative, but I would not recommend, is to implement an application class and maintain your connection there so it will be persistent as long as your app process is alive.
You should not be handling requests inside activities unless they are simple enough to fire off (i.e., do not require responses). The common use case is that you are interacting with a REST interface that you want to handle across multiple activities. The basic idea is to issue requests to the service and let it mediate the connection for you. Google IO 2010 had a good lecture that you can listen to.
Implementing the functionality inside an Application class is not recommended, as you will get strange behavior when your app is killed by Android when memory is tight.
I want to use a started (foreground) service to manage a network connection that should persist when the user leaves the application for a short time, and that the user should be aware of (so he can return to the app and maybe disconnect). This service will only ever be used locally by activities in the same process.
Maybe it's just because I am new to Android, but I find it unnecessarily difficult to bind to this service in every activity that uses it - in particular, the asynchronous nature of binding, which only really seems to be necessary for accessing services in a different process. Is there any indication against just accessing the started service through a static variable instead?
Maybe I'm understanding your question wrong, but there is no need to bind to the started Service from every Activity. Instead, you could simply start the Service from wherever you need to interact with it. This calls the onStartCommand() if the Service is already started. You could include an extra with the Intent that starts the Service to distinguish between the first start and subsequent ones.
Of course - this addresses the use case where you do not want to have a client-server mode of interaction between your activities and the Service - that scenario requires binding and if you really need binding, then you need to bind from every component that needs to be served by the Service.
To begin with, this is the first Android app I'm writing, and I have very little prior Java experience. So nothing is too simple -- I could easily be missing anything "obvious".
Here's the general design I'm dealing with:
A long-lived bidirectional network connection.
Requests should go out over the network when the user interacts with the UI.
The UI should be updated when the responses to said requests come back -- asynchronously.
The app will contain multiple activities.
These activities will be focused on particular areas of functionality available, all relying upon the same underlying network connection. So I want to set up this connection no matter which activity my app starts in, and have it survive across switching to another activity in my app, but I want to shut it down when switching away from my app completely.
I think I want threads. I've got something basic working, but not well because I don't think I have them organized properly. I also am, so far, unable to pass data between the UI and network thread, so I can't get requests in nor actions for responses out. So I'd appreciate any advice.
I think I want threads.
You don't have a choice on that front. You will need a thread that listens on your socket for incoming data. Android is no different than standard Java in that respect.
I also am, so far, unable to pass data between the UI and network thread, so I can't get requests in nor actions for responses out.
Well, your thread should be managed by a Service. The network connection supports multiple activities, so no one activity should own the thread.
You will then need to decide when the network connection should exist. Since activities come and go, you will need to decide if the network connection should only exist when one of your activities is in the foreground (in which case you would likely bind to the service with bindService() from each activity), or whether there is an explicit "start" and "stop" operation that the user must do, so the connection can live after all of your activities are gone (in which case you would likely use startService() instead of bindService()).
Once you know when and how you are starting/stopping the service, you can decide how that service will communicate its results back to the various activities. There are tons of options, some better than others depending on your use case. Registered listeners, Messenger, broadcast Intents, a ContentProvider, and so on are all candidates. Any of those can be used by a background thread and can arrange to get data to the foreground activity on the main application thread. The other activities would typically refresh their data during onResume(), since there usually is no point in proactively updating them when they are not on the screen or may have even been kicked out of RAM.
IOW, "advice" is several chapters in a book or two. :-)
In Virgil Dobjanschi's talk, "Developing Android REST client applications" (link here), he said a few things that took me by surprise. Including:
Don't run http queries in threads spawned by your activities. Instead, communicate with a service to do them, and store the information in a ContentProvider. Use a ContentObserver to be notified of changes.
Always perform long running tasks in a Service, never in your Activity.
Stop your Service when you're done with it.
I understand that he was talking about a REST API, but I'm trying to make it fit with some other ideas I've had for apps. One of APIs I've been using uses long-polling for their chat interface. There is a loop http queries, most of which will time out.
This means that, as long as the app hasn't been killed by the OS, or the user hasn't specifically turned off the chat feature, I'll never be done with the Service, and it will stay open forever. This seems less than optimal.
Long question short:
For a chat application that uses long polling to simulate push and immediate response, is it still best practice to use a Service to perform the HTTP queries, and store the information in a ContentProvider?
Don't run http queries in threads
spawned by your activities. Instead,
communicate with a service to do them,
and store the information in a
ContentProvider. Use a ContentObserver
to be notified of changes.
I have yet to view the presentation, though I have reviewed the slides. I have serious reservations about the ContentProvider portion of the proposed architecture.
Always perform long running tasks in a
Service, never in your Activity.
Everybody has their pet "always" and "never" statements, myself included. I would hesitate to put this in the "always" category. Using a Service as a home base of long-running tasks is a fine strategy, but it too has its issues (e.g., in a screen rotation, unbindService() will destroy the Service before the next bindService() kicks in, if there are no other bound connections, leaving you with gobs and gobs of connection bookkeeping if you have a complex app).
For a chat application that uses long
polling to simulate push and immediate
response, is it still best practice to
use a Service to perform the HTTP
queries, and store the information in
a ContentProvider?
It is a practice. IMHO, the jury is still very much out as to whether it is a best practice.
I have a service that listens to a socket. When receiving certain input it is to create an activity. When receiving other input, it is to kill this activity. I have struggled for a while to make the service communicate with the activity through AIDL (http://developer.android.com/guide/developing/tools/aidl.html), but this seems to not be effective. I think AIDL is only effective when the process that is to be talked to is a service, not when it is an activity? I would love some directions or suggestions on how to solve my problem.
Cheers,
I have a service that listens to a
socket. When receiving certain input
it is to create an activity.
Please make this configurable. Services should not be starting activities except in very unusual circumstances (e.g., the socket is a SIP connection and you are creating a VOIP client). Popping up an activity interrupts the user in whatever they are doing.
When receiving other input, it is to
kill this activity.
The only scenario I have seen where this is a valid pattern is dismissing the in-call screen when the other party hangs up the line. If you are creating a VOIP client, your proposed pattern should be OK, but otherwise, please reconsider having the activity vanish in the middle of the user using it.
I think AIDL is only effective when
the process that is to be talked to is
a service, not when it is an activity?
No, it works in the reverse direction too, but usually only if the activity is the one starting the service and binding to it. More importantly, AIDL is only for cross-process communication.
I would love some directions or
suggestions on how to solve my
problem.
You have not really provided enough information on the nature of the communication to give you a thorough answer. What, exactly, is the service trying to tell the activity? Is the activity also trying to communicate with the service?
The recommended pattern for ongoing communication from an activity to a service is to use the local binding pattern. You will find an example of this in your SDK samples, and you can find one here as well.
The service then has options for communicating back to the client: via a callback (e.g., the Handler in the answer supplied by Mr. Smiljanić) or via broadcast Intents. In the case of the callback, the activity would need to bind to the service in order to get access to an API to provide the callback object. The service would then hold onto that object and call methods on it during key events.
If your service is doing its primary work on a background thread, you will need to ensure that your UI operations get performed on the UI thread. The Handler is one approach to that.