Main Activity class
Having looked at activity_main.xml layout file we are now ready to proceed to MainAcitity.java activity class. Just to recap, layout xml file takes care of our user interface while it is the java class files that contain the code for the logic of the app.

With our project open in Android Studio click the activity tab, the following code is already auto generated for you by AS so that you don’t have to type it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package com.androidshowtime.myfirstapp;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);
}
}

Line 1 provides the name of our app’s package. Lines 3 and 4 show our imports; we need imports to enable us to use methods of other classes.

At line 6, the keyword public tells us that our java class i.e. MainActivity is visible and its public methods are accessible by other classes in our package. At the moment our package contains the MainActivity class only.

The keyword extends means the MainActivity class is the subclass and it will inherit its methods from a superclass called AppCompatActivity class.

The keyword override on line 8 allows us to declare and use an already defined method in Android, in this case the Activity’s onCreate() method.

Line 9  overrides the oncreate() method which takes a bundle object as an argument. The bundle argument is passed to the onCreate() to help recreate a previously saved activity state. If no data was saved, savedInstanceState value is null.

On Line 10, the keyword super in java allows you to call a super class’s method implementations. This is used when a method is overridden in the current class but the intention is to call the method in the super class.

On line 12 we call setContentView() inside the onCreate() method to set the design of our activity. This design is written on the activity_main.xml located in the layout folder. The layout folder is found inside Resource Folder which is represent ed by R, therefore the full path for the xml layout file is R.layout.activity_main.xml .

Activity Class and AppCompatActivity
Activity is the presentation layer in an Android app, e.g. a screen which the user sees. In other words, activity is the Java class code that creates a screen window.

Activity class is a pre-defined class in Android and every app which has a User Interface must inherit from it to create a window.

The Activity class serves as the entry point for an app’s interaction with the user, providing the window in which the app draws its UI.

Activity class is a crucial component of an Android app; unlike in other programming languages where apps are launched with a main() method, the Android system initiates its program within the activity by calling specified methods which correspond to certain stages of the activity lifecycle.

An Android app can have several activities that can be switched between them during runtime of the app; one activity in an app specified as MainActivity is the first screen to be displayed when the user launches the app. Inside the MainActivity you can start other activities to perform different actions.

The activities launched on the Android system are managed as an Activity Stack. When a new activity is started, it is placed on the top of the stack and becomes the running activity – the previous activity always remains below it in the stack, and will not come to the foreground again until the new activity exits.

To use activities in your app, you must register information about them in the app’s manifest, but thanks to Android Studio our Main Activity is already declared in our manifest.xml file.

1
2
3
?xml version="1.0" encoding="utf-8"?>

<!—the main activity is registered between the activity tags -->

Activity class is the base class of all the other activities; some of the activities include FragmentActivity, ListActivity and AppCompatActivity to name just a few.

Based on Activity, FragmentActivity provides the ability to use a Fragment. A fragment is the part of an activity and is also known as sub-activity. There can be more than one fragment in an activity. Fragments represent multiple screens inside one activity.

ListActivity is an activity that displays a list of items by binding to a data source such as an array.

Our above MainActivity extends AppCompatActivity as it is no longer recommended to use Activity class in its pure form because its subclasses are far much better. For instance, extending AppCompatActivity provides backward compatibility on other lower end Android devices so that they can use newer added to Android versions.

AppCompatActivity is from the appcompat-v7 library (please see the v7 Support Library import on line 3 above) and is the base class for activities that use the support library ActionBar features. ActionBar is a display bar at the top of each screen.

Android Support Libraries
To provide this backward compatibility Android provides you with Support Library package. The Android Support Library package is a set of code libraries that provide backward-compatible versions of Android framework APIs as well as features that are only available through the library APIs. Each Support Library is backward-compatible to support a specific range of Android platform versions and set of features.

Use of Android Support Library in your app code is encouraged and preferred. By using these libraries you can increase your target market and target audience.

v4 Support Library  is a support library designed to be used with Android 1.6 (API level 4) and higher. v7 Support Library  is designed to be used with Android 2.1 (API level 7) and higher.Here are a few of the key classes included in the v7 appcompat library:

  • ActionBar – Provides an implementation of the action bar user interface pattern.
  • AppCompatActivity – Adds an application activity class that can be used as a base class for activities that use the Support Library action bar implementation.

v8 Support Library is designed to be used with Android (API level 8) and higher.
v13 Support Library is designed to be used for Android 3.2 (API level 13) and higher.

Activity LifeCycle
Android activities go through a certain life cycle during their lifetime. The activity class provides a number of callbacks that allow the activity to know that a state has changed: that the system is creating, stopping, or resuming an activity, or destroying the process in which the activity resides.

The below figure summarizes the lifecycle methods

Android activity life cycle

onCreate()  Called when the activity is first created. This is where you should do all of your normal static set up: create views, bind data to lists, etc.  You must implement this callback, most importantly you must call setContentView() to define the layout for the activity’s user interface.

This method also provides you with a Bundle containing the activity’s a previously frozen state if there was one.  If you save the state of the application in a bundle it can be passed back to onCreate() if the activity needs to be recreated e.g. orientation change when rotating your device from landscape mode to portrait and vice versa.

oncreate() is always followed by onStart().

onRestart() – The system invokes this callback when an activity in the stopped state is about to restart. onRestart() restores the state of the activity from the time that it was stopped. This callback is always followed by onStart().

onStart() – Called when the activity is becoming visible to the user. Followed by onResume() if the activity comes to the foreground, or onStop() if it becomes hidden.

onResume() – Called when the activity start interacting with the user. At this point your activity is at the top of the activity stack, with user input going to it. Always followed by onPause(). It is used to initialize components released during onPause() e.g. restart animations. onResume() is always followed by onPause()

onPause() – Called when an activity is going into the background but has not (yet) been killed. This state occurs when, for example, the user taps the Back or home button.

onPause() is used to commit unsaved changes, stop animations and other things that consume CPU/Battery e.g. Broadcast receivers. You should not do anything lengthy here.

Once onPause() finishes executing, the next callback is either onStop() or onResume(), depending on what happens after the activity enters the Paused state.

onStop() –  The system calls onStop() when the activity is no longer visible to the user. The next callback that the system calls is either onRestart(), if the activity is coming back to interact with the user, or by onDestroy() if this activity is completely terminating.

Note that this method may never be called, in low memory situations where the system does not have enough memory to keep your activity’s process running after its onPause() method is called.

onDestroy() – The system invokes this callback before an activity is destroyed.This callback is the final one that the activity receives.  It is called to allow your activity to do any shut-down operations it may wish to do e.g. to ensure that all of an activity’s resources are released.

The below table gives few examples of situations and callbacks invoked

Situation Callbacks
When open the app onCreate() –> onStart() –>  onResume()
When home button pressed onPaused() –> onStop()
When any dialog open on screen onPause()
After dismiss the dialog onResume()
When phone screen off onPaused() –> onStop()
When screen is turned back on onRestart() –> onStart() –> onResume()
When back button pressed to exit the app onPaused() — > onStop() –> onDestory()
Open a recent app from Activity Stack onRestart() –> onStart() –> onResume()
Incoming Call onPause()
After call end onResume()

Watch the below video to  reinforce what is contained on this post.

Hope this was helpful, keep the comments coming!

Leave a Reply