Since I am quite new to developing an Android app I would like to ask the more experienced developers how to approach the following problem.
The app that I am trying to build is supposed to do the following:
When the app is running it is constantly receiving various doubles via upd packages. Depending on the double values it will show certain messages in text- and image views on the main activity.
So far I already set up a foreground service (running on an extra thread) which is receiving the doubles. The service is bound to the main activity.
I decided to use a bound service because in future I would like to connect additional activities to that service.
And here are my questions:
Did I choose the right config (bound foreground service) for what I am planing to do?
How can I update my image- and text views depending on the values of the doubles received by the udp service? Can I do this direclty inside the service and only push an update if the values changed?
Thank you very much for your time and assistance on this matter.
Did I choose the right config (bound foreground service) for what I am planing to do?
No objections to the bound Service. Having an interested Activity bind to the Service will ensure it's being kept alive as long as the Activity is considered to be in the foreground.
How can I update my image- and text views depending on the values of the doubles received by the udp service? Can I do this directy inside the service and only push an update if the values changed?
You should not try to update a View "from outside". Only the component (Activity or Fragment) to which the View is belonging should have the right to modify it.
Instead, just notify interested components of changes in the data.
Ideas for intra-app communication:
You could send broadcasts via LocalBroadcastManager
Or you have the Service update a data repository and use LiveData to keep the UI up to date like described in the Guide to app architecture .
Related
I know this look like tons of question around SO. But it's not (although I can also be wrong).
I have a long running Service (running in a separate thread using blutooth socket pooling for data in a OBD2 adapter every 5 seconds).
This Service is running in the same process and is a Foreground Service.
The user start this Service through an Activity. It then connect to the Bluetooth device and start pooling and saving data to a SQLiteDataBase.
The user can then minimize the activity and do other stuff.
When he returns (if ever, he can stop the service through a notification area button) to the application it checks if the Service is running and if so, it starts another Activity which show the data that is being pulled from the OBD2.
My question is, between this visualization Activity and the Service should I use and by this I mean the recommended or the right one:
LocalBroadcast? This is actually what I am using. Every time the service pull some data, it sends a broadcast with the data everytime it was pulled. Then in the onReceive method call runOnUiThread to update the respective View.
Messenger? As far as I know (never used it) I should send a Messenger from the Activity to the Service (much like a Handler) and in the Service it should send the Messages with the data pulled. But from this I would get a RemoteObjectException if the Activity was destroyed (like I said, the user could just minimized the activity and then it got GCed). So, I would probably need a way of sending the Messenger to the Service every time the Activity gets created and check if it's ok to use the messenger form the Service every time (if that's even possible, I've never used this).
BindService? Should I bind to the service when I open the Activity and then get the data directly from methods in the Service? But this would probably mean I would have another thread in the Activity gets this data from the Service every time, right?
Handler? (for a moment now I realize don't know the difference between Messenger and Handler, should it be that "use Messenger when Service runs in another process and Handler otherwise)
I've seen/read a lot of answers here in SO and through the web in general.
But in the end I don't see a ultimate answer for my case. But I'm sorry if this is just because I couldn't figure it out.
Thanks in advance!
EDIT: forgot to mention, I would rather make use only support libraries and android framework stuff, I'm still learning Android and I want to understand what's happening within its own classes.
I'm making an app in which i want a process always run in background e.g in facebook we got a notification and it will notify in our app. Kindly text.
Try Services and BroadcastReceiver to do this.
guess you need to explain the function you want in a detailed way.
Usually we will use a Service
or a Intent Service to do what you mentioned. If you want to detect a change in your application or the phone, you may register a broadcast receiver or a Content observer in the service depends on the function and effect you want.
But bare in mind that, service do not have UI so you should avoid to interact with users while using Services.
From my understanding, service can do most of the tasks you want. One example is play music. You can run a service in foreground if you want to ensure that the services is harder to be killed by the system when memory is low.
Intent service is used to handle asynchronous requests (expressed as Intents) on demand one followed by another. One good example is downloading a file
For Content observer, you will observe a content and the observer will react to if when there is any change from the "OnChange" method.
For broadcast receiver, usually we will use it to observe something happen, for example, screen unlocked, boot completed, sms received.
It really depends on your needs in order to decide what kind of services you want. Please explain in details in order to get more information.
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 service that downloads some data from internet and periodically sends progress to the indicator activity. In the end of processing service sends a result.
I have a question what is the best way to achieve persistence of the communication.
Messenger or ResultReceiver, I need to parcel them into Intent and store list of listeners in the service. But on configuration change activity destroys, and it's hard to maintain this list.
LocalBroadcastManager, I need to migrate from Messages to Intents, and also there is no sticky send in this class. So if I get result while my progress activity is in background result will be lost.
BroadcastManager is good, but I don't need to broadcast my progress system wide, and security issues.
Any ideas?
You may want to give Otto (http://square.github.io/otto/) a try.
In your service, whenever you want to communicate with the activity, post a new event using a shared Bus. You should do that on main thread with a handler or main looper since you are probably using IntentService. The service may act as a producer as well. When your activity is recreated, current known value will be posted.
Your activity just needs to register with the Bus and subscribes to the right event. When it is paused, just unregister with the Bus.
I belive the best way to achieve that persistance is:
After the service downloads, you should save your data in a database or a file.
The service then sends broadcast to update.
If the activity is "alive" all goes well and it goes to the database/file to get the updated content.
If the activity was killed or something, you just have to make sure the data is in the database/file so that when you start/restart the activity you can get the latest content from database/file.
While downloading keep a state and progress saved in the db/file the same way.
Check this Google I/O Session, it explains this really good.
Use static variables inside your Application class (extends Application). Inside Service you set this variables. Inside Activity you read periodically this variables.
You should use massenger to send download progress, because it is more secure and less expensive method then broadcast receiver.
I am having some trouble creating a NON-IPC service that allows adding/removing multiple listeners at various times, for example, I would like to be able to contact the service and "subscribe" to its events any time, or "unsubscribe" from it. The service wakes up every once in a while and sends an event to all subscribed listeners.
I have been looking at stackoverflow examples, googling, etc, particularly I found something similar here:
android restful api
In that example, the suggestion is to use ResultReceiver to serve as a callback from a service. But in this approach, doesn't it mean that the service can only notify listeners sent to it as part of the first intent (i.e I cannot add/remove listeners whenever I want)?
Also, in that example, what happens if the activity gets destroyed by the OS for some reason, but the service still has a reference to the listener and tries to invoke it? The listener will try to perform some action on the activity, which no longer exists, right?
Maybe I am missing something... I'd appreciate some input if possible..
Tnx
First, 'sleeping' services are anti-pattern in Android. If you need to do something periodically, start your service using AlarmManager. Second, the service can be restarted at any time, so you cannot rely on 'subscribing' where you keep references to other components (activities mostly). If you need to send a notification to multiple activities, use a broadcast receiver. Activities can register for it statically (using AndroidManifest.xml), or dynamically (with code).