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
Related
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.
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.
Folks,
This is a newbie question. I have read a few articles on intents but I am a bit confused on what the main idea behind an intent is when it comes to starting an activity. If I know that I have to create and show an activity, why can't I do something as simple as the following?
MyActivity a = new MyActivity();
a.show();
Thank you in advance for your help.
Regards,
Peter
A activity has a lifecycle and this is managed by the framework. I would say to get an extra hold of the life cycle, Android introduced a set of rules to launch a activity (startActivity). To add-on, Intent is not only to launch your activities. Intents can be used to launch other thirdparty or inbuild views/service/targets. This could be another reason why they introduced intent. Just my two cents.
Intents communicate between activities in an app and between apps.
Your example:
MyActivity a = new MyActivity();
a.show();
assumes that Android is just objects, so that instantiating an Activity and somehow showing it will make it appear. This isn't the case, though; the Android system does a lot more. The activities in your app are "floating", as it were, within the Android framework. Most of what makes an Activity tick is invisible to you. In particular, the Android-specific thread model and the way that the system communicates with Android components (like Activities) is invisible.
I won't go into most of this, but an added advantage of Intents for starting an Activity is that an Activity can add itself as a candidate for Intents that want to do a specific task. Suppose I have an app that edits images. I can easily make myself discoverable by filtering for Intents that have the action ACTION_EDIT for MIME types that I can handle. This is exactly how Android implements the list of apps that appear when you try do to something with a file.
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.
click here for more information.
in basic words Intent is your ears regards to Android device. Your activity can talk to Android through Intent and listen on "any change" on your phone.
It's like "grandmother" that sits outdoors next to entrance of big house and listens about all talks, gossips and notify you about.
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 writing an app, that has a somewhat modular system. It has a core app, and some apps, that consist of a single Service, that implements the desired interface. I followed the guide to create the IPC communication. But now I need to get all the services, installed on the system, that my core app can wotk with. How do I do this? I mean, is there any way to mark my Service apps with some kind of a tag, and then filter results, presented by the PackageManager#getInstalledPackages() based on that tag value? What's the common practice of doing so?
Create a custom Intent to which your activities will respond. You can then use PackageManager.queryIntentServices to get your list of matching services. You can get the package info, etc. from the information embedded in the ResolveInfos.
Ideally you'd actually use these intents for invoking the services, but you could always just use them as identification tags and fall back on the binding mechanism you were using before.