Android Base Activity

My First Activity Principal States Common Intents Download Activity Example

What is an Activity?

We can say that each of the screens of an application are an “activity”.



We can say that all the screens of an application are an “activity”.

As we comment earlier an activity represents the “controller” in a MVC pattern init the logic of your app and is linked to a view (layout) for response to UI (view) events.

The activities are made up of two parts: the logical and the graphic part.

The logical part is a .java file that is the class that is created to be able to manipulate, interact and place the code of that activity.

Later we will see that there are some variations, but for now let’s say they all are controllers of our screens.

That is, if an application has five screens, it has five “Activities”.


The official Google definition say

An activity is a single, focused thing that the user can do. Almost all activities interact with the user, so the Activity class takes care of creating a window for you in which you can place your UI with setContentView(View)


My First Activity

In order to get working our first activity we need to create a new Android project with Android Studio.

The base phases are simple:

1) In Android Studio, create a new project with the app name and package

  • Into Android Studio select File -> New Project in the dialog set the followint and click “next”:
    • Application Name: “My First Activity”
    • Company Domain: “”

2) In the Target Android Devices screen, keep the default values and click Next.The Minimum Required SDK is the earliest version of Android that your app supports, which is indicated by the API level. To support as many devices as possible, you should set this to the lowest version available that allows your app to provide its core feature set. If any feature of your app is possible only on newer versions of Android and it’s not critical to the core feature set, enable that feature only when running on the versions that support it (see Supporting Different Platform Versions).

3) In the Add an Activity to Mobile screen, select Empty Activity and click Next, then Customize the Activity screen, keep the default values and click Finish.

After some processing, Android Studio opens and displays a “Hello World” app with default files. You will add functionality to some of these files in the following lessons.

Now take a moment to review the most important files. First, be sure that the Project window is open (select View > Tool Windows > Project) and the Android view is selected from the drop-down list at the top. You can then see the following files:

app > java > com.example.myfirstapp >
This file appears in Android Studio after the New Project wizard finishes. It contains the class definition for the activity you created earlier. When you build and run the app, the Activity starts and loads the layout file that says “Hello World!”
app > res > layout > activity_main.xml
This XML file defines the layout of the activity. It contains a TextView element with the text “Hello world!”.
The content of the layout show a view <TextView> with “Hello World!”.
app > manifests > AndroidManifest.xml
The manifest file describes the fundamental characteristics of the app and defines each of its components. You’ll revisit this file as you follow these lessons and add more components to your app.
The manifest file define a main activity

Pay attention to intent  “android.intent.action.MAIN” action and “android.intent.category.LAUNCHER” Launcher is category of the intent.

An Intent is an object that provides run-time binding between separate components (such as two activities). The Intent represents the “intention to do something” of an app. You can use intents for various tasks, but in this lesson, your intent starts another activity. Intent concept is going to be further study in depth.

Main tells operating system that the activity is main activity of the application, Launcher tells the operating system that the activity should be visible in the launcher of the phone, and while you tap on any application then activity with main intent will get called.

So if we  remove Launcher intent, then the application will not be visible in the launcher on the phone and will acts like hidden application.

Gradle Scripts > build.gradle
Android Studio uses Gradle to compile and build your app. There is a build.gradle file for each module of your project, as well as a build.gradle file for the entire project. Usually, you’re only interested in the build.gradle file for the module. in this case the app or application module. For more information about this file, see Building Your Project with Gradle.
The code for our first activity look like this, pay attention to how the activity (remember the controller) is linked to layout (activity_main) by the instruction setContentView().


The Activity States & Lifecycle

Android kills activities which are running in the background when there is a need for memory. Killing one or all might depend on some conditions. For an instance paused or stopped can make android kill an activity or a process itself.

The clear summerize is:

If an activity has lost focus but is still visible (that is, a new non-full-sized or transparent activity has focus on top of your activity), it is paused. A paused activity is completely alive (it maintains all state and member information and remains attached to the window manager), but can be killed by the system in extreme low memory situations.

If an activity is completely obscured by another activity, it is stopped. It still retains all state and member information, however, it is no longer visible to the user so its window is hidden and it will often be killed by the system when memory is needed elsewhere.

If an activity is paused or stopped, the system can drop the activity from memory by either asking it to finish, or simply killing its process. When it is displayed again to the user, it must be completely restarted and restored to its previous state.


When your app performs intensive work in response to user interaction, this single thread model can yield poor performance unless you implement your application properly. Specifically, if everything is happening in the UI thread, performing long operations such as network access or database queries will block the whole UI. When the thread is blocked, no events can be dispatched, including drawing events. From the user’s perspective, the application appears to hang. Even worse, if the UI thread is blocked for more than a few seconds (about 5 seconds currently) the user is presented with the infamous “application not responding” (ANR) dialog. The user might then decide to quit your application and uninstall it if they are unhappy.

On Android Developer Site has said that : We shouldn’t use long operations work in UIThread. Instead, we should do it on another thread. At this site, they still say :

if the UI thread is blocked for more than a few seconds (about 5 seconds currently) the user is presented with the infamous “application not responding” (ANR) dialog.

To test this statement, I make a proof. Here is the blocking UI code:

There an example of killed activity after 8000 ms, the activity will finish using the following code. The max time for freezing the UI activity are 5 seconds.

Attention, no blocking the UI (User Interface).


Following the bad example of blocking the UI:


OK, this is for advance level, but the right way would be post delay without blocking the UI Thread to finish the activity after 100 ms.


Activity state

One activity during its life could pass over the next states:

State Description


Activity is visible and interacts with the user.


Activity is still visible but partially obscured, instance is running but might be killed by the system.


Activity is not visible, instance is running but might be killed by the system.


Activity has been terminated by the system of by a call to its finish() method.


Principal States

The Activity lifecycle is based on the next principals callbacks: onCreate(), onStart(),onResume(), onPause(), onStop(), and onDestroy(). The system invokes each of these methods as an activity enters a new state.




State changes occur when the activity is first created (onCreate), when is going to be displayed (onStart – onResume). At the moment when the activity is no longer visible or partially visible, it will happen to background activity pauses (onPause) and then stops (onStop). The differences between onPause and onStop ares basically onStop is called when the activity is no longer visible to the user, think that an activity could be still visible when is under other Activity that has transparencies.

In a summary we will generally use oncreate to associate the activity to the layaout and get the views of it as an EditText. onResume to reserve certain resources that we release on onPause such as the use of the camera. Another case of important use in OnResume would be when we return from an activity and we want to refresh some screen content. When you press back on the current activity and go back in the previous one we will go through onResume always and it will be nice to carry out our screen refresh, for example from a database.


Transparency Capability Example

And Can I build transparent activity?, Yes you can.


In both besides onPause or onStop can realize task of releasing memory of the objects that we need during this activity  is used to release objects differentiating the ones we do not need if the activity is partially seen (onPause) or completely (onStop).

The system either invokes this onDestoy because the activity is finishing due to someone’s calling finish(), or because the system is temporarily destroying the process containing the activity to save space. We can distinguish when is due to the invocation of the finish() using the isFinishing() method.

Activity Lifecycle Example 

In this example we are working with two activities, InitActivityOne and InitActivityTwo. In the first activity we have a button to navigate to InitActivityTwo. The button execute a method into the one activity which use an Intent object (Intent allows us to interact with other activities of our application and the system itself, we will see later) for start the second activity. All the lifecycle states is trace by LogCat (is the default system for tracing in Android).

Complete examples are available in the download area

The code of the InitActivityOne


The code of the InitActivityTwo

Video Execution Example

Intents and intents filters

An Intent is an mechanism that you can use to request an action from another component of the application. Although intents facilitate communication between components in many ways, there are three key use cases:

To start an activity, start a service and send a system message, let´s see:

Start  an activity let to navigate between activities. You can start a new instance of an Activity by passing an Intent to startActivity (). Also we can pass parameters to the destiny activity. The following example shows a destiny activiy with extra parameter called EXTRA_MESSAGE.  If you want to receive a result of the activity when it finishes, call startActivityForResult (). The activity receives the result as a separate Intent object in the onActivityResult () callback of the activity

To start a service that performs operations in the background without a user interface. You can start a service to perform a single operation (such as downloading a file) by passing an Intent to startService ().

To deliver a message is a warning that any application can receive. The system delivers multiple system event messages, such as when the system boots or the device begins to load. You can send a message to other apps by passing an Intent to sendBroadcast (), sendOrderedBroadcast () or sendStickyBroadcast ().

Common Intents

Google app Intents


Intent Explicit And Implicit Example

In this demo we will see how to use intents to invoke system activities (implicit attempts) or own our app (explicit intent). Let’s see:


The implicit ones, remember that the component is not specifically named; But instead a general action is declared to perform and a URI with referents protocol let know Android what app can be used to open it.

The following are the implicit Intents:

Implicit Intents

Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI


intent.putExtra(SearchManager.QUERY, “Mobile”);



Intent intent = new Intent(Intent.ACTION_VIEW);

The explicit invokes an activity of our app called InitActivityTwo and adds as a parameter a message “a name” that is displayed when the second activity is displayed.

Pay attention to how the parameter is set and how it is collected in the second activity, creating in this case the TextView element in run-time instead from a xml layout.

Below the layout of the first activity in which they show the different buttons to run each of the intents, the first is the one that allows to go to the InitactivityTwo.

The InitActiviyOne have the intents and are linked to the layout by android:onClick=”invokeWebSearch” directly invoke public invokeWebSearch(View view) method.

Pay attention how is the call and the response over each intent resolve, we have two intents invoked by startActivityForResult this is used to indicate to android that we are laughing an intent with a possible response the two intents with resonse are the following:

We need indicate a code for each request in order to then be able to differentiate the different responses received. The response are received un the same callback protected void onActivityResult(int requestCode, int resultCode, Intent data). 

Following the method linked with buttons for start the different intents. Observe how the code REQUEST are applied on each invoke.


As we can see is necessary firstly check that the result is OK and then for each resultCode filter and choice the action required. In this case are showing the data from a message received from the InitActivityTwo and also the contact name and phone number received from the contacts app thanks to the implicit intent. Great!!

Following all code for the InitActivityOne, all together. Let’s go for it !!

Activity recive the intent param extra message and is showed on a text view.

The textview is created programmatically in run-time and fill with extra data from the origin intent Intent intent = getIntent(); String message = intent.getStringExtra(InitActivityOne.EXTRA_MESSAGE);  is used.



In a summary we will generally use onCreate to associate the activity to the layout and get the views of it as an EditText. Usually the EditText or similar objects are defined like a properties/attribute of the activity, that way yo can use across all activity.

onResume to reserve certain resources that we release on onPause when we want to refresh some screen content in a back from a second activity (for example from a database).

Very important, Attention, no blocking the UI (User Interface), all operations should be asynchronous, because in other case Android ANR (Application Not Responding) will appear and close te app.

Intent implicit Vs Intent explicit, implicit are the system intents like make a call or pick contact, explicit are by name action used e.g. to navigate into our app activities.

Pass data to intent and receive result, is easy using extra data from out intent and implementation the onActivityResult and in the second invoke  intent.getStringExtra(InitActivityOne.EXTRA_MESSAGE); (see the example code attachment).

Good job, let’s move on to the next chapter on user interfaces, you get along very well.

Download Example Activity IntentParameters


All Downloads

git clone


Info Links

Portions of this page are reproduced from work created and shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License.


Social media & sharing icons powered by UltimatelySocial