I am clear with the concept of Intent but one thing i didn't understand is why should the Intent be a asynchronous message call.
why should the Intent be a asynchronous message call.
API calls are synchronous while intent-based invocations are
asynchronous.
API calls are compile time binding while intent-based calls are
run-time binding.
It is basically a passive data structure holding an abstract description of an action to be performed.
How it works?
Intents are asynchronous messages which allow application components to request functionality from other Android components. Intents allow you to interact with components from the same applications as well as with components contributed by other applications. For example, an activity can start an external activity for taking a picture.
Intents are objects of the android.content.Intent type. Your code can send them to the Android system defining the components you are targeting. For example, via the startActivity() method you can define that the intent should be used to start an activity.
An intent can contain data via a Bundle. This data can be used by the receiving component.
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 am new to android and am currently reading a book called 'Professional.Android.2.Application.Development'.
I have seen some of the code given to me to start an application development and I have noticed that most of the java code consists of intents.
I want to know why we are using intents and not events or services.
All I know about intents are that they are an abstract description of an operation to be performed.
I also want to know the importance of intents in android.
Can anyone please explain it to me as I am new and a little bit confused.
What is a Intent ?
Intent is basically a message that is passed between components (such as Activities, Services, Broadcast Receivers, and Content Providers). So, it is almost equivalent to parameters passed to API calls. The fundamental differences between API calls and intents’ way of invoking components are:
API calls are synchronous while intent-based invocations are
asynchronous.
API calls are compile time binding while intent-based calls are
run-time binding.
Of course, Intents can be made to work exactly like API calls by using what are called explicit intents, which will be explained later. But more often than not, implicit intents are the way to go and that is what is explained here.
One component that wants to invoke another has to only express its’ intent to do a job. And any other component that exists and has claimed that it can do such a job through intent-filters, is invoked by the android platform to accomplish the job. This means, both the components are not aware of each other’s existence and can still work together to give the desired result for the end-user.
This invisible connection between components is achieved through the combination of intents, intent-filters and the android platform.
This leads to huge possibilities like:
Mix and match or rather plug and play of components at runtime.
Replacing the inbuilt android applications with custom developed
applications.
Component level reuse within and across applications.
Service orientation to the most granular level, if I may say.
Here is additional description about intent, almost formal.
An intent is an abstract description of an operation to be performed. It can be used with startActivity to launch an Activity, broadcastIntent to send it to any interested BroadcastReceiver components, and startService(Intent) or bindService(Intent, ServiceConnection, int) to communicate with a background Service.
An Intent provides a facility for performing late runtime binding between the code in different applications. Its most significant use is in the launching of activities, where it can be thought of as the glue between activities. It is basically a passive data structure holding an abstract description of an action to be performed. The primary pieces of information in an intent are:
action
The general action to be performed, such as ACTION_VIEW,
ACTION_EDIT, ACTION_MAIN, etc.
data
The data to operate on, such as a person record in the contacts
database, expressed as a Uri.
On this data structure is that the android is implemented as you read the following documentation is very helpful:
Android Intent first documentation
Android Intent second documentation
Android Intent third documentation
Android Intent Native documentation
I am wondering when I should favour an intent based approach over a classic oberserver design pattern in my Android app.
Would it be wize to use intent's to publish events within one activity?
Definition
Observer maintain a list of dependents to notify a change. On the other side Intent is an abstract description of operation. Which can be received by same or multiple application to perform a task.
Synchronous VS Asynchronous
Observer is synchronous as the changes effect right-way. Intent is asynchronous.
Binding
Observer bindings are compile time. On the other side intent bindings are at run time
Secure
For internal communication observer is much secure as Intent will broadcast message and anyone can receive the message.
Intent provide additional functionality over Observer on Android platform
Communicating with third party application and processes.
Receive system notification to perform a task
Application module reuse by third party app. (Ex taking pic)
Intent stays around and your app can retrieve data in some later time (Sticky Intent)
Would it be wise to use intent's to publish events within one activity?
This will depend on your requirement. Look into your requirement to see which one needed.
I think not because a new intent will usually bring a new activity unless your activity has been declared as single top. Anyway intents do not resemble observers much. A Handler can be a better approximation.
I'm developing restful android application, but I'm still newbie to android, and I would like to avoid beginners bed structural design that would cost me troubles latter.
I've read lots of discussions about android services and restful applications, many of them contrary to each other, so I would like to know have I choosen a good approach.
Inspired by this presentation http://www.youtube.com/watch?v=xHXn3Kg2IQE I put my http requests into IntentServices, instead of the Async Task.
I've choose Intent Service because of:
as a services they are not sensitive to foreground/background switching like Activities (won't get killed).
Intent service provides work in separate thread, so the user interface stays responsive.
Since Intent Service cannot run multiple request simultaneously, I've "split" my domain into few groups and for each group I have written my Intent Service. (ends up in: one CRUD set -> one intent service)
This way I got that inside of a group can be only one request running at a time (And this is good for me, since this way it could never be executed for example update and delete at same unit).
And, on the other side, I can run multiple requests at the same time if they are from the other groups, and don't affect each other.
So basically, I have this:
one generic HTTPRequest class that builds requests from name value pairs
UserIntentService - creates user related requests and executes it by using HTTPRequest cass, and proccess request using UserProcessor. Notifies caller by intent with data.
CallIntentService - creates call related requests and executes it by using HTTPRequest cass
and proccess request using CallProcessor. Notifies caller by intent with data.
UserProcessor - parsing response
CallProcessor - parsing response
ServiceHelper - finds and starts right intent service
When using from activity, I use something like this: SeviceHelper.StartService (action, data),
and I get response by local BroadcastReceiver inside of the activity. I register receiver on the OnStart(), and unregister it on the onStop() method of the activity.
Is that a good approach?
Should I have only one IntentService for all calls?
Is it better to have one Service that runs all the time in background, instead of using Intent Service that has to be started for each request?
Is there any other things that can get bad with this approach that I'm missing?
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.