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
Related
Basically, there is a Google way, which suggests using Service for long running operations (which I use at the time). On the other hand, there are a lot of examples in community by honored developers, which avoid using Service and at most incorporate Fragment's setRetainInstance(boolean retain).
While Google has declared that a lot of bad stuff might happen if we don't use a Service, I still feel anxious because there are, it seems, so many projects leaving Service aside.
Can you consolidate the Google's case or provide suggestions for abandoning Service?
P.S. I'm developing "classic" rest-client applications.
P.S.S. I forgot to mention that Service is used in pair with ContentProvider(for cachging purposes, guard against system app forceshutdowns).
Thanks.
If the network request is very likely to take under a second, or if you don't mind it if your process terminates before the request completes, using simple threading from the UI layer is fine, IMHO.
But once the user leaves your app (HOME, responds to an incoming call, etc.), the lifetime of your process is limited, and it could be very short if you do not have a service to tell the OS that you're still doing important work for the user.
So, if the network request is more in the 1-15 second range, and you'd like to feel fairly confident that the work will run to completion, use an IntentService or something along those lines.
If the network request is likely to be longer than that, such as a large download, now you have to worry about the device going to sleep and such. My WakefulIntentService was designed for this sort of scenario, where it will keep the device awake long enough to get the work done, then let the device go back asleep.
Some developers use services for all significant network I/O, skipping them only for truly ephemeral stuff like thumbnail images to populate a ListView or RecyclerView. So long as the service is only running when it is actively delivering value to the user, this is perfectly fine.
In my app, I'm using a contact sync adapter, but it has a lot of information that it shares with the main app. There are settings that the adapter needs to work proplery (like login information and if the user changes any sync settings), so I currently have it running in the same process, and it communicates with the main ap using getApplicationContext(), and then I have some shared variables in the Application that the sync adapter is using during the sync process.
But in the training document, and a few tutorials online, the sample adapter is set up to run in its own process -- it's using android:process=":sync" in the manifest. Is that necessary? And if it does run in a separate process, how can I communicate back to the main app?
In our context, due to fast searching requirement, we are using remote service to hold a huge database in memory.
The reason we are using remote service, instead of local service is that, we believe running the service in separate process, will make us harder to hit maximum memory per process limitation (The limitation is vary based on different devices and OS version).
In our initial design, we are using AIDL. Later, we switch to Messenger. I cannot recall the reason behind. I will check back our source code history log to figure out why. But, I think it is mostly, Messenger is less complicated than AIDL, and we do not need the multi-thread capability provided by AIDL.
Running Service in its own process may be helpful
1) if you want your service to withstand your main app's process destruction (but START_STICKY is more than enough for that case),
2) if you'd like to designate this process for all "sync" tasks of your application (as stated in the tutorial),
3) if you want other apps to use your Service.
To communicate with the Service running in separate process, you use Bound Services.
However, running Service in separate process increases the complexity of communicating with it, so consider if any of cases mentioned above relates to your app purposes.
I think it should be separated, but it's not required.
In general, separating a Service process is well worth to consider if it may be used independently from system components or other applications. In this perspective, the lifecycle of the process should be managed independently from other components such as Activity in the same app, so Android can mark which process is currently used easily and precisely to decide which process to be killed in case of a memory shortage. Also the service can keep running even if the front activity crashed unexpectedly.
It's hard to maintain sharing data between separate processes. For login credentials and preferences, I guess you may go with a combination of SharedPreferences and OnSharedPreferenceChangeListener.
When the application starts, it may cache different things, in particular for the UI. By splitting the sync logic in a different process, you allow the UI process to be killed when the device is running low in memory, which will free these UI caches.
Hence, this technique is primarily of interest to apps that run services for a long time. Typical examples:
the service that plays music in a music app
the service that uploads the video in Youtube
However:
this increases the complexity of the app
if done incorrectly, it can actually increase the overall memory footprint of the app
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've just recently started working with the android framework and am looking for advice/design patterns to use for the following situation:
Application is a server/client structure. The server should be running at all times (or at least be recreated shortly after termination), but the client can close as need be. To accomplish the server, I understand that I want to extend Service and use START_STICKY functionality and run it in the background.
The part where I'm a bit lost of how to proceed is that I want to create several persistent network connections inside the server. It is important that the connections are threaded and can run asynchronously. A lot of documents point towards using AsyncTask for this, but I don't need to reference the UI thread at all from the network threads and the connections wont ever be terminated, so I'm hoping someone could point me in a better direction?
My conceptual idea was to have the network threads bind to the service to store events, and the client can then also bind to the service to retrieve the events. I'm unsure of the structure to use for these network threads.
The server should be running at all times
There are very very few applications that need this. Statistically speaking, yours probably isn't one of them. Users attack people like you with task killers and the like, plus give out one-star ratings on the Market for harming their use of their device. I strongly encourage you to reconsider this design decision.
so I'm hoping someone could point me in a better direction?
Plain old ordinary Java threads are just fine. Depending on the nature of the threads, you might consider using a thread pool. This part is not significantly different than in other Java environments. Bear in mind that the vast majority of Android devices today are single-core, and you only have so much heap space (as little as 16MB), so having tons o' threads isn't exactly great.
My conceptual idea was to have the network threads bind to the service to store events
The network threads are part of the service, and therefore don't need to bind to it.
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.