I have a service running in the background. Based on some condition it has to start some activity. Activity has to send back the response.
I did google search and found out we have to use Notification mechanism. But I am not clear how to send the response back from activity to the service running.
Also service is collecting sensor data(acclerometer, gps). So should activity be started in separate thread so that collecting sensor data is not affected.
Please clarify.
Activity would be started in main UI thread, instead, your long-running service should run in and manage its own thread, since according to the document, service is also created in main thread.
Basically the best way to communicate is to use Intent. This allows loose couple of sender/receiver (i.e., activity/service in your case). Intent is a large topic in terms of android, and yet it is one of the most fundamental one, I think you should look for tutorials online about it.
If your activity is opened and return the result after completing the task of Activity then you can use startActivityForResult and then return the result.
Using of notification is simple, just create a interface class, and implement the class in your service. When you need to send data back to service, you can just call the appropriate method with data.
Related
So basically what i am trying to do is i want a service that runs in background and updates the LatLong to the server. This operation needs to happen all the time even if the application is running or not.
Now when the application is launched i want the service to calculate the distance between the latlong and update the UI in addition to the work that it was already doing i.e. updating the latlong to the server. i want the service to do the additional work for multiple activities. lets say i launch the application and i am on Activity A, onclick of a button on Activity A the service starts updating the UI and when we click gain it stops updating. Now i am on Activity B and on click i want the service to do some work in addition to the updation of LatLong and update the UI.
What would be the best approach to achieve this.??
EDIT
The problem i am facing is not getting the service update the UI but making the activity communicate with the service when it has already started.
i can pass on some data when i am starting the service but how to communicate with the service when it has already started. How to tell the service that see you are already running and doing some operations now you have to perform some more operation on top of the previous operation.
I can make some static method in the service and call them when i need to perform the extra operation but i dont wanna do that.. i want to better approach.
Here is the basically services runs on the same main thread process as ui. When you want make it run continuously you have run it in your tread. In this way you avoid service being get stopped as application go in background or killed. (Please take look at Service.START_STICKY flag, this is what you need as i guess).
And more coming your second problem of activity getting updated with service information or data that is being collected for this you need look at " How Bind the service". (In activity check for service connection and Binding to a activity, Unbindibg is also there have look at it also). Activity has all the call backs for it you need to implement binder.
EDIT
Service to update ui has to have send and receive intent mechanism. You can broadcast and intent from the services check your activity is running or not. If running broadcast intent and have receiver in activity to listen it.
You can do it by interface mechanism too
I am new to android development and having trouble understanding how I should use service's and more specifically which kind. I am developing an simple system that only will do to things. One of those to is to continuously ask a server simple telnet questions. The answer to these questions should be prompted on the screen.
So to simplify my question. What kind of service should I prefer? bound, intent service etc?
I presume it has to run a own thread since it is suppose to do network comm, so how should I do that.
Finally and most importantly, how do I supply/give the MainActivity the information the service has gathered and post it on the screen?
What kind of service should I prefere? bound, intentservice etc?
A bound service runs only as long as another application component is bound to it. With other words, if an activity bounds to that service, and later that activity gets finished, the service also gets destroyed.
So, first decide the behaviour of the service you want to have. Do you want it to be destroyed when the activity bound to it gets destroyed? If yes, then perhaps a bound service is the right thing to do, if not then use a started service instead which can run in the background indefinitely, even if the component that started it is destroyed.
I presume it has to run a own thread since it is suppose to do network
comm, so how should I do that.
Yes, you are right. You can use the Service class and create a thread inside it that will do the heavy work, or, you could simplify things by using an IntentService which provides its own worker thread.
Finally and most importantly, how do I supply/give the MainActivity
the information the service has gathered?
If you decide to go with a bound Service, then you'll be able to communicate with the service through a so called binder object. On the other hand if you go with IntentService then you could use a ResultReceiver, or a BroadcastReceiver to send the result back.
Suggested readings:
http://developer.android.com/guide/components/services.html
http://developer.android.com/guide/components/bound-services.html
Here is a quick summary on services in Android, hopefully this will help in deciding what approach to go. Reading Android Services is highly recommended
Android Service
"A Service is an application component that can perform long-running
operations in the background and does not provide a user interface"
runs on the main (UI) application thread.
it is given preference over activities in termination when resources
are low
it is not intended to interact directly with an activity/fragment (an activity may be destroyed at any time) no simple callback ability due to above... however there are some ways to address this using Intents, Handlers and Messages
an activity can be bound to a service which
basically gives an instance of the service to call methods, the methods will run on the main thread, a suggested way to use a separate thread, is to use Executors
I'm developing an app with a service that forwards calls to a web-service, and a few activities that place those calls. The activities need to process the results of those calls. For example, I have a writeComment method on the service, that accesses the web-service and returns some information about the newly written comment.
Right now I let the Activity take care of all the threading. The Activity binds the service, and then uses an AsyncTask that calls the bound service's writeComment method.
All works well as long as the Activity isn't stopped while the AsyncTask is running. If it does (easily happens when flipping the phone), the AsyncTask dies a violent death when trying to update the UI in onPostExecute. I'm not entirely sure how to fix this - I do need to let the user know the server has been updated.
If I go the other way around, and register a callback with the Service, I'm still a bit stump, because I need to notify the Service the Activity has changed - I need to tell it not to notify me in the first Activity's onDestory, and reregister in the second Activity's onCreate. And I need to handle the case where the asynchronous task completes after onDestroy and before onCreate.
What is considered Best Practice in this case?
Thanks,
Itay.
My intuition tells me to let the service handle the threading. Services are far less transient (although still transient to some degree) than activities and therefore you'll have less issues of threads trying to interact with a Context (be it an Activity or a Service) that's no longer there. Have you looked at the IntentService class? It handles a lot of the threading for you.
In my app, I have a long-running service and Activities that need to render data in the service. The service also pings the Activities when there is a change but the Activity can also query the service. The way I approached this was two-fold.
Firstly, I bind my activity to the Service in order to send messages from Activity to service.
Secondly, the Service sends notifications with Broadcasts and the Activity listens for those broadcasts. I set that up in the Activity onResume and tear it down in the onPause. I think this is the part that you're missing.
I am currently writing an app, which consists of a service and an activity. The service is running in the background, doing some live audio processing. If the user want to get some information about the running service or want to change the settings of the service, the activity gets started and bind to the service.
Currently i am using the asynchronous messenger system to communicate between the service and the activity. For example, the service can send some results to the activity through a message and the activity can handle this message and show the results. This works fine, but it is stressful to write the messaging stuff for each communication. And it is not always needed. Sometimes i only want to ask the service, if a flag is set or not. If i do this asynchronous, i have to send a message to the service which asks for the value of the flag and the service has then to send a message back to the activity to answer the request.
So i want to have some getter and setter which can synchronously access the service. This can be done by using a binder, which works too.
The problem is, that i sometimes need synchronous communication to get the value of flags etc. and sometimes i need asynchronous communication to push the results from the service to the activity. So what i need is a binder and a messenger. But i dont know how this can be done, because the service can only return one object from the onBind() method, either a binder object or a messenger object.
Do you have any suggestions how this can be done or some other approach to realise asynchronous and synchronous communication between an activity and a service?
Thanks in advance!
Tobias
If you are already binding to the service, your activity can supply a listener object to the service, which the service will then call when events occur.
You just need to make sure that you unregister that listener object before unbinding from the service, and do both before the activity is destroyed, so your service does not wind up with a strong reference to a defunct activity.
I've created an application which does synchronization with the server.
I've already have a code, which does synchronization once user pressed a button. Now it is time to add Service there.
I have the following questions with regards to the services on android:
will the service be started if user never run application before? (i.e. just installed that)
when the service will be started first time? can I start it from onCreate of the main application?
if user presses Synchronize button in the application, should I start that Service or should I have different process for the same? How can I check then that background synchronization is not happening at the same time?
should I use ASyncTask, even if the service is started as
startService(new Intent(this, ServiceSync.class));
The preferred approach to syncing data in Android is providing a SyncAdapter to perform the sync. You have a very nice summary of the required steps in this post.
You will also find these articles useful.
Edit:
1-2-3: You can use a bound service to manage the interaction and service methods from your activity. You have full working samples in the link provided. Basically, you bind to the service in your activity's onStart method and unbind onStop.
Remember that a service runs on the UI thread, so every time-consuming task such as fetching data over the network must be done in a separate thread.
4: You don't need an AsyncTask here.