Introduction to Activity in Android
Every time you start an Android Studio project the dialog box asks you to select a type of an activity that usually acts as a starting point of your app. For our “Hello World” app we selected an Empty Activity.
It also asked us for a name and by default it’s usually MainActivity although you can change this to anything you want. You can find the MainActivity.java file inside main and under java folder as shown below.
What is an Activity in Android?
The official Android docs define activity as “An activity is a single, focused thing that the user can do”. Put it simply, activities are where you write your Java code so that the visual layout that we create using xml editor can actually do something useful. Layout editor only creates the visuals or gui but activity java files are where all the magic happens.
Let’s go over the default activity code generated by Android Studio.
package com.andtuts.helloworld; 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); } }
A few things to note here.
- Activity class is an extension of Android’s AppCompactActivity class.
- AppCompactActivity is added via import: import android.support.v7.app.AppCompatActivity.
- By Default it implements an OnCreate method. More on that later
- setcontentview tells the app where to find the associated layout for activity.
As you can see Activity file actually puts together the window or screen of our app, we can then add the functionality inside activity file or even on separate java files. Your app can have as many activities as it needs. You can even have multiple activities within an activity using what’s called a fragment which we will discuss in another post.
It also needs to implement onCreate function which as the name suggests executes when the app gets initialized. There are many other methods including onPause, onResume and so on and it’s critical that you understand each one of them and how it works. Let’s take a look at Android’s activity lifecycle diagram.
Official Android doc on activity lifecycle is very detailed an explains the concepts very well and I’d recommend you read it thoroughly. Let’s go over some of the major ones.
onCreate is required for every activity and it is the first method that’s called every time your activity is run. Also stores a bundle with activity state if needed.
onStop is called when an activity is no longer visible to the user and is usually followed by onDestory but may also be followed by onRestart.
onDestroy final call before activity is destroyed.
Credits:
Activity lifecycle image: https://developer.android.com/reference/android/app/Activity.html