So, we have completed the development of our first app and it’s time to move on! This time, we will ponder upon the question, “How to communicate between activities?”, i.e., Is it possible to switch from one activity to another in an app and if so, how? This post will try to answer most of these questions?
Let’s start from the very basic question! Why do we need to switch between activities? In an app, we need to have multiple activities which perform various tasks. As an example, a Message application has at least an Activity for showing the entire list of threads and an activity for creating new messages. Hence, we need to switch between these activities over and over again in order to make a user-friendly Message application. Similar situation arises in most of the apps since most of them consist of more than one activity.
So, we can see that we need to switch between activities, and most of the apps consist of various activities which can switch between one another. Now, we need to see how it is possible. Clearly, the title of the post suggest that there is something called Intents in an Android App which can help us in this regard.
Intent is the part of the Android framework which facilitates communication between activities. An intent can be treated as a function which can be called in an Activity with the parameters which (in broad sense) give the location of the activity to which we need to switch over.
One can use intents to not only switch between activities, but also to share some data from one activity to another. We will talk about it in detail later.
Once an intent is called, the control switches over to the other activity. The other activity after completing its job can simply call a function finish() in order to finish the activity and pass the control to the earlier activity.
When the control is sent back to the earlier activity, a specific function (called a callback function) is executed which can be used to process the data sent by the other activity (if any!).
So, we have discussed the complete flow of control with the use of Intents! In the next post, we will start the development of the second app based on intents where we will look at the exact code.
Till then, BYE!