Android - Shared networking between activities - android

I am developing an application which utilizes a custom network protocol over TCP. Several tasks within the application use different activities however each activity requires the networking enabled (since each activity has to send/receive some custom packets over the network).
So my idea is basically to
At application start - create a service to handle networking ( I read somewhere that I should do the networking in another thread in this service to prevent ANR)
When a new activity is run, it binds to that service. During that time it sends/receives data from the service. When the activity ends, it unbinds from the service.
I would like to know if this makes sense.
Also, I understand that I can send data to the service (to send over the network) using the aidl interface, but how would I receive data from the service? Polling through the aidl seems to be the only way I can think of - which means I would need another thread in each of my activities to prevent ANR. Surely there is some better way.
I appreciate your help and am open to suggestions.

Actually I've been reading more and am beginning to look at callback methods in the sample code provided here. After reading it more thoroughly I have a better understanding of the services and AIDL.

Related

Correct way of Starting Persistent Multithreaded Service in Android

I need to create a test application that will allows the starting/stopping of a persistent background service that runs several threads in the background. (Mainly a WebSocket Server and the Tango location Service). It needs to be persistent so I can start a web browser and connect to the ws socket.
According to what I read, the application should be structured as follows:
Activity -> Service (persistent) -> (Service (Tango) + Thread (WS))
The persistent service needs to be run as a foreground service using startForeground() and as a separate process (set in the manifest) so it doesn't close when the activity is closed.
Now, I got to questions :
1) Is my current understanding correct? Or am I approaching this the wrong way.
2) If I later want to stop the service, I want to start the activity and be able to stop it from there. How does the activity know that the service is running and how does it connect to it? Do I need to implement the binding part? How?
3) Could I achieve 2) using notifications instead and closing it from there?
This is the best I could come up with and so far it seems to work. However, if someone has a better way of implementing this or more "correct" I will change to that answer.
The solution I went for boils down to what I stated above. The only thing is that I had to implement Runnable in new classes to pass the pointers around.
It is very important that no network code is executed in the main thread of the Service, that needs to be in a separate thread.

Android Service for communicating with server

I need the service to have a steady connection with the server.
Activity and service should have bi-directional communication.
Here are the options I know
Use intent service
Extend Service class ( make it run in a different process ) and communicate using Messaging
My thoughts:
Intent services are nice, they run in their own thread, but they stop when the task is done. I don't want that. For example, if for some reason the connection is interrupted it should try to reconnect, instead of exiting the service
Extending service class makes sense. I have previously worked on a project that used Messaging for communicating with the service, the problem here is that as the project grows, it becomes hard to manage the communication.
I'm looking for an approach, where the service runs in a different process or thread, should start again if terminated for any reason (something like START_STICKY).
Also it would be nice if the communication is easy and something like Otto or EventBus can be used.
Edit : So the question is, what's the ideal way to implement it, which saves me from dealing with Messages and gives a STICKY service.
Use the Retrofit Library to make API Calls

Singleton or Service for socket connection

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.

How to create two cooperating but non-blocking services in Android?

I am confused about where Android services run. I know services marked 'remote' run in their own processes, but what about ordinary local services?
The reason I ask is I want two local services to cooperate but not be blocked by each other. So for example, Service1 manages a network connection and receives packets. On receipt of a packet, I need that service to hand-off the packet to Service2 that processes the information and takes some action, including possibly sending a return message. I need the receipt, hand-off and processing to happen asynchronously, so the network service can continue to receive packets whilst the application service processes them. How do I ensure this happens?
I know one solution is to broadcast Intents, but how do I include custom data objects (i.e. packets) in an Intent? I don't want to implement the parcelable interface (overkill for local services) but I really need to be able to hand-off complex data objects between the services.
Thanks
Everything in your manifest file that is defined to run in the same process also share the same main thread. This thread is also sometimes the UI thread if that process has activities running in it. So, if you have two local services and they are running in the same process they are going to share the same main executing thread. In order for them to both do work 'at the same time' (until multicore android devices exist all execution is sequential anyway) then your service handling the network connection is going to need to do that in a separate thread. Your other service will need another thread as well.
Your problem is commonly called the producer-consumer pattern. Here's a link quick example of an simple implementation using blocking queues.

Best way for Service that starts Activity to communicate with it

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.

Categories

Resources