Header Image - Randall Morgan

Category Archives

One Article

Android Native Development with Java Getting to know Android

This entry is part 1 of 1 in the series Android Native Development with Java

Mobile platforms such as Android and IPhone are becoming the de facto computing devices.  Many people have left their laptops and even tablets behind as the power of smart-phones has increased. Now applications that once ran on the desktop are running on smart-phones. Software development is changing. Every product must contend with mobile support whether it be a website or service, or a desktop application. Users now expect that their data will travel with them and they will have access to it from all the devices they own. For the software developer, that means supporting multiple devices, often supporting multiple code bases and feature sets. Android has been around now for about a decade and has grown to own most of the mobile market. IOS is a close second. There are tools out their that will help the mobile developer develop products for both platforms using a single code base. I’ve written about my favorite, Dart/Flutter in other articles. However, these tools often lack either the flexibility to accomplish certain tasks, or they simply do not support a critical function of the device. When this occurs it is often necessary to fall back on native development. Either writing code that your main application can call, or writing the complete application in the platforms native code. This means that even a cross platform developer using tools such as Flutter or Xamarin often need to maintain a considerable amount of platform specific knowledge. Simply put, knowing native development for a platform is important even if you use cross platform tool sets.

I recently began taking some Android course (thanks to a Google Scholarship, THANK YOU GOOGLE!!! ) and thought I would share my knowledge and experience here. These are not the first Android courses I have taken. But I still feel I am far from an expert in Android development. Things change so quickly and I often am playing catch up just trying to stay abreast of new technologies. Sharing my knowledge with others and teaching others helps me ground my own understanding of a topic. So here I will share what I know a little at a time.

Tools Needed

Throughout this series I will be using Android Studio. At the moment it is version 3.0.1. The latest API is 27 revision 1. Android Studio is free and can run on Linux, Mac, and Windows.  It includes an emulator for running your compiled code though, other emulators from 3rd parties are available. AndroidStudio can be downloaded from: https://developer.android.com/studio/index.html If you would like to follow along I suggest you download and install AndroidStudio. Read the “User Guide” particularly the sections starting from “Meet Android Studio” to “Build And Run Your App”. These sections will help you get things setup and walk you through setting up the emulator. I will assume a familiarity with the Java programming language throughout this series. If you have never used Java but have C++ or C# experience, you should be able to follow along just fine.

Step One:

Ok, now that you have Android Studio setup and working and have an virtual device working for testing. It’s time to start coding.

The base for most Android Apps is the Activity. An activity typically loads the User Interface (UI) and provides some interaction with the user. An activity goes through a number of stages during it’s life cycle.  For most applications the activity is the heart of the application. Most applications have one or more activities however, it is possible for an application to be written without using an activity. These are rare however and are more advanced than we will cover here. You can think of an activity as a user task.

Fig. 1.1 Android Activity Life Cycle. Courtesy, www.developer.android.com

Fig. 1.1 Android Activity Life Cycle. Courtesy, www.developer.android.com

As stated, activities have a life cycle. The android framework provides 6 core callback methods that allow you to interact with the activity life cycle. These are: onCreate(), onStart(), onResume(), onPause(), onStop(), and onRestart() as shown in figure 1.1.

Android activities get created and destroyed based on the user’s interaction and system resource requirements. If the user navigates aways from your application and opens another app that requires resources your app is using, your application will be destroyed and then rebuilt when the user navigates back to it. The same actions can occur when the user rotates the device your app is installed on. Rather than doing a complicated dance to redraw the layout in the new orientation, android simply destroys your app and then recreates it when the user returns to it. This may seem like a drastic measure to take however, android works hard to limit power consumption and extend battery life, and this approach aids that goal.

The onCreate() method is fired when the activity is first created. Android requires that if we use an activity we must override this method in our code. In the onCreate() method we perform the activity logic that should only be completed once in the activities life cycle. Here we can load the layout, set class variables, and retrieve data that may be needed for the activity.

The onCreate() method receives an parameter of savedInstanceState of type Bundle. A bundle is a collection of state variables and data saved from the last run of the application. If the application has never been ran before the bundle will be null and the android framework will create it for us on the first run.

So let’s try some code! Open Android Studio and create a new project. Call it “ActivityApp” and select “Empty Activity” for the application type. Android Studio will create some boiler plate code for you. It should look like this:

 [cc lang="java" tab_size="4" lines="20"]
package me.randallmorgan.activityapp;

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);
  }

}
[/cc]

The first line provides our Java package name. This name comes from the concatenation of the app name and the reverse of the domain name you enter when creating the project. This is a typical java standard for package naming. It ensures that no two packages are named exactly the same. So that when these packages are distributed, there is no confusion as to which package is which or who is responsible for the package. Android follows this java standard package naming convention.

Lines 3 and 4 include the needed framework libraries AppCompatActivity and Bundle. Line 6 is the beginning of our application. We declare a public class MainActivity that extends the AppCompatActivity class found in the android framework code. The public, protected, and private prefixes to our class and methods are used to annotate the visibility of the code. We wont worry about these just yet. But we’ll come back to them in a later post.

Next we Override the onCreate() method from the framework’s AppCompatActivity class and provide our own code to initialize our activity. First we call the onCreate() method of our parent calls AppCompatActivity. This ensures that the framework does the work it needs to do to initialize our activity, such as extracting the state information from the saveInstanceState bundle. Finally, we call setContentView() passing in the resource id of our layout. In this case, the default activity_main.xml layout.

The setContentView() method takes the layout file and turns it into an actual view on the screen. We use the resource layout file to store our UI design. We’ll talk about UI design next time. For now, let’s continue with the activity life cycle.

Logging

Android Studio provides a logging system that allows us to see debug messages. These messages can be grouped into various categories such as Error, Warning, Info, Assert, Debug, Verbose, and WTF (What a Terrible Failure). The WTF level is typically reserved for the framework developers and under normal development conditions shouldn’t be used by mobile developers. To use the logging methods we first need to import the “android:util.Log” library. Next we set a tag value. This tag can be any string value but is usually set to the current class name. Then to print out information to the debug output window (Logcat) we only need to call the Log.d() method. The Log.d method takes to strings values and an option Throwable. A throwable is an exception. Exceptions are a type of error handling that allows a program to catch recoverable errors and do some processing on non recoverable errors  (like logging them).

Log.d() is used for debugging messages. There are other Log methods. One for each type of error message we listed earlier. The ones you might use are Log.d(tag, msg), Log.e(tag, msg), log.i(tag, msg), Log.v(tag, msg), Log.a(tag, msg). The Log.wtf(tag, msg) should only be used if you understand what you’re doing. This is for catastrophic errors only!!! Again, it is best left to the Android framework developers.

So let’s see how logging works. Go back to our ActivityApp project. Open the main_activiy.java file. Edit the code as follows:

[cc lang="java" tab_size="2"]
package me.randallmorgan.activityapp;

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

public class MainActivity extends AppCompatActivity {
  final String mTag = "MainActivity";
  
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    
    super.onCreate(savedInstanceState);
    setContentView(R.layout.test_activity);
    
    Log.d(mTag, "onCreate called.");

  }
}
[/cc]

We’ve added line to declare a class wide string variable of “mTag” and set it’s value to “MainActivity” following standard convention. Next we added a line to the end of our onCreate() method to log our message passing Log.d() the variable mTag, and our message “onCreate called.”. If you run the app in your emulator and open the Logcat window you should be able to locate our message: … D/MainActivity: onCreate called. You may need to filter the output using the dropdown  to show only the messages in the Debug category.

Visualizing the Activity Life Cycle

Ok, now that we have debugging working, let’s try out some of the other functions that get called during the lifecycle of our activity. Edit your code to read as follows:

[cc lang="java" tab_size="2"]
package me.randallmorgan.activityapp;

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

public class MainActivity extends AppCompatActivity {
    final String mTag = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.test_activity);
        Log.d(mTag, "onCreate called.");

    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d(mTag, "onStart called.");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(mTag, "onResume called.");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(mTag, "onPause called.");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(mTag, "onStop called.");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.d(mTag, "onRestart called.");
    }
    
}
[/cc]

Now compile and run the app. Open the Logcat window and you should see the follow debug messages:

  • onCreate called.
  • onStart called.
  • onResume called.

Now rotate the view in the emulator. You’ll see a bunch of text scroll through the Logcat window. If you examine it you should see the following message:

  • onPause called.
  • onStop called.
  • onCreate called.
  • onStart called.
  • onResume called.

As you can see, our app was stopped by the Android framework and then recreated in the new orientation.

Ok, that’s it for today. Next time we’ll discuss layouts and the resource xml files. Then we’ll look at interacting with our layout.

Newsletter Powered By : XYZScripts.com