I know that an activity can communicate with a local service using the IBinder interface; I am trying to find a way for communication between two services.
Specifically, I have my main service starting an IntentService to handle file uploads. I want this IntentService to inform back to the main service once it is done uploading, and before it dies.
Any ideas about how this would happen?
You have to use BroadcastReceiver to receive intents, and when you want to communicate simply make an Intent with appropriate values.
This way you should be able to make a 2-way communication between any component.
In Android, there is a special way of completing tasks like yours. Look at AIDL (it's not well documented in official docs, but there are some extra sources on the web). This is a way of implementing two-way communication between any components placed in separate processes. In comparison to BroadcastReceivers, using this you'd get direct calls and callbacks, that will be less dirty than relying on something would come from somewhere in BroadcastReceiver.
To reach the needed effect, you'll have to define an interface for a callback and an interface for performing actions (with a callback supplied, or register/unregister methods). Than, after you received some command using the second interface, you should perform the job and post back the result through callback. To reach the asynchronous completion add a key work "oneway" before method signature (return type). To separate in and out params (if you need it), use "in", "out" and "inout" keywords near params.
As it comes to restrictions, only primitives, arrays and parcelables (and parcelable arrays) might be transferred between processes.
To control your callbacks lifecycle and operations atomicity, use RemoteCallbacksList for storing registered callbacks and notifying recipients using the duplicate of your list got from beginBroadcast.
If you have any troubles, you're free to ask here.
Related
I'm writing an Android library that is inherently asynchronous (waiting for events from a USB device connected to the micro USB port). Looking at how Android packages implement asynchronous APIs, I found a few different ways:
Taking a PendingIntent and sending it when an event happens (For example: UsbManager.requestPermission(), NfcAdapter.enableForegroundDispatch()).
Defining an internal callback interface and taking an instance of it, and then calling it when the event happens (Examples include View and its subclasses).
Taking a "broadcast action" as a String and then broadcasting that action (possibly locally using LocalBroadcastManager) (Example from IntentService documentation).
Having a purely synchronous API and letting the caller call it asynchronously (in an AsyncTask for example) (For example: SQLiteOpenHelper.getReadableDatabase()).
How should I design my API? And are there any recommendations for when to use each kind of API?
The main question is whether you will desing an API that is synchronous or asynchronous.
Synchronous API
API user will need to create a thread/AsyncTask (or similar) manually, so it's a bit more work on that side.
it's easier to misuse it - for instance by running a blocking method on the main thread
it's easier to reason about than the asynchronous API, because the code flow is streamlined and linear.
Asynchronous API
it's safer on the caller side (will never block UI)
tends to be (a bit) harder to use because of the callbacks (or intents, broadcasts listeners etc.)
If you opt for a synchronous API, you're pretty much done ;)
But if you opt for the asychronous one, in Android case (as you listed already) - you'll need to decide how the API implementation will notify the caller about the asychronous action being completed (or status being changed etc).
The PendingIntent is ususally used for a limited set of actions (i.e. launch an activity or a service, or send a broadcast). I assume your library client will want to do more varied actions than that.
Broadcasting an action is an option. It will separate the client from the library by "the intent wall", though. So for instance if your library would like to return some complex data structure to the caller, this data structure would need to be parcelable to fit into an Intent. Broadcasting is also a way of, well, "broadcasting" something. This means that multiple listeners could pick the message up.
Having that said, I would prefer to use the pure Java solution with callbacks interfaces, unless there is a good reason to use Android-specific solution.
I have a two part question. Both are somewhat general.
I'm creating an app that relies heavily on communication with a server. I plan to have different classes for each repository I'll need. Is an Android service the correct pattern to use here? There may be certain situations where I'll want to cache things between activities. Will a service allow me to do this?
Assuming a service is what I want to use for this, how can I load content once the service is bound. When the user opens the app, I want to start loading content. However, binding a service isn't blocking, so I can't write the code that makes requests with the service in my onStart() right? Is there some helper class that will wait for the service to load then execute a function? I know I could put some code in my onServiceConnected() method but I'd like to stay away from coupling like that.
Hopefully that wasn't too abstract. Thanks in advance.
Yes, Service is the way to go, but a started service, not a bound one.
You could make async request methods, and the Service can broadcast the result back to your Activity.
The async request in this case is a startService(intent) with an
Intent containing the request parameters. The service would start a background thread for the operation, optimally you can use a networking library for this (for example Volley).
And the reply is a broadcast by the Service with the relevant data.
This answers the problem of caching, because the Service can decide what to return. So in case the Service does not have the requested resource, it will download (and return) it. But if the Service has the resource, then it will just simply return the cached version.
To start, you should get yourself familiar with these topics:
Started Services (for the requests)
LocalBroadcastReceiver (for the reply)
Event Bus (alternative to LocalBroadcastReceiver, for example Otto)
I don't know much about your concrete needs, but it seems like you want to implement a REST client with cache. There is a really good Google IO presentation on that here. Definately worth to watch!
1)If you need code to run even when your Activity isn't, the correct answer is a Service. If you just need to cache data, then storing it in a global static variable somewhere may be ok.
2)Your service can start a Thread or AsyncTask. These execute in parallel. onStartCommand generally launches it in this case.
As with most things, the answer to these questions are subjective at best. I would need more information then I currently have, but I'll take a vague, general stab at this...
If you need something persistently hitting your server repeatedly I would say use a service.
Where you call it is not nearly as important as how many times it needs to be called. That being said the answer is yes. If you need this data as soon as the application or activity loads, then the onCreate method is where it needs to be loaded.
My reccomendation is either A) service or B)AsyncTask.
Go with A if you have to hit the server repeatedly for data and need it in regular intervals. Otherwise go with an AsyncTask and load all the data you need into an object for storage. Then you can use it as you need and it will essentially be "cached".
The difference between the two is simply "best tool for the job". I see you use some javascript. To give a proper analogy, using a service for a server call rather than an async task, is the equivalent of using a web socket (node js) when you could of just used an ajax call. Hope this helps. Oh and PS, please don't use static variables in Android =).
(I have a remote service with an AIDL interface that is used by several client apps. I would like to add an asynchronous method to the interface for calls that take some time, but I need the solution to be secure, meaning that only my applications can communicate with the service. The client applications are signed with the same signature as the service app. Currently the apps just bind to the service and call a single interface method to perform various operations.
One option is broadcasting an Intent from the service when the operation is complete and using a BroadcastReceiver in the client application, but (Question #1) can this be done in a way that ensures only my apps can receive the Intent? setPackage() seems to do this, but I need to support Gingerbread devices, which seems to rule out that approach according to the answer here: setPackage for intent in gingerbread
So it seems I need to add a second .aidl interface with the callback interface for the service to use, implemented by the client. I have seen examples that use listeners here, but I am not sure what the difference is versus the client just passing in the second interface object as an argument (as used in the IScript / IScriptResult example from this answer: Service call backs to activity in android)
Question #2, what is the benefit of using a listener here vs. a callback method?
A callback method/listener is the right thing to do. (As CommonsWare says, it's pretty much the same thing). I would say it's much simpler than fiddling around with BroadcastReceivers, since you're already using aidl.
Something like this:
IAsyncThing.aidl:
package com.my.thingy;
import com.my.thingy.IAsyncThingListener;
interface IAsyncThing {
void doSomething(IAsyncThingListener listener);
}
IAsyncThingListener.aidl:
package com.my.thingy;
import com.my.thingy.IAsyncThingListener;
interface IAsyncThingListener {
void onAsyncThingDone(int resultCodeIfYouLike);
}
You can enforce that only your apps can bind to the service by using a signature-level permission on your service (see the note on 'service permissions' here: http://developer.android.com/guide/topics/security/permissions.html). Specifically:
Declare a permission in your service's AndroidManifest.xml. Ensure it is signature level.
Add that permission in your service tag
In all the other apps, use uses-permission to use it.
A couple of other things to bear in mind:
In the caller, you'll need to subclass IAsyncThingListener.Stub. Your calling application code may already be subclassing something else, so that means you'd have to use an extra (probably inner) class to receive the completion notification. I mention this only because this might be the answer to question #2 - which I don't fully understand.
If the service is potentially in different processes from the caller, each should register for death notification of the other using IBinder.linkToDeath.
I am looking to implement the Google IO Rest Structure part A - Using a Service API. So i have identified the following portions of the structure.
An interface that provides rest method.
A Processor Class that implements the above interface. There will
many processor Classes. Each Processor class will return a model
class type.
A Service Provider, that deals with a Single Processor. The data
returned from the Processor is handled by the Service Provider. This
will call the Processor Function, and obtain the data returned.
A SerivceProcessor that is a service class. There will be a
single class in the application. This will communicate with the
various SericeProvides based on the Bundle data passed to it.
Service helper that provides high level integration between the
Activity and the Service
Now i am not clear here. The Service has the data that has been requested. How to proceede further. How do i pass the data back from the Service to the ServicHelper. Put it in a Bundle with the tag BUNDLE_EXTRA ? For this my pojo would have to be either Serializable or Parceable. I know Serializable is a really bad option on the Android Platform. What other options are they. Would i be using a Broadcast Intent ?
Thanks for any help here.
You can do a couple of things.
notifying back to the service helper through intents (letting it implement a broadcast receiver). This might be a bad idea since with a single rest call you can get a lot of rows. In this case you should implement some sort of facility to put your pojos in the intents you are sending back (like a fillIntent/getFromIntent method)
inside the service provider, store the result data somewhere (sqllite, contentprovider, file) and just throw a broadcast intent that will contain only the requestId and the result of your call.
The service helper intercept the broadcast and notifies any interested activity that the request has been completed. The activity updates the ui according to that. In this case the servicehelper is used just to keep track of the ongoing request / notify the results.
In my opinion this approach is better because you keep the ui and the model separated, and you don't demand to the activity the storage of the data, and it's more "rest oriented".
Plus: some time ago I tried to implement this approach. It's not completed but you can check the service helper and the request / result intents here postman lib
A more mature and robust library is robospice, which is what I would use now if I had to deal with rest services.
im wondering if it would be a bad idea to create a Singleton that is used between some Android Activities and a Android Service. As far as I know the static fields, in my case the Singleton, is available as long as the whole Process is alive.
My plan is to use a singleton instead of Parcelable to share data between my activities and a Background service. So my Activity1 will add some data by calling MySingleton.getInstance().addData(foo); then I would sent an Intent to inform my Service that new Data has been added to the singleton. Next my BackgroundService would handle the intent and call MySingleton.getInstance().getLatestData(); then it would process the data (takes some time). The result of the service would next be "post" back by using the singleton and fire a broadcast intent, which are handled by the Activity1 (if alive) and the Activity1 will retrieve the result from the singleton.
Do you guys think thats a bad idea?
EDIT:
What I want to implement is an peace of software that downloads data from a web server parse it and return the result. So my Activity would create DownloadJob Object. The DownloadJob-Object would be put into the DownloadScheduler (Singleton) which queues and manage all DownloadJobs. The DownloadScheduler would allow to run 5 DownloadJobs at the same time and use a queue to store the waiting. The effective Download would be done by the DownloadService (IntentService), which gets informed over an Intent that the a new DownloadJob should now be executed (downloaded) right now. The DowanlodService would retrieve the next job from the DownloadSchedulers queue (PriorityBlockingQueue) and return the Result by setting DownloadJob.setResult(...) and fires up an broadcast intent, that the Result is ready, which will be received by the DownloadScheduler which would remve the job from the queue and inform the Activity that the download is complete etc.
So in my scenario I would use the singleton to access the DownloadJobs from the DownloadService instead of making a DownloadJob Parcelable and pass it with the Intent. So i would avoid the problem, that I have two DownloadJobs in memory (one on the "Activity Site" and one on "Service site").
Any suggestions how to solve this better?
Is it true that static instances, like DownloadScheduler(Singleton), would be used by freed by the android system on low memory? So would subclassing the Application and hold there the reference (non static) avoid this problem?
If you are using the singleton just as shared memory between a background service which I assume is performing operations on a different thread, you may run into synchronization issues and or read inconsistent data.
If the data in the singleton is not synchronized, you have to be careful because you are relying on your "protocol" to be sure that nobody is reading while your background thread is writing (which may lead to errors).
On the other hand, if it is synchronized, you are risking to face anr error because the activity which reads the data may be blocked waiting the service to finish to write the data in the singleton.
As the other said, you also have to keep in mind that your singleton may be freed if the os needs resources, and that your data may not be there anymore.
I'd rather use an event bus such as otto or eventbus
EDIT:
Using a singleton as the entry point of background (intent) service is the approach suggested in 2010 Virgil Dobjanschi talk about building rest client applications for android.
The suggested approach is having a singleton that performs as controller of ongoing requests. Please consider also that request to intent service are already queued by the os, so you can throw several intents that will be processed sequentially by the intent service.
Some time ago I also tried take that as a starting point for a library, which still remains unfinished. YOu can find the sources here
What I would certainly not do is to store your data in the singleton. The approach I would prefer is to store the data in some persistent storage (such as sql / preferences / file / content provider) and let the client know of the change through a broadcast message (or, if you are using a content provider, through an observer).
Finally, to some extent this is the approach followed by the robospice library, which looks quite mature and ships a lot of interesting features such as caching.
A better idea is to subclass Application and put any long living objects in there. By subclassing Application you can properly handle startup and shutdown of the application something you can't easily do with a singleton. Also by using an Application Activites and Services can share access to the models within your program without resorting to parcelables. And you can avoid all of the problems Singletons bring to your program.
You also don't have to resort to storing everything in a database which requires lots of boiler plate code just to shove a bunch of data in there. It doesn't do anything for sharing behavior between parts of your application and doesn't do anything to facilitate communication and centralization of activities. If you really need to persist state between shutdowns great use it, but if not you can save yourself a lot of work.
You could also look into using something like Roboguice which makes injecting shared models into your Activities and services.
You might find this helpful:
what's design pattern principle in the Android development?
Using a singleton like this is not necessarily a bad idea, but you will lose it's state if Android decides to stop your process. You may want to consider storing your state instead in a SQLite database or a persistent queue (take a look at tape for a good example).