I can find several examples of how to build a service, but I'm having a difficult time finding a working example of how to send messages between an Activity and a Service. From what I can find, I think my options are to use Intents, AIDL, or to use the service object itself as per this question.
In my case, my activity is the only activity that will ever access the service, so a local service will do. When the activity is open, I want to see some status messages from the service, which will be coming in at up to 20 Hz. Are there any limitations on how many messages per second those communications methods will support? Basically, which method is going to be best for my situation?
Thanks.
Since your Actvity and Service are a part of the same app, then no need to use AIDL. You may simply use your Service as a local one.
The limitation is only affected by the performance of your device. There is no cap on requests per second.
Usually there is a context switch involved, that uses quite a lot of cpu (compared to other parts of the transmission), but since you use a local service you don't suffer from that. In any case, 20Hz is not a problem.
The best solution for you would be to use AIDL, and set up a callback that the service can call to report its status.
There is good example of how this is done in the APIDemos.
Related
I'm trying to develop an Android application consists of an Activity and a Service. The Activity launch a process on the Service of indefinite duration, which will be closed from Activity. Do not use then the subclass IntentService, but directly Service. Controlled by onStartCommand and OnDestroy.
I obviously need to pass information from the Activity to the Service: the status of the Service and some strings.
I tried to use LocalBrodcastManager, but when turning the devices or when the activity goes in state onPause, the message will lost. I tried to follow several examples, but with little success. This in particular I could not complete it because of some missing information, evidently deemed obvious, but which are not obvious to me: https://developer.android.com/training/run-background-service/report-status.html
I then tried to use Messenger via IBinder ( Example: Communication between Activity and Service using Messaging ), But the program seems a bit complex and I can not able to fit my needs.
What I need is to launch the service from my activity (possibly make binding automatically?, in case of Messenger use), the Service should signal the Activity to be active, then Service records some points via GPS LocationListener, writes it to a file and should point out, again the Activity, the data that is recording, the file size, etc.
What do you recommend to use to pass this information and can you provide to me some example?
I am actually in the midst of a tutorial explaining and comparing many different approaches to IPC in Android but since it's not ready and because you need an easy fix i'll recommend https://github.com/greenrobot/EventBus.
Also feel free to look in an old but still relevant example me and my friends made a while back here: https://github.com/RanNachmany/AndconLab
Goodluck.
I have been developing for Android for little less then 2 years, and I am still puzzled by this seemingly simple question.
When should one implement a service?
From my experience there are some rare cases but I am questioning this because on every phone there are quite a lot of them running and I doubt it's just a poor application design.
This is essentially core of my question but following are some of my experiences and thoughts about the subject which can explain my question in more detail.
In all apps that I have developed only one really required a service. It was a background sound recorder and I was using it as Foreground service with notification since I wanted buttons to be able to control it (like music players do for example).
Except this I never really saw a requirement for the constantly running service because:
A) Intent listeners (Manifest registered BroadcastReceivers) are quite a useful feature and using them as you know is usually enough for many use-cases (for example showing notifications).
B) If scheduled execution is a must one can subscribe to alarm events.
C) I know that service in Android is quite different then for example in Windows since in Android services are just a "package" to organize your code in and have a the system manage the lifetime of the object. Services use the Main Thread but it's customary to spawn new threads in them.
D) In the development documentation services are suggested for network communication and background calculations but I don't get why you should not just use AsyncTasks for that. I am a big fan of these and use them extensively for lot of things from downloading data from the internet to doing FFT calculations under time critical conditions.
E) I get the usefulness of Foreground services but why are people using background services so much (excluding the system apps).
Those are my thoughts about the SERVICE and I hope someone with more experience will be able to explain these PROS and CONS (along with others that I probably missed).
When should one implement a service?
When you have work -- delivering value to the user -- that:
Needs some time to complete, perhaps longer than you have time for in the component wishing the work to be done, or
Is delivering that value under user control (e.g., music player, controlled by play/pause buttons in a UI), or
In rare cases, needs to be running continuously, as it delivers value continuously
there are quite a lot of them running and I doubt it's just a poor application design
Some are likely to be poor implementations, either due to technical misunderstandings, or other concerns (e.g., making marketing happy) trumping making users happy.
It was a background sound recorder and I was using it as Foreground service with notification since I wanted buttons to be able to control it (like music players do for example)
That is a reasonable use for a service, IMHO.
Intent listeners are quite a useful feature and using them as you know is usually enough for many use-cases (for example showing notifications)
I assume that by "Intent listeners" you mean manifest-registered BroadcastReceivers. In that case, if the work to be done by the BroadcastReceiver will take more than a millisecond, that work should be delegated to an IntentService for completion. onReceive() is called on the main application thread, and it is not safe for a manifest-registered BroadcastReceiver to fork a bare thread, as the process could go away shortly after onReceive() returns. However, in these cases, the service is usually short-lived (e.g., do some network I/O and disk I/O, then go away).
In the development documentation services are suggested for network communication and background calculations but I don't get why you should not just use AsyncTasks for that
An AsyncTask is a fine solution for background work that is:
Requested by the UI (activity or fragment), and
Will take less than a second or so, and
Is non-critical
For example, if you are downloading avatars to show in a ListView, AsyncTask is probably a fine choice, whether you use them directly or use some image-fetching library that uses them internally.
Conversely, if the user buys an MP3 through your app, and you need to download that MP3 file, an AsyncTask is not a good solution. That could easily take over a second. While the download is going on, the user could switch away from the app (e.g., press HOME). At that point, your process is eligible to be terminated... perhaps before your download is complete. Using an IntentService to manage the download is a signal to the OS that you are really doing work here, adding value to the user, and so the process will be left alone for a little while.
Note that if the background work might take 15+ seconds, WakefulBroadcastReceiver or my WakefulIntentService is probably a good idea, so the device does not fall asleep while you are trying to wrap up this bit of work.
I can name some of the Service uses from my experience:
to implement
location listener,
sound module, generating various voices
in app content updates,
API, provide services to other apps
in app billing
Communication with webservices (if requests frequency is high)
actually (excluding 5.) they all are working for the whole app duration, they are using some of the other android services, also they manage their state. I suppose one of the important thing here is state management during application life cycle changes.
I prefer to look at AsyncTasks in a same way as Executors (ExecutorService), they should be executed sequentially and for small tasks.
In the android website, you can find a table when to use Service, Thread, or WorkManager (the new API for scheduling jobs, currently in alpha as of this comment posted). https://developer.android.com/guide/background/#table-choose
The website also state that you need to use started service only as last resort. The Android platform may not support started services in the future. Refer to this link https://developer.android.com/topic/performance/scheduling#services
You should avoid using started services that run perpetually or perform periodic work, since they continue to use device resources even when they aren't performing useful tasks. Instead, you should use other solutions that this page describes, and that provide native lifecycle management. Use started services only as a last resort. The Android platform may not support started services in the future.
If you consider UI and bound services, u would think that both can exist and not be doing anything for certian periods. In such scenarios, your UI can be recreated a lot of times however service does not. And this is where service is important. Lets say you are processing images and then rotate device you want processing to continue while UI is being recreated. You recording a voice and then rotate device. These are one of the places where I find service very important. (Having lot of heavy data processing, interaction with web, that could be few seconds)
I'm a beginner in android development and I'm trying to implement an android udp client, which connects to a java server and sends/receives some packets from it.In this process it collects some data (like round-trip delay etc), which is used to measure the QoS of that particular network. I have tried implementing the connection and sending/receiving data using Java Threads, but the application crashes, and hangs if i try to use more than 2 threads. So I'm looking for alternatives. While going through this site as well as some other links I found that in android multiple threads can be implemented using AsyncTask, Handler etc. Also I found that the Service class also helps to run a background service in an app. Please suggest which approach among these would be the best to achieve my purpose.
Thanks in advance.
You can use AasyncTask to do this and as you mentioned service may be useful too, where u can let your application do whatever it wants in background , if user needs to use application by its interface then AsyncTask must be used to avoid Crashing
There is not one right answer that can be applied as a broad stroke to how to do Android multi-threading. There are a few different ways to approach it based on what your specific needs are.
Any long running, blocking call, in Android will result in the application crashing.
The most common solution is to use an AsyncTask though. For example, when I want to make a call out to a web API endpoint for some XML data within an Activity I would in this case use an AsyncTask and kick off the calls from within doInBackground.
This is not an appropriate solution though if the wait time is longer, or possibly an unknown wait time. Or in a situation where there will always be waiting such as a message queuing service. In this type of situation it may be best to write a separate app based on extending the Service class. Then you can send/receive notifications to/from the service from your primary application in a similar manner to how you would communicate with a web service.
As relatively new to the android platform I was given the task of implementing a email client. For this I want to use an service that allways run in the background (client should allways receive emails as soon as the server gets them, requirement from the customer).
Now I've looked into the Service's in android, but can't seem to find any good answer on whether or not the Service should be local or remote.
What would the main advantages/disadvantages be with choosing one over the other? Bare in mind the Service must be running at all times. I know, I know. BAD. But it is essential to core features of the application.
First, the correct/efficient way to do instant notifications from a remote server like this on Android is to use Google Cloud Messaging. GCM lets you remotely wake up the device by sending an Intent to your application, which you can then use as a signal to fetch the message from the server, post a notification to the status bar, etc.
Doing what you're describing with an eternally running service will have a significant effect on battery life unless you get everything exactly right. Keeping the phone awake all the time is not a viable option. Use GCM and do not roll your own solution for this.
But since your question was more general about whether to run a service in a separate process, in general simpler is better and in this case simpler means running in the same process. You'll have access to all of the various elements of your app's process in memory and in general you will probably have a much easier time. Your events will all happen on the same main thread's Looper. Everything will be much more straightforward.
If you don't already have a very good reason for using a separate process for your service, you should run it in the same process.
Generally I don't know the reason why you can want to use another process. If you will - you'll have to deal with Inter-process communications, with all this AIDL, Parcels etc.
And if you will keep the same process - it will be much easier to transfer the data between your components.
The only reasons to make several processes I think is to try to avoid Android Heap budget limitation. You can try to move heavy objects between processes and try to double your limit. However I think you don't need this, also it's bad way too.
So I will recommend not to play with processes and keep things as simple as possible.
Good luck
I'm writing an application with 3 mapactivities, and i've implemended a local service(like google tutorial) that recives update from location manager, to share location data from gps between these activities.
Now i want to put every activity in separated process to follow google's suggestion.
So my question is how I have to proced??
Implement and AIDL interface for remote services or register every mapactivity to location listener??
Thanks for answers and sorry for my bad english :P
If it's just a single application that needs location information, then using a remote service and AIDL is an unnecessary complication. The easiest way would be to have a local service with which the activities can bind, then have the service use sendBroadcast() to send location information. The activities can then register a BroadcastReceiver to pick up this data.
First the rationale:
That quote in the Javadoc is a bit... weird. If you understand "running" as being between onResume() and onPause(), then normally two Activities belonging to the same Application cannot "run simultaneously". You would probably have to mess with the Application class or the OS itself to have it behave otherwise.
To wit, I'm actually developing an app at the moment that uses several MapActivity subclasses and haven't encountered any problems so far (i.e. 40+h of development and testing, both on emulators and a device).
Therefore I would suggest:
Try to implement your app as a single-process activity with a local service and just run with it.
If you don't want to do that (can't blame you ;) ), or you encounter any problems, I would suggest starting out with a MapView, perhaps encapsulated within a Fragment. Here's a discussion to get you started.
In short, due to Android's practical fragmentation, keeping your Activities in one process and commiting more time by starting with a more bare-bones implementation will be a safer, ultimately less time-consuming and probably more efficient approach than artificially splitting your app and potentially gritting your teeth on the IPC. At least in my opinion.
After some research i think the best way is to implement IPC with a messenger like described in Android doc http://developer.android.com/guide/topics/fundamentals/bound-services.html#Messenger.. I'll test this solution an report here the result..
Best tutorial is http://developer.android.com/reference/android/app/Service.html#RemoteMessengerServiceSample where is implemented a 2 way communication from client and service..