Sobes.tech
Junior

What are Intents used for in Android?

sobes.tech AI

Answer from AI

Intents in Android are used for:

  • Starting an Activity: Transition between screens or launching external applications.

    // Starting an Activity
    val intent = Intent(this, AnotherActivity::class.java)
    startActivity(intent)
    
  • Starting a Service: Performing background operations.

    // Starting a background service
    val intent = Intent(this, MyService::class.java)
    startService(intent)
    
  • Sending broadcast messages: Notifying other system components about events.

    // Sending a broadcast message
    val intent = Intent("com.example.MY_CUSTOM_ACTION")
    sendBroadcast(intent)
    
  • Passing data between components: Extras can be added to Intents.

    // Passing data between Activities
    val intent = Intent(this, DisplayMessageActivity::class.java).apply {
        putExtra("EXTRA_MESSAGE", "Hello from previous Activity!")
    }
    startActivity(intent)
    
  • Implicit actions (Implicit Intents): Performing actions without specifying a particular component, allowing the system to choose an appropriate app.

    // Opening a web page
    val webpage: Uri = Uri.parse("http://www.android.com")
    val intent = Intent(Intent.ACTION_VIEW, webpage)
    startActivity(intent)
    

They serve as a kind of message describing the intention to perform some action.