Intro to Android

Message Passing

Intents

Intents allow message passing and late run time binding between components. Basically you broadcast a desire, such as opening a web browser or a specific Activity you created. Android handles the rest.

Intents

A good example is when sharing a picture you snapped with a social network. You have options, such as Twitter, Instagram, etc. depending on what you have installed. If you are writing a camera application, you don't have to care about how someone plans to share the picture, just that they are able to do it in the manner they wish.

Intents

Using intents frees you to focus on creating the content that is important to your application, not implementing or forcing people to use a particular method. It makes your app a participant in the system instead of a self-contained app that must handle everything by itself. You're part of the community!

You have several options with when invoking an intent:

  • Start one of your application's own components (e.g. by using startActivity() with an internal class). This keeps the intent within the current process' boundaries.
  • Send an intent for an activity from another application that crosses process boundaries.
  • Broadcast a system-wide intent, such as opening a web browser or sharing a piece of content. This also crosses process boundaries. The system presents the user with an option of how to react to the request.

Code Example

In this example, we are getting a reference to a button and setting a click listener that starts an internal activity.

findViewById( R.id.activity_button ).setOnClickListener(
    new View.OnClickListener()
    {
        @Override
        public void onClick( View v )
        {
            startActivity( ViewSystemActivity.createIntent( LooselyCoupledActivity.this ) );
        }
    };
)

Event Bus

Event buses are a great way to decouple our components without using a interface or listener pattern that can produce a lot of boilerplate code. You can use an application-wide bus, such as Otto, to pass messages.