Activities & Intents — Android Tutorials pt. 3

ByRafael Toledo in

Hi everyone! This is the third part of Android series, today we will create our first Activity, understand how it works, and get some general concepts about Intents!

On the previous post, we created a famous Hello World project like. Starting today, we will create a new project, that will be evolved step by step alongside the entire series. So, create a new project following the previous tutorial but, instead of selecting Empty Activity, this time select the Add No Activity option. This way, we can get better control, create only what we need, and get a better understanding of what’s happening. No magic, and no secrets for now! 🙂

Some initial configuration will be done by Android Studio, and a fresh project will be created. Don’t worry, we will understand every point of the generated project at the right moment. When Android Studio stops loading, you will see two items on project tree on the left side, app and Gradle Scripts. This is because we are using the Android view, that groups a lot of resources and files in a better way for Android development. Alright, some “sugar” and magic is good sometimes, but, when learning the basics, and understanding what is really happening, it’s better to see the raw thing, so the magic turns not into magic, but only tricky. It’s better for our understanding and to build knowledge.

So, let’s change from Android view to Project view, that will show the real folder structure of our project.

So, let’s jump to java folder, inside app/src/main/java. The project has this structure because of Gradle. Gradle is a very popular tool that helps the management of the project build, including dependencies, compilation and general tooling. In a better moment, we will learn more about Gradle.

In the java folder, at this moment, you can see only the application package declaration. So, let’s create our first Activity. Right-click the package (in my case, net.rafaeltoledo.tutorial), and select the New -> Java Class option. Give the new class a name, like MainActivity.

On Android, Activities are the representation of a screen. They are responsible to show the windows’ content, the user interface interactions, and some more things. It’s the core Android component that holds the UI interaction.

Right now, our MainActivity is just a common Java class. To make it a real activity, we need to extend the Activity class. But, in our case, we will extend AppCompatActivity instead. Why?

AppCompatActivity is a specialization of Activity that makes their behavior the same when running in different Android versions, plus backporting some new behavior introduced in newer Android versions to APIs back to 7 (Android 2.1). AppCompatActivity is part of the support libraries, that will be part of this tutorials soon.

Alright, we got an Activity, but how do we make it available on our phone launcher? To allow this, we need to setup our Android Manifest. The Android Manifest is a XML file that acts like a summary of our app. It describes, among other info, which activities our app have, which permissions it needs to run, and a lot of more info.

With our project, as we didn’t selected the Activity creation on project wizard, we have only a basic AndroidManifest.xml, located inside app/src/main folder. This initial version can be a bit different, depending of your Android Studio version:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="net.rafaeltoledo.tutorial">
 
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
 
    </application>
 
</manifest>

Here, we have 2 important points:

  • The main node manifest with the package attribute. This attribute is important, as it indicates which Java package will hold the class. This class, generated automatically on each build, it’s an index of all app resources. We will learn more about resources very soon.
  • The application node, that configures and describes our app. Some of the information present here is the app icon, the app label (that is shown on together with app icon) and the app theme.

To add our activity, let’s add a new node inside of application, like this:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="net.rafaeltoledo.tutorial">
 
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
 
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
 
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
 
    </application>
 
</manifest>

With this node, we added an activity, referencing its name .MainActivity. This ‘path’ can be absolute, like net.rafaeltoledo.tutorial.MainActivity or, in this case, relative to the package attribute of the manifest node. We also added a configuration to the activity, with the intent-filter tag.

The Android OS have a messaging system known as Intents. An intent is an intentions of doing some thing, like send a message to a component, or even send a message to an already created component. The intent can hold a lot of information, like the recipient, and action, an category, and more extras.

Remember the core Java, or even any other language, when we started our apps using a main() method or function? The idea here is very similar: when the app icon is being touched on lancher, the system triggers an Intent to the configured Activity, with the category android.intent.category.LANCHER (an Android constant) and the action android.intent.action.MAIN (another Android constant), telling our app that it should start its main activity. Some apps even have more than one main activity (but it’s not so usual).

To see this happening in the practice, let’s hold this intent triggered by the lancher and check some data. So, let’s override the onCreate() method of our MainActivity. As we extended AppCompatActivity, we inherited a lot of methods that allows us to do a lot of cool things. The onCreate() method is one of the lifecycle callbacks of an activity. As you can note, we didn’t called the activity constructor directly. Instead of this, the OS itself launches the activity. So, we are only notified about what’s happening with our activity. You can check the entire activity lifecycle here, but don’t worry. Everything will make a lot more sense very soon.

So, inside the onCreate() method, let’s get some data from the Intent that triggered our Activity. With this data, let’s write some info on Android log (also known as LogCat), like the action, the categories and the component. The code looks like this:

public class MainActivity extends AppCompatActivity {
 
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent intent = getIntent();
        Log.d("MA::Action", intent.getAction());
        for (String category : intent.getCategories()) {
            Log.d("MA::Category", category);
        }
        Log.d("MA::Component", intent.getComponent().getClassName());
    }
}

Note that, to show data on LogCat, instead of the default System.out from Java, we used the Log class. It allow us to better logging info on Android, controlling the log level (error, warning, debug, and others) and we can add a tag (the first parameter) for better searching the log (that sometimes is a bit noisy).

Now, if you run your app, and clicks the Android Monitor tab (in the bottom of Android Studio), you can see our fresh log messages, showing what’s arrived with the intent.

So, that’s all for today! In the next post, we will begin to understand the Android resources, and create our first layout for MainActivity!

If you want to check the complete project until now, you can check the code on Github!

Stay tuned! 🙂

Leave a comment! 0

Your e-mail will not be visible. Mandatory fields are shown with *

Commenting as Anonymous

read more