Android Intent is a messaging object used to switch between different android components. An Intent’s most common use is to launch a new activity from the current activity.
The startActivity()
method is used to call an Activity.
The primary element of an Android application is Android Intent. However, applications can also be built without it.
Some general functions of Intent are as follows:
To call an Intent, we either include an <intent-filter>
or use a flag. An Intent contains the following primary information:
ACTION_VIEW
, ACTION_EDIT
, or ACTION_MAIN
.There are two types of Intent. These are as follows:
Implicit Intent states the action to be performed. It is not responsible for calling specific in-app components.
For example, if the user wants to see a location on a map, we can use an Implicit Intent to switch to another app that displays a specific location on a map.
To create an Implicit Intent, create a MainActivity
from which we can call the Intent. We then add the Intent in setOnClickListener
. An example of Implicit Intent is given below:
import android.content.Intentimport android.os.Bundleimport android.widget.Buttonimport androidx.appcompat.app.AppCompatActivityclass MainActivity : AppCompatActivity() {override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)val button = findViewById<Button>(R.id.btn)button.setOnClickListener{intent = Intent(Intent.ACTION_VIEW)intent.setData(Uri.parse("https://www.educative.io/"))startActivity(intent)}}}
button
assigns the value ID used in XML file.intent
assigns an action.Explicit Intent is used to invoke a specific target component. It is used to switch from one activity to another in the same application. It is also used to pass data by invoking the external class.
For example, we can use an explicit intent to start a new activity when the user invokes an action or plays music in the background.
To create an explicit Intent, we create an activity that works as our MainActivity
. We create another activity named NextActivity
that the explicit intent will direct to. We then join both of these activities with a button. An example of Explicit Intent is shown below:
import android.content.Intentimport android.os.Bundleimport android.widget.Buttonimport androidx.appcompat.app.AppCompatActivityclass MainActivity : AppCompatActivity() {override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)val button = findViewById<Button>(R.id.btn)button.setOnClickListener{startActivity(Intent(this, NextActivity::class.java))}}}
MainPage
button
assigns the value ID used in XML file.