Intents on Android

October 13, 2019

Interprocess communication or IPC is a functionality given by a system to allow the processes to share data with each other.

You can use named pipes or domain sockets on Unix, postMessage on the web and intents on Android. There are other mechanisms on Android for a service, but today we will focus on intents.

This system is used to communicate with other apps. Here’s a simple example, which opens the phone dialer, to start with:

// We create an Intent with ACTION_DIAL as the operation to be performed
// As an argument, we give it a URI containing a phone number starting with tel:
val intent = Intent(Intent.ACTION_DIAL, Uri.parse("tel:12345"))
// Finally we launch this intent with startActivity
startActivity(intent)

As the snippet shows it, intents are a structured format of data, shared to another activity when the system starts it. There are different type of actions as:

You can find the complete standard activity actions list here. This system is also used to start activities within your app. Imagine your app has two activities: MainActivity and SendMessageActivity.

You can write a message in the first one and the second one lets you choose which contact to send it:

// MainActivity.kt
// Intent has a second constructor with a context as 1st parameter and a class as 2nd
val intent = Intent(this, SendMessageActivity::class.java)
// We can add extra information to our intent
// Think of it as URL query string
intent.putExtra("message", "Hello Yacine")

startActivity(intent)

Finally we need to write the code to receive the intent content on the SendMessageActivity:

// SendMessageActivity.kt
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_send_message)

    // We extract the "message" parameter from the Intent
    val message = intent.getStringExtra("message")

    // We set the message string to the TextView in our layout
    val textView = findViewById<TextView>(R.id.text_view)
    textView.text = message
}

There are other ways to do IPC on Android as BroadcastReceiver and, Binder or Messenger to communicate with a Service.


Any thoughts or comments? Ping me on Twitter @yrezgui