I've written an application which has multiple activities with multiple buttons. A colleague of mine wrote a service which detects gestures, based on the gyroscope sensor (move up, down, rotation...). We want to join the application and the service so we would be able to control the app using gestures from the service.
Since we both don't have so much experience with Android, we'd like to ask, how this is usually achieved?
For the Service -> Activity communication you can use LocalBroadcastManager, check this SO answer: Android update activity UI from service
For the Activity -> Service communication you either start service and add extras to intent or have a bound service.
Make sure you read this article: http://developer.android.com/guide/components/services.html
Related
I have an app with an auto log out feature where I was using a Timer to auto log out the user (where user is a static singleton object).
Recently I realized there were some other activities and I have to implement a global log out feature so I tried to implement different Timers to each Activities and tried to synchronize them, but it wasn't a good approach and it was a pain. Then I turned my face to the services.
What I need to know is a good way to control a single service within different applications. Any ideas will be appreciated.
You can implement bound service, start it, and bind it with two activities.
More information You can find in official developer docs this and this
you can implement a "Bound" service to interact it from different activities.
Here is complete example for Bound service with explanation.
http://developer.android.com/guide/components/bound-services.html
A broadcast is a message that any app can receive. The system delivers
various broadcasts for system events, such as when the system boots up
or the device starts charging. You can deliver a broadcast to other
apps by passing an Intent to sendBroadcast(), sendOrderedBroadcast(),
or sendStickyBroadcast().
All that you need to do is to create BroadcastReceiver. Add IntentFilter for it. Register it in your Service. And than send Intent with action that you add to IntentFilter from any of your Applications.
Go throw this article to get better understanding of Intents
Is it possible to make an activity and a service communicate, using the Observer design pattern?
I want to make them communicate both ways by giving them both the role as Observer and Notifier
The reason why I want to do this, is that I want low coupling between them. So if the activity crashes for some reason, the service will still be running and still trying to notify the GUI without crashing.
The reason I want the service to remain running, is that it acts like a server in a LAN and I still want the system and the clients to communicate even when the GUI of the server is gone.
If this can't be achieved using the Observer pattern or is too complex, is there another way to achieve what I described above?
Thanks in advance
You can run the service as foreground if your are using notification . so when the activity exit the service can update with the notification or remote views.
Also , When you start the activity you can bind the service from the activity to communicate using service connection.
bindService(new Intent(this,
YourService.class), mConnection, Context.BIND_AUTO_CREATE);
A started service can use the startForeground(int, Notification) API to put the service in a foreground state, where the system considers it to be something the user is actively aware of and thus not a candidate for killing when low on memory. (It is still theoretically possible for the service to be killed under extreme memory pressure from the current foreground application, but in practice this should not be a concern.)
check the link - http://developer.android.com/reference/android/app/Service.html
http://developer.android.com/guide/components/bound-services.html
You could have a communication from Activity to Service with a usual Binder. The Service can inform the Activity about changes with a Callback, which you can register in onServiceConnected() and unregister in the Activities onPause().
With this you have a two way communication between Service and Activity and the implementation isn't to complex.
So if the activity crashes for some reason, the service will still be running
The thing is, Activity doesn't crash. The whole app process does. So if you want to separate Activity and a Service, you need to run them in defferent processes. Note sure about if Service is restarted after process crash, though.
Take a look here https://stackoverflow.com/a/12022185/468311, that would be a good start for you.
If this can't be achieved using the Observer pattern or is too complex
As suggested, use Binder. Or you can communicate using Intents.
But keep in mind that Service wasn't intended to be used as a forever-running piece of your app. Try avoding this. Use Service for pereodic background operations.
I am building an Android application.
I am trying to do a running app. this means I will need a background service running and counting my GPS data and report that to the activity.
But - I want the activity to be able to send actions to this service too (Start, Stop , etc).
I have struggled with a few methods of doing this 2-way service<->activity communications.
Any reference? what is the best approach to do that?
Thanks
Did you try service bind mechanism?
You can create service for collecting GPS data (http://developer.android.com/guide/components/services.html), start it on application startup (http://developer.android.com/guide/components/services.html#StartingAService), bind this service on starting your activity and use binder object for transferring data between the service and activity (http://developer.android.com/guide/components/bound-services.html), unbind on closing your activity and service will continue working on background.
In this model, your service will work always and will transfer data when it needed.
Binding might be an overkill when you deal with the same process. I would recommend using Otto from Square as an event bus mechanism to post events to your service and vice versa.
If you dont want to add a library to your project then consider using the LocalBroadcastManager that is part of the support library.
I have a class that starts a Bluetooth reading thread and another that receives/decodes what's read from that port and produces some output logs depending on the information read.
In my design, those 2 components form a service for my application (multiple activities) from where I would like to start/stop getting the output logs on a continuous basis (typical frequency of 2-3 logs per second).
My questions:
1) Should I derive from Service or IntentService. The doc says about IntentService: "This is the best option if you don't require that your service handle multiple requests simultaneously". This may be my case since the main activity will start/stop the service...
2) What would be the appropriate way to catch the service events? Does the BroadcastReceiver is appropriate for this type of communication?
3) I may need to occasionally send some stuff to the Bluetooth port. So, I'll have to pass information from my application to the service. Does the PendingIntent should be used for that?
Thank you!
Should I derive from Service or IntentService
IntentService is designed for discrete tasks, not stuff that would run indefinitely until the user manually stops it. I would use Service.
What would be the appropriate way to catch the service events? Does the BroadcastReceiver is appropriate for this type of communication?
That is certainly one approach. You might use the LocalBroadcastManager from the Android Support package to reduce overhead and keep everything private to your app. Have your activities register a receiver in onResume() and remove it in onPause(). The foreground activity will then be notified of events.
I may need to occasionally send some stuff to the Bluetooth port. So, I'll have to pass information from my application to the service. Does the PendingIntent should be used for that?
No, I would have the activity simply send a command to the service via startService(), with the data to be passed included in extras on the Intent. If you have data that cannot be packaged as extras, you may need to consider binding to the service, so you can get a richer API, though this makes configuration changes more annoying.
I'm creating an application that connects to an XMPP server on Android. I want to keep the connection on till the user logs out.
Should I use a regular Service or a Bound Service to keep the connection on?
Any tips, advice and helpful information are welcomed.
I like this explanation:
Started services are easy to program for simple one way interactions
from an activity to a service, however, they require more complex and
ad hoc programming for extended two-way conversations with their
clients.
In contrast, bound services may be a better choice for more
complex two-way interactions between activities and services. For
example, they support two-way conversations.
So, as you said, If you want to interact with the service use bound service. With started services (or intent services) you could do it, only it would require more complex programming.
(by Douglas Schmidt: https://www.youtube.com/watch?v=cRFw7xaZ_Mg (11'10'')):
Here is a summary that helped me understand (thanks Doug):
Finally, one last link that helped me also:
http://www.techotopia.com/index.php/An_Overview_of_Android_Started_and_Bound_Services
Started services are launched by other application components (such as an activity or even a broadcast receiver) and potentially run indefinitely in the background until the service is stopped, or is destroyed by the Android runtime system in order to free up resources. A service will continue to run if the application that started it is no longer in the foreground, and even in the event that the component that originally started the service is destroyed
A bound service is similar to a started service with the exception that a started service does not generally return results or permit interaction with the component that launched it. A bound service, on the other hand, allows the launching component to interact with, and receive results from, the service.
A bound service is the server in a client-server interface. A bound service allows components (such as activities) to bind to the service, send requests, receive responses, and even perform interprocess communication (IPC). A bound service typically lives only while it serves another application component and does not run in the background indefinitely.
If all the code exists in one activity from user connected to user logout then go for bound service
But if it is code exists in multiple activities try with service
I found out the difference between the two and when to use it. If you want to interact with the service (for example send arguments etc), use bound service and it return the service object in the onServiceConnected method (where you can call methods in the service). You cannot interact with a regular service (from another class)