Introduction To Android App Components — Activities and Intents (Part — I)

Tushar Tambi
AndroidDevelopers
Published in
10 min readJun 30, 2020

First Of All, If you do not have any prior knowledge of Android Development then you can refer it here.

So now as you have basic knowledge of Android App Development. Let’s start with the basics of Android App Components.

As I always say, Android Apps can be written using Kotlin, Java and C++ languages. So, you can write them in any language that you want. This tutorial is based on Java.

So, let’s talk about what Android App Components really are.

Android App Components:

There is always a requirement for basics to start something with. So as with Android App Development.

We can see the Android App components as the basic building blocks for Android App Development.

There are 4 types of basic Components:

  1. Activities
  2. Services
  3. Content Provider
  4. Broadcast Receiver
Basic Android App Components
Android App Components

Using these basics, we can build any Android App from a basic calculator to a complex app.

In this article, we will be starting with getting Introduction of Activities and Intents in Detail.

Activities

Topics to Cover:

  1. Introduction to Activities
  2. Configuring the manifest
  3. Introduction to Lifecycle and Lifecycle Methods

Introduction to Activities:

Activity is one of the most crucial components of building an android app. In fact, we can say that this is the heart of the android app development. Different Activities are grouped together in a single android app and then we use them to run our app.

Android system initiates Activity by using call back methods.

For now, just remember that Call back methods are different methods that are used while different lifecycles of activities.

Example of Activity: showing a login prompt, reading an email.

Now let’s recall what was the last time that we saw Activity.

Remember when we create a new Android Project, we see a screen that says select an activity.

Whenever you start any new project you choose an activity as a template or say a base for your Android App.

An android app may contain more than one activity. When one app invokes other apps then it tries to contact with the activity of the other app.

Activity Actually provides a window where app draws its UI.

Typically, one activity in the app is called the main activity. This is the activity is the first screen that the user sees firstly when a user opens the app.

First, it is necessary to extend the activity class.

This class is defined in the Android libraries and it provides a common interface for interacting with a user. Including operations performed when moving between life cycle stages, as we’ll talk about shortly.

If you want to see inside of these libraries, then click on the library name with Ctrl pressed.

Configuring the manifest:

To use your activity in your app you must add it in the manifest file of the application. (you must declare them)

To declare your activity, open your manifest file and add an <activity> element as a child of the <application> element. For example:

Although there are many attributes that this tag can take but for now the only required attribute is the name attribute.

Intent filters: They are the most powerful feature of the android app development. By using them we can launch activity based on not only by explicit intent but also by implicit intent.

“Oh my god! now, what are these explicit and implicit intents.”

Don’t worry below is an example of them.

Like you must make a UPI payment using your app, but you want g pay, phone pay or other UPI apps to start when user wants to make payment.

If you want that our app will show every UPI app that our mobile has then we will use implicit intent where our app will show every UPI app that user can select. and the user can use any of these.

But suppose that we want that only g pay, or any specific app will run only then we use implicit intent.

How can you use the intent filter? There is a tag inside the activity tag that you can use. (There is one more way to use intent filters when using intents in android app. we will talk about intents later in this article).

Here “<category android: name=”android.intent.category.LAUNCHER” means this will be first activity after launching our app.

There are more intent filters that you can add. This is your work go and search for more intent filters that you can add in the manifest file.

Permission: Our apps need some permission for launching any activity. More generally a parent activity cannot launch its child activity if both the activities do not have the same permission.

some common permissions are:

  • INTERNET
  • Using storage
  • using media
  • Sharing, etc.

Here is an example for INTERNET PERMISSION:

Intents

An intent is a message that one component uses to interact with or request functionality from other components.

It is a very essential component for developing any android app.

Types of Intents:

Explicit and Implicit intents.

Remember we have talked about them in this article.

Here is a brief overview of them.

An Application can define the target component that must be used as to perform an operation (explicit intents) or it can give the task to the android system to find the required apps in the system so as to complete the given operation (implicit intents).

Creating explicit and implicit intents:

  • Explicit Intents defines the components that must be called by the Android System. They are basically used within your application.

An Example of Explicit Intent is:

Intent i = new Intent (this, SecondActivity.class);i.putExtra(“Value1”, “This is from First Activity”);
  • Implicit Intents specify the action that is to be performed by the Android System. When we provide some information regarding the operation Android System searches the components that are specific to perform the given tasks. Now let’s suppose you want to set a reminder for some event and you have only one app that can perform this task then Android System will open this app directly but if your device has more than one task to perform this action than Android Will show you a selection dialogue of these options to start.

Try this in Android Studio.

Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(“https://www.google.com/”);startActivity(i);// this intent is for opening a web page.

Exercise: Try this intent by yourself.

Intents are famous because of three major functions performed by them:

  1. Starting an Activity: Whenever you want to start a new Activity you pass the Intent to startActivity() method. This method is defined in the Context object which Activity extends.

# Start the activity connect to the

# specified class

// here Intent is taking two arguments // First is "this", context of the activity// Second is the name of the second Activity to which you want to //navigate
Intent i = new Intent (this, ActivityTwo.class);
startActivity(i);

Also, let’s suppose you want to receive some result from the activity when it finishes you can also use intents. In that case, you have to pass the intent to startActivityForResult() method.

2. Starting a Service: Now you must be thinking that now what is the Service now.

Service is a component that performs its operation in the background without any user intervention. To start Service via intent use the method startSerive(Intent) method call.

3. Delivering a Broadcast: A Broadcast is a message that any app can receive.

Starting a new Activity from the Current Activity:

You can start second activity using startActivity(Intent) function.

// First ActivityIntent i = new Intent (this, SecondActiviy.class);startActivity(i);

Now let’s look at one example:

Example: Register an activity for the share intent

The following example registers an activity for the ACTION_SEND intent. It declares itself only relevant for the text/plain mime type.

<activityandroid:name=”.ActivityTest”android:label=”@string/app_name” ><intent-filter><action android:name=”android.intent.action.SEND” /><category android:name=”android.intent.category.DEFAULT” /><data android:mimeType=”text/plain” /></intent-filter>

Introduction to Lifecycle and Lifecycle Methods:

In the lifetime of activity, it goes through several states known as a lifecycle.

Now you must be thinking that what the heck is this lifecycle?

So, let’s clear your doubt.

You run your app, when you navigate through, out of, and back to your app in the different stages of its lifecycle.

Now there must be something that will remind the activity that the current state of the activity has changed. This will tell that is the system is creating, destroying, resuming or stopping the activity.

These works are done by some methods, that are provided by Android, Known as call-back methods.

Why these call — back methods are so important? This is because, if you do not handle all above-mentioned situations while creating an app will cause crashing of the application or security issues.

Let’s take an example to understand the lifecycle method:

Suppose you made an android video game, whenever user switches between app then you must terminate the network and pause the video. And when the user returns to your game you will start the video and reconnect the network and allow the user to continue his / her game.

Remember we talked about call-back methods before. here are some common call-back methods that we can use”

  1. OnCreate(): This invokes when the system creates your activity. You must use setcontentview(your layout file) inside this method. After oncreate there is always on Onstart ()
  2. Onstart(): Activity enters to this method when it entered in a started state after oncreate method.
  3. OnResume(): The system invokes this call-back just before the activity starts interacting with the user.
  4. OnPause(): The system calls onPause() when the activity loses focus and enters a Paused state.
  5. Onstop(): The system calls onStop() when the activity is no longer visible to the user.
  6. OnRestart(): The system invokes this call-back 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.
  7. OnDestroy(): The system invokes this call-back before an activity is destroyed.

Here is a diagram that will help you understand more clearly about them:

if you want to read more about various life cycle methods you can check them here.

Example: Let’s create an app that will allow you to enter your userName and some text about you. Then this information will be passed to the next Activity using intent.

Let’s start it by creating a new project.

Open Android Studio and create a new project. Configure it and create your first activity.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<EditText
android:id="@+id/UserNameTextId"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="16dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintVertical_bias="0.0"
android:hint="UserName"
android:padding="8dp"/>

<EditText
android:id="@+id/SomeTextId"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="@id/UserNameTextId"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:layout_margin="16dp"
android:hint="Enter Some text"
android:padding="8dp"/>

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Go To Next Screen"
app:layout_constraintTop_toBottomOf="@+id/SomeTextId"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:layout_margin="16dp"/>

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.java

package com.example.activitiesexample;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

// Declaring the components
private EditText mUserName, mAboutMe;
private Button ClickMe;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Initialising the components
// findviewByid is used to find the component in the layout file so you can use them here
mUserName = findViewById(R.id.UserNameTextId);
mAboutMe = findViewById(R.id.SomeTextId);
ClickMe = findViewById(R.id.button);

final String UserName = mUserName.getText().toString().trim();
final String Text = mAboutMe.getText().toString().trim();

// making the click event for our button
ClickMe.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra("name", UserName);
intent.putExtra("about",Text);
startActivity(intent);
}
});


}
}

Now let’s create SecondActivity when you want to show your data.

activity_second.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SecondActivity">

<TextView
android:id="@+id/UserName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
android:layout_margin="32dp"
android:text="UserName"/>

<TextView
android:id="@+id/AboutText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="@+id/UserName"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:layout_margin="32dp"
android:text="About Me"/>

</androidx.constraintlayout.widget.ConstraintLayout>

SecondActivity.java

package com.example.activitiesexample;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class SecondActivity extends AppCompatActivity {
TextView UserNameText, AboutMeText;
// when you transfer the data from one activity to other you //always pass them in bundle, so in second activity you catch them //by using bundle
Bundle bundle = null;


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

bundle = getIntent().getExtras();
setContentView(R.layout.activity_second);



UserNameText = findViewById(R.id.UserName);
AboutMeText = findViewById(R.id.AboutText);


String name = bundle.getString("name");
String text = bundle.getString("about");


UserNameText.setText(name);
AboutMeText.setText(text);


}
}

Let’s run our application.

When we click on GO TO NEXT SCREEN button then we will see this screen.

In Future We will be discussing “How Data is transferred between different Activities”.

Important Links:

Download Java: https://www.java.com/en/download/

Java Tutorials: https://www.tutorialspoint.com/java/index.htm

Download Android studio: https://developer.android.com/studio

Learn more about Android Studio: https://developer.android.com/studio/intro

Official Android Developer Page: https://developer.android.com/index.html

Google Developers Codelabs provide a guided, tutorial, hands-on coding experience: https://codelabs.developers.google.com/?cat=Android

Links for Contact:

GitHub: https://github.com/8426988382

Email: Tushar Tambi

References:

If You have any doubts feel free to ask in comments.

“Any comments or suggestions are welcome”

--

--