Intent is an object to pass messages, which can be used to send requests to other components (activity, service, broadcast receiver, etc.) for execution. But for activities, its main usage is to start another activity.
Explicit Intent Navigation
With explicit intent, we directly tell the class name to start, which is widely adopted within applications.
Suppose we jump from MainActivity to SecondActivity
Implicit is often used to interact with other apps on the phone, instead of other components within the same app. Upon calling, Android will skim through all apps and let users choose.
Implicit intent
1 2 3 4 5 6 7 8 9
// opens a website IntentwebIntent=newIntent(Intent.ACTION_VIEW); webIntent.setData(Uri.parse("https://www.android.com")); startActivity(webIntent);
// starts a phone call IntentdialIntent=newIntent(Intent.ACTION_DIAL); dialIntent.setData(Uri.parse("tel:10086")); startActivity(dialIntent);
Data Transmission
Passing Data with Bundle
Bundle is a key-value pair container that is specific for carrying data in Intent.
@Override protectedvoidonCreate(Bundle savedInstanceState) { // ...... // suppose we have a textview TextViewinfo= findViewById(R.id.infoTextView); // 1. get the intent that starts this activity Intentintent= getIntent(); // 2. get Bundle from intent Bundlebundle= intent.getExtras(); if (bundle != null) { // 3. get key-value pairs // provides default to avoid null Stringname= bundle.getString("USER_NAME", "Guest"); intage= bundle.getInt("USER_AGE", 0); booleanisVip= bundle.getBoolean("IS_VIP", false); } /* Or alternatively, we can directly get from Intent. String name = intent.getStringExtra("USER_NAME"); int age = intent.getIntExtra("USER_AGE"); */ }
Pass Custom Class Objects
We mainly have 2 ways.
We implement java.io.Serializable interface for our class.
We implement Parcelable interface which is specific for Android. We have to implement writeToParcel logic (packing) and CREATOR logic (unpacking), but it’s more efficient.