Activity in Android
In this tutorial we will leanr about one of the most important concept related to Android development, which is Activity.
What is an Activity in Android?
Human mind or concious is responsible for what we feel, what we think, makes us feel pain when we are hurt(physically or emotionally), which often leads to a few tears, laughing on seeing or hearing something funny and a lot more. What happens to us in the real world physically(getting hurt, seeing, hearing etc) are intrepeted by our mind(concious or soul) and we think or operate as per.
So in a way, we can say that our body is just a physical object while what controls us through every situation is our mind(soul or concious).
In case of Android → Views, Layouts and ViewGroups are used to design the user interface, which is the physical appearence of our App. But what is the mind or soul or concious of our App? Yes, it is the Activity.
Activity is nothing but a java class in Android which has some pre-defined functions which are triggered at different App states, which we can override to perform anything we want.
Activity class provides us with empty functions allowing us to be the controller of everything.
For example, if we have a function specified by our mind → onSeeingSomethingFunny() , although we know what happens inside this, but what if we can override and provide our own definition to this function.
One thing that is different here in context to our example is, that a human is created once at birth, and is destroyed once at death, and for the time in between is controlled by the mind/soul/concious. But an Activity is responsible to create and destroy an App infinite number of times. So apart from controlling the app, Activity also controls creation, destruction and other states of the App’s lifecycle.
There can be multiple Activities in Android, but there can be only one Main Activity. For example, In Java programming (or programming languages like C or C++), the execution of the program always begin with main() method. Similarly, when the user presses the App icon, the Main Activity is called and the execution starts from the onCreate() method of the Activity class.
Different States of App (or, the main App Activity)
Starting from a user clicking on the App icon to launch the app, to the user exiting from the App, there are certain defined states that the App is in, let’s see what they are.
- When a user clicks on the App icon, the Main Activity gets started and it creates the App’s User Interface using the layout XMLs. And the App or Activity starts running and it is said to be in ACTIVE state.
- When any dialog box appears on the screen, like when you press exit on some apps, it shows a box confirming whether you want to exit or not. At that point of time, we are not able to interact with the App’s UI until we deal with that dialog box/popup. In such a situation, the Activity is said to be in PAUSED state.
- When we press the Home button while using the app, our app doesn’t closes. It just get minimized. This state of the App is said to be STOPPED state.
- When we finally destroy the App i.e when we completely close it, then it is said to be in DESTROYED state.
Hence, all in all there are four states of an Activity(App) in Android namely, Active , Paused , Stopped and Destroyed .
From the user’s perspective, The activity is either visible, partially visible or invisible at a given point of time. So what happens when an Activity has one of the following visibility? We will learn about that, first let’s learn about these states in detail.
Active State
- When an Activity is in active state, it means it is active and running.
- It is visible to the user and the user is able to interact with it.
- Android Runtime treats the Activity in this state with the highest priority and never tries to kill it.
Paused State
- An activity being in this state means that the user can still see the Activity in the background such as behind a transparent window or a dialog box i.e it is partially visible.
- The user cannot interact with the Activity until he/she is done with the current view.
- Android Runtime usually does not kill an Activity in this state but may do so in an extreme case of resource crunch.
Stopped State
- When a new Activity is started on top of the current one or when a user hits the Home key, the activity is brought to Stopped state.
- The activity in this state is invisible, but it is not destroyed.
- Android Runtime may kill such an Activity in case of resource crunch.
Destroyed State
- When a user hits a Back key or Android Runtime decides to reclaim the memory allocated to an Activity i.e in the paused or stopped state, It goes into the Destroyed state.
- The Activity is out of the memory and it is invisible to the user.
Note: An Activity does not have the control over managing its own state. It just goes through state transitions either due to user interaction or due to system-generated events.
Activity Lifecycle methods
Whenever we open Google Maps app, it fetches our location through GPS. And if the GPS tracker is off, then Android will ask for your permission to switch it ON. So how the GPS tracker or Android is able to decide whether an app needs GPS tracker for functioning or not?
Yes, obviously, the App when started asks for the GPS location which is only possible if the GPS tracker in switched ON.
And how does the App knows this, because we coded it that whenever a user starts it, it has to ask the user to switch ON the GPS tracker, as it is required.
Similarly, we can also tell the app to perform a few things before exiting or getting destroyed.
This is the role of Activity Lifecycle. There are six key lifecycle methods through which every Activity goes depending upon its state. They are:
Method | What does it do? | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
onCreate() |
Value | Description | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
» density « | The display density has changed — the user might have specified a different display scale, or a different display might now be active. Added in API level 24. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
» fontScale « | The font scaling factor has changed — the user has selected a new global font size. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
» keyboard « | The keyboard type has changed — for example, the user has plugged in an external keyboard. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
» keyboardHidden « | The keyboard accessibility has changed — for example, the user has revealed the hardware keyboard. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
» layoutDirection « | The layout direction has changed — for example, changing from left-to-right (LTR) to right-to-left (RTL). Added in API level 17. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
» locale « | The locale has changed — the user has selected a new language that text should be displayed in. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
» mcc « | The IMSI mobile country code (MCC) has changed — a SIM has been detected and updated the MCC. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
» mnc « | The IMSI mobile network code (MNC) has changed — a SIM has been detected and updated the MNC. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
» navigation « | The navigation type (trackball/dpad) has changed. (This should never normally happen.) | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
» orientation « | The screen orientation has changed — the user has rotated the device. Note: If your application targets Android 3.2 (API level 13) or higher, then you should also declare the «screenSize» and «screenLayout» configurations, because they might also change when a device switches between portrait and landscape orientations. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
» screenLayout « | The screen layout has changed — a different display might now be active. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
» screenSize « | The current available screen size has changed. This represents a change in the currently available size, relative to the current aspect ratio, so will change when the user switches between landscape and portrait. Added in API level 13. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
» smallestScreenSize « | The physical screen size has changed. This represents a change in size regardless of orientation, so will only change when the actual physical screen size has changed such as switching to an external display. A change to this configuration corresponds to a change in the smallestWidth configuration. Added in API level 13. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
» touchscreen « | The touchscreen has changed. (This should never normally happen.) | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
» uiMode « | The user interface mode has changed — the user has placed the device into a desk or car dock, or the night mode has changed. For more information about the different UI modes, see UiModeManager . Added in API level 8. All of these configuration changes can impact the resource values seen by the application. Therefore, when onConfigurationChanged() is called, it will generally be necessary to again retrieve all resources (including view layouts, drawables, and so on) to correctly handle the change. Note: To handle all Multi-Window related configuration changes use both «screenLayout» and «smallestScreenSize» . Multi-Window is supported in Android 7.0 (API level 24) or higher. Whether or not the activity is direct-boot aware; that is, whether or not it can run before the user unlocks the device. Note: During Direct Boot, an activity in your application can only access the data that is stored in device protected storage. The default value is «false» . android:documentLaunchMode Specifies how a new instance of an activity should be added to a task each time it is launched. This attribute permits the user to have multiple documents from the same application appear in the overview screen. This attribute has four values which produce the following effects when the user opens a document with the application:
Note: For values other than » none » and » never » the activity must be defined with launchMode=»standard» . If this attribute is not specified, documentLaunchMode=»none» is used. android:enabled Whether or not the activity can be instantiated by the system — «true» if it can be, and » false » if not. The default value is » true «. android:excludeFromRecents Whether or not the task initiated by this activity should be excluded from the list of recently used applications, the overview screen. That is, when this activity is the root activity of a new task, this attribute determines whether the task should not appear in the list of recent apps. Set » true » if the task should be excluded from the list; set » false » if it should be included. The default value is » false «. android:exported This element sets whether the activity can be launched by components of other applications:
If an activity in your app includes intent filters, set this element to » true » to allow other apps to start it. For example, if the activity is the main activity of the app and includes the category » android.intent.category.LAUNCHER «. If this element is set to » false » and an app tries to start the activity, the system throws an ActivityNotFoundException . This attribute is not the only way to limit an activity’s exposure to other applications. Permissions can also be used to limit the external entities that can invoke the activity (see the permission attribute). android:finishOnTaskLaunch Whether or not an existing instance of the activity should be shut down (finished), except for the root activity, whenever the user again launches its task (chooses the task on the home screen) — » true » if it should be shut down, and » false » if not. The default value is » false «. If this attribute and allowTaskReparenting are both » true «, this attribute trumps the other. The affinity of the activity is ignored. The activity is not re-parented, but destroyed. This attribute is ignored if FLAG_ACTIVITY_RESET_TASK_IF_NEEDED isn’t set. android:hardwareAccelerated Whether or not hardware-accelerated rendering should be enabled for this Activity — » true » if it should be enabled, and » false » if not. The default value is » false «. Starting from Android 3.0, a hardware-accelerated OpenGL renderer is available to applications, to improve performance for many common 2D graphics operations. When the hardware-accelerated renderer is enabled, most operations in Canvas, Paint, Xfermode, ColorFilter, Shader, and Camera are accelerated. This results in smoother animations, smoother scrolling, and improved responsiveness overall, even for applications that do not explicitly make use the framework’s OpenGL libraries. Because of the increased resources required to enable hardware acceleration, your app will consume more RAM. Note that not all of the OpenGL 2D operations are accelerated. If you enable the hardware-accelerated renderer, test your application to ensure that it can make use of the renderer without errors. android:icon An icon representing the activity. The icon is displayed to users when a representation of the activity is required on-screen. For example, icons for activities that initiate tasks are displayed in the launcher window. The icon is often accompanied by a label (see the android:label attribute). This attribute must be set as a reference to a drawable resource containing the image definition. If it is not set, the icon specified for the application as a whole is used instead (see the element’s icon attribute). android:immersive Sets the immersive mode setting for the current activity. If the android:immersive attribute is set to true in the app’s manifest entry for this activity, the ActivityInfo.flags member always has its FLAG_IMMERSIVE bit set, even if the immersive mode is changed at runtime using the setImmersive() method. android:label A user-readable label for the activity. The label is displayed on-screen when the activity must be represented to the user. It’s often displayed along with the activity icon. If this attribute is not set, the label set for the application as a whole is used instead (see the element’s label attribute). The label should be set as a reference to a string resource, so that it can be localized like other strings in the user interface. However, as a convenience while you’re developing the application, it can also be set as a raw string. android:launchMode An instruction on how the activity should be launched. There are four modes that work in conjunction with activity flags ( FLAG_ACTIVITY_* constants) in Intent objects to determine what should happen when the activity is called upon to handle an intent. They are: » standard » The default mode is » standard «. As shown in the table below, the modes fall into two main groups, with » standard » and » singleTop » activities on one side, and » singleTask » and » singleInstance » activities on the other. An activity with the » standard » or » singleTop » launch mode can be instantiated multiple times. The instances can belong to any task and can be located anywhere in the activity stack. Typically, they’re launched into the task that called startActivity() (unless the Intent object contains a FLAG_ACTIVITY_NEW_TASK instruction, in which case a different task is chosen — see the taskAffinity attribute). In contrast, » singleTask » and » singleInstance » activities can only begin a task. They are always at the root of the activity stack. Moreover, the device can hold only one instance of the activity at a time — only one such task. The » standard » and » singleTop » modes differ from each other in just one respect: Every time there’s a new intent for a » standard » activity, a new instance of the class is created to respond to that intent. Each instance handles a single intent. Similarly, a new instance of a » singleTop » activity may also be created to handle a new intent. However, if the target task already has an existing instance of the activity at the top of its stack, that instance will receive the new intent (in an onNewIntent() call); a new instance is not created. In other circumstances — for example, if an existing instance of the » singleTop » activity is in the target task, but not at the top of the stack, or if it’s at the top of a stack, but not in the target task — a new instance would be created and pushed on the stack. Similarly, if you navigate up to an activity on the current stack, the behavior is determined by the parent activity’s launch mode. If the parent activity has launch mode singleTop (or the up intent contains FLAG_ACTIVITY_CLEAR_TOP ), the parent is brought to the top of the stack, and its state is preserved. The navigation intent is received by the parent activity’s onNewIntent() method. If the parent activity has launch mode standard (and the up intent does not contain FLAG_ACTIVITY_CLEAR_TOP ), the current activity and its parent are both popped off the stack, and a new instance of the parent activity is created to receive the navigation intent. The » singleTask » and » singleInstance » modes also differ from each other in only one respect: A » singleTask » activity allows other activities to be part of its task. It’s always at the root of its task, but other activities (necessarily » standard » and » singleTop » activities) can be launched into that task. A » singleInstance » activity, on the other hand, permits no other activities to be part of its task. It’s the only activity in the task. If it starts another activity, that activity is assigned to a different task — as if FLAG_ACTIVITY_NEW_TASK was in the intent.
As shown in the table above, standard is the default mode and is appropriate for most types of activities. SingleTop is also a common and useful launch mode for many types of activities. The other modes — singleTask and singleInstance — are not appropriate for most applications , since they result in an interaction model that is likely to be unfamiliar to users and is very different from most other applications. Regardless of the launch mode that you choose, make sure to test the usability of the activity during launch and when navigating back to it from other activities and tasks using the Back button. For more information on launch modes and their interaction with Intent flags, see the Tasks and Back Stack document. android:lockTaskMode Determines how the system presents this activity when the device is running in lock task mode. Android can run tasks in an immersive, kiosk-like fashion called lock task mode. When the system runs in lock task mode, device users typically can’t see notifications, access non-allowlisted apps, or return to the home screen (unless the Home app is allowlisted). Only apps that have been allowlisted by a device policy controller (DPC) can run when the system is in lock task mode. System and privileged apps, however, can run in lock task mode without being allowlisted. The value can be any one of the following R.attr.lockTaskMode string values:
|