Beginning Android and Java

Welcome to Android Programming for Beginners, In this article, we’ll jump right into creating Android apps. We’ll explore why Android is so popular, what Android and Java are, how they work together, and why that matters for us as future developers.

We’ll quickly set up the software needed to build and launch a simple first app.

By the end of this chapter, we’ll have:

  • I learned how Java and Android work together
  • Set up Android Studio, the software that helps us build Android apps
  • I learned about the Java Development Kit (JDK) and the Android API, and how to use them with Android Studio
  • We built our first Android app
  • Deploy and run the app on an Android emulator and a real device

There’s a lot to cover in this article, so let’s get started!

Technical requirements

Here are the basic technical requirements for Android development with Android Studio:

For Windows:

  • Windows 7, 8, or 10 (64-bit)
  • At least 4 GB of RAM (8 GB recommended)
  • At least 2 GB of free disk space (4 GB recommended: 500 MB for the IDE and 1.5 GB for the Android SDK and emulator)
  • Screen resolution of at least 1280 x 800

For Mac:

  • macOS 10.10 (Yosemite) or higher, up to 10.14 (Mojave)
  • At least 4 GB of RAM (8 GB recommended)
  • At least 2 GB of free disk space (4 GB recommended: 500 MB for the IDE and 1.5 GB for the Android SDK and emulator)
  • Screen resolution of at least 1280 x 800

For Linux:

  • GNOME or KDE desktop
  • A 64-bit system that can run 32-bit applications
  • GNU C Library (glibc) version 2.19 or later
  • At least 4 GB of RAM (8 GB recommended)
  • At least 2 GB of free disk space (4 GB recommended: 500 MB for the IDE and 1.5 GB for the Android SDK and emulator)
  • Screen resolution of at least 1280 x 800

Why Java and Android?

When Android launched in 2008, it wasn’t as stylish as iOS, but it quickly gained popularity due to its variety of affordable and fashionable devices.

For many, including myself, developing for Android is incredibly rewarding, both as a hobby and as a business. Creating and refining an app is an exciting process that feels uniquely fulfilling.

One reason for this is that Android is free and open-source, allowing developers to distribute apps freely. The personal nature of Android devices also makes it special—you’re creating something that people carry with them everywhere, impacting their daily lives.

Android development is highly respected, and skilled developers are in high demand. With the growth of Android devices and technology, the need for developers will only increase.

How Java and Android work together

The Android API simplifies complex tasks by providing pre-written code that developers can leverage. Imagine the API as the accelerator in a car: pressing it triggers a complex set of actions under the hood, but you only interact with the accelerator pedal.

Consider the following Java code snippet, which may look complex at first:

LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double latitude = location.getLatitude();
double longitude = location.getLongitude();

This line of code uses the Android API to find available satellites, communicate with them, and retrieve your precise latitude and longitude. This illustrates the power and depth of the Android API when used with compiled bytecode and the Android Runtime (ART).

The Android API provides a wealth of pre-written Java code, which simplifies the development process by handling complex functionalities for you.

The essential question is: how do we effectively use this code to build sophisticated apps? The answer is the Java programming language, designed to manage complexity and interface with the Android API seamlessly.

Java is object-oriented

Java is a programming language that’s been around for a long time, even before Android. It’s an object-oriented language, which means it uses reusable pieces of code called “objects.”

To make this clearer, think about how cars are made. A car manufacturer doesn’t design each part from scratch every time. Instead, they create parts that can be used in many cars and refine them over time. Similarly, Java lets developers create and reuse code parts, called “classes,” that work like blueprints for building objects.

When we use Java to write code, we create these blueprints (classes) and then make objects from them. For example, the Android development team has created complex Java code to communicate with satellites. They make this code easy to use for developers by simplifying it into a single line of code that handles many details behind the scenes.

This process of using pre-written code to simplify our own coding is a key part of object-oriented programming (OOP). OOP allows us to build apps more easily by reusing and combining these objects.

Can you explain again: what is Android?

To build an Android app, we write our own Java code and use the Android API’s code. This code is turned into bytecode and then converted into machine code by ART when the app is installed. Machine code works with the Linux operating system, which manages the different hardware in Android devices.

Device makers write special software called drivers to ensure their hardware (like CPUs, GPS receivers, and memory) works well with Linux.

The bytecode and other resources are packed into an Android Application Package (APK), which ART uses to set up the app for the user.

Android Studio

A development environment encompasses all the tools and resources necessary to set up, develop, and deploy software efficiently in one cohesive space. For Android development, two key components form the foundation of this environment:

  1. Java Development Kit (JDK): Java is the backbone of Android development. Before our Java code (or code from other developers) can be executed on an Android device, it must be compiled into bytecode and subsequently translated into machine code. The JDK is an essential software package that provides the tools needed to compile Java code. It includes a vast library of pre-written code that is distinct from the Android API but crucial for development.
  2. Android Software Development Kit (SDK): Developing Android applications requires a specialized set of tools and the Android API itself. The Android SDK is a comprehensive collection of these tools, including libraries, debuggers, emulators, and more. Fortunately, the Android SDK is bundled within a single application, Android Studio, making it easier to manage and access everything you need in one place.

Why Android Studio is Essential for Android Development

Android Studio is an Integrated Development Environment (IDE) specifically designed to streamline the Android development process. It simplifies the complex tasks of code compilation, linking with the JDK, and integrating the Android API. Once Android Studio is installed, developers can focus entirely on coding and designing within the IDE, as it handles much of the underlying complexity automatically.

With Android Studio, you have a powerful tool at your disposal that not only accelerates development but also ensures that all essential components are seamlessly integrated. This allows developers to concentrate on innovation without being bogged down by the intricacies of the environment setup.

Setting up Android Studio

Setting up Android Studio is easy, though it may take some time. Grab a snack and follow these steps. We’ll be installing Android Studio on the D drive, which is usually larger and has more free space than the C drive. If you prefer a different drive, you can adjust the instructions as needed.

  1. Download Android Studio:
  1. Prepare Your Folders:
  • While it downloads, create a folder named Android on the root of your D drive. Inside this folder, create three subfolders: Android Studio, Projects, and Sdk. These will store the program, your projects, and the Android SDK.
Android folder
Android folder
  1. Install Android Studio:
  • Once the download finishes, find the file (named something like android-studio-ide...) and double-click it to start the installation.
  • Grant the installer administrative privileges and click “Next” to begin.
  • On the “Choose Components” screen, make sure both “Android Studio” and “Android Virtual Device” are checked, then click “Next.”
Choose Components screen
Choose Components screen
  1. Set the Installation Path:
  • In the “Configuration Settings” window, click “Browse” and navigate to D:\Android\Android Studio. Click “OK,” then “Next.”
  • On the “Choose Start Menu Folder” window, just click “Install” to continue.
Configuration Settings window
Configuration Settings window
  1. Complete the Installation:
  • When the first part of the installation is complete, click “Next,” then “Finish.” Android Studio should start automatically, but if it doesn’t, you can launch it from the Start menu.
  1. Set Up the SDK:
  • You’ll be prompted about a missing SDK. Click “Next” to continue.
  • On the “SDK Components Setup” screen, change the install location by clicking the “Android SDK Location” field and browsing to D:\Android\Sdk. Click “Next.”
SDK Components Setup screen
SDK Components Setup screen
  1. Finish Up:
  • On the “Verify Settings” window, click “Finish.” Android Studio will download additional files to complete the installation. This may take a few minutes, and you might need to allow access to your PC.
  1. Launch Android Studio:
  • When it’s done, click “Finish.” You’ll see the Android Studio welcome screen. You can either proceed with your next steps or close the app and reopen it later from the Start menu.
Android Studio welcome screen
Android Studio welcome screen

Now that Android Studio is set up, you can start developing Android apps!

What makes an Android app?

We will write Java code that uses other people’s Java code. This will be compiled into bytecode and then converted into machine code on our users’ Android devices. Besides the Java code, we will also add and edit other files, called Android resources, included in the final APK.

Android resources

Our app will use resources like images, sounds, and User Interface (UI) layouts stored in separate files from the Java code.

The app will also have files for the text content. Storing text separately makes it easy to change and adapt the app for different languages and regions. Even though we can design the UI visually, Android reads the layout from text-based files.

Since computers don’t understand text like humans do, we need to organize these files in a specific way using a format called XML (eXtensible Markup Language). XML is designed to be readable by both humans and computers. We won’t need to learn all of XML, just follow some basic rules. Most of the time, we’ll use a visual editor in Android Studio to handle XML files, which have names ending with.xml.

The structure of Android’s Java code

Java code for Android is organized in a specific structure. There are millions of lines of code we can use, so it needs to be easy to find and reference. This code is organized into groups called packages, which are specific to Android.

Packages:

When we create a new Android app, we give it a unique name called a package. We will see how to do this later in the book. Packages can also be divided into sub-packages, like folders and sub-folders, to keep similar packages together.

Think of the Android API packages as a code library we can use. Some common Android packages are:

  • android.graphics
  • android.database
  • android.view.animation

These packages are named to clearly show what they contain.

Classes

In Android development with Java, classes are a fundamental building block that define objects’ properties and behaviors. Here’s a breakdown of some key types of classes you’ll commonly use in Android development:

1. Activity Class

  • Purpose: Represents a single screen with a user interface.
  • Example: MainActivity is an example of an Activity class that might display a list of items.
  • Lifecycle Methods: Includes methods like onCreate(), onStart(), onResume(), onPause(), onStop(), and onDestroy(). These methods are used to manage the activity’s lifecycle.
java
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Sets the UI layout for this activity } }

2. Fragment Class

  • Purpose: Represents a portion of the UI in an Activity. Fragments are used to build dynamic and flexible UIs.
  • Example: A Fragment class might handle a single screen component, like a user profile section.
  • Lifecycle Methods: Includes methods like onCreateView(), onActivityCreated(), onStart(), onResume(), and more.
java
public class ExampleFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_example, container, false); } }

3. Service Class

  • Purpose: Represents an application component that performs long-running operations in the background.
  • Example: A Service class might handle playing music in the background or downloading files.
  • Lifecycle Methods: Includes onStartCommand(), onBind(), and onDestroy().
java
public class ExampleService extends Service { @Override public int onStartCommand(Intent intent, int flags, int startId) { // Perform some background operation return START_STICKY; } @Override public IBinder onBind(Intent intent) { return null; } }

4. BroadcastReceiver Class

  • Purpose: Listens for and handles broadcast messages from other applications or the system.
  • Example: A BroadcastReceiver might listen for system events like network changes or battery status updates.
  • Lifecycle Methods: Has a single method onReceive(), which is called when a broadcast is received.
java
public class ExampleReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // Handle the broadcast message } }

5. ContentProvider Class

  • Purpose: Manages access to a structured set of data. It is typically used to share data between different applications.
  • Example: A ContentProvider might provide data about contacts, photos, etc.
  • Key Methods: Includes query(), insert(), delete(), and update().
java
public class ExampleProvider extends ContentProvider { @Override public boolean onCreate() { // Initialize your content provider return true; } }

6. Application Class

  • Purpose: Provides a base class for maintaining global application state.
  • Example: A custom Application class might initialize libraries or manage app-wide resources.
  • Lifecycle Methods: Includes onCreate() and onTerminate().
java
public class ExampleApp extends Application { @Override public void onCreate() { super.onCreate(); // Initialize global state here } }
  • Activities and Fragments handle the UI.
  • Services manage background tasks.
  • BroadcastReceivers listen for system-wide broadcasts.
  • ContentProviders offer structured data access.
  • Application classes manage global app state.

Methods

In Android development with Java, methods are functions that perform specific tasks. Different types of methods are used in Android classes, such as lifecycle methods, event-handling methods, utility methods, and more. Here’s an overview of some of the most common methods used in various Android classes:

1. Activity Methods

Activity methods manage the lifecycle and user interactions within an Activity. Here are some important ones:

  • onCreate(Bundle savedInstanceState): Called when the activity is first created. This is where you initialize your activity, set up the UI, and set listeners.

    java
    @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); }
  • onStart(): Called when the activity becomes visible to the user.

    java
    @Override protected void onStart() { super.onStart(); }
  • onResume(): Called when the activity starts interacting with the user. This is where the activity is in the foreground.

    java
    @Override protected void onResume() { super.onResume(); }
  • onPause(): Called when the activity is partially obscured or is about to go into the background.

    java
    @Override protected void onPause() { super.onPause(); }
  • onStop(): Called when the activity is no longer visible to the user.

    java
    @Override protected void onStop() { super.onStop(); }
  • onDestroy(): Called before the activity is destroyed.

    java
    @Override protected void onDestroy() { super.onDestroy(); }

2. Fragment Methods

Fragments also have lifecycle methods similar to activities, but they are specific to fragments:

  • onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState): Creates and returns the view hierarchy associated with the fragment.

    java
    @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_example, container, false); }
  • onViewCreated(View view, Bundle savedInstanceState): Called immediately after onCreateView(), and is used to set up any view-related logic.

    java
    @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); }
  • onAttach(Context context): Called when the fragment is attached to its parent activity.

    java
    @Override public void onAttach(Context context) { super.onAttach(context); }
  • onDetach(): Called when the fragment is detached from its parent activity.

    java
    @Override public void onDetach() { super.onDetach(); }

3. Service Methods

Service methods manage background operations that need to run even if the app is not in the foreground:

  • onStartCommand(Intent intent, int flags, int startId): Called when a service is started using startService(). Used to handle start requests.

    java
    @Override public int onStartCommand(Intent intent, int flags, int startId) { return START_STICKY; }
  • onBind(Intent intent): Called when another component wants to bind with the service using bindService().

    java
    @Override public IBinder onBind(Intent intent) { return null; // Return null if no binding is allowed }
  • onDestroy(): Called when the service is no longer used and is being destroyed.

    java
    @Override public void onDestroy() { super.onDestroy(); }

4. BroadcastReceiver Methods

BroadcastReceiver methods handle broadcasts sent by the system or other apps:

  • onReceive(Context context, Intent intent): Called when the receiver receives a broadcast. The Intent parameter contains the data about the broadcast.

    java
    @Override public void onReceive(Context context, Intent intent) { // Handle the broadcast }

5. ContentProvider Methods

ContentProvider methods manage shared data in a structured format:

  • query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder): Retrieves data from the content provider.

    java
    @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { // Query the data return null; }
  • insert(Uri uri, ContentValues values): Inserts new data into the content provider.

    java
    @Override public Uri insert(Uri uri, ContentValues values) { // Insert data return null; }
  • delete(Uri uri, String selection, String[] selectionArgs): Deletes data from the content provider.

    java
    @Override public int delete(Uri uri, String selection, String[] selectionArgs) { // Delete data return 0; }
  • update(Uri uri, ContentValues values, String selection, String[] selectionArgs): Updates existing data in the content provider.

    java
    @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { // Update data return 0; }

6. Utility Methods

These are custom methods created by developers to handle specific tasks, such as calculations, network operations, or data manipulation. These methods can be created in any class to perform specific functionalities.

java
public void fetchDataFromServer() { // Code to fetch data from a server }

Summary of Methods in Android:

  • Activity and Fragment Methods: Manage lifecycle and UI.
  • Service Methods: Handle background tasks.
  • BroadcastReceiver Methods: Process broadcast messages.
  • ContentProvider Methods: Provide structured data access.
  • Utility Methods: Perform custom tasks as needed by the app.
Android API
Android API

Building our first Android app

In programming, it’s a tradition for beginners to create a simple app that says “Hello, World!” using their chosen language or operating system. We’ll start by building this basic app.

To start your project in Android Studio, follow these steps:

  • Open Android Studio: Launch it like any other app. On Windows 10, you’ll find the icon in the Start menu.
    Tip: If asked to “Import Studio settings,” choose “Do not import settings.”
  • Welcome Screen: On the Android Studio welcome screen, select “Start a new Android Studio project.”
Android Studio welcome screen
Android Studio welcome screen
  • Select a Project Template: In the “Select a Project Template” window, choose the Basic Activity option. This template will automatically generate some starter code and resources. We’ll explain these in more detail in the next chapter. Make sure “Basic Activity” is selected, and then click Next.
Select a Project Template window
Select a Project Template window
  • Configure Your Project: In the “Configure Your Project” window, you will:
    • Enter the project name (“Hello World”).
    • Choose a location on your computer to save the files (like the “Projects” folder).
    • Provide a package name (a unique identifier for your project; use a format like com.yourdomainname or com.gamecodeschool.helloworld).
    • Select the programming language you want to use.
Configure Your Project screen
Configure Your Project screen
  • Package Name: The package name can be almost anything. If you have a website, use your domain name (e.g., com.yourdomainname). If not, you can use com.gamecodeschool.helloworld or make up any name you like. The package name only matters if you decide to publish the app.

Deploying the app so far

Before we start learning Java and looking at the code, you might be surprised to know that we can already run our project. It won’t have many features yet, but since we will be running the app often to check our progress, let’s see how to do that. You have three options:

  1. Run the app in debug mode on an emulator (a virtual Android device on your PC) using Android Studio.
  2. Run the app on a real Android device using USB debugging.
  3. Export the app as a full Android project to upload to the Play Store.

Option 1: Running on the Emulator

This is the easiest to set up because we did it when installing Android Studio. If your PC is powerful, the emulator will run almost like a real device. However, since mouse clicks replace screen touches, it might not be suitable for testing certain features, like a drawing app. You might still prefer testing on a real device from time to time, as I do.

Option 2: Running on a Real Device

This takes a few more steps to set up but provides more accurate results since it uses real screen touches. Once set up, it works as well as the emulator.

Option 3: Exporting the App

This takes at least 5 minutes to prepare. After that, you have to manually install the app on a real device each time you change the code.

What’s the Best Approach?

Use the emulator to quickly test and debug small changes. Regularly test on a real device using USB debugging to ensure everything works correctly. Only occasionally export a full package.

Now, let’s go through how to run the app using both the emulator and USB debugging on a real device.

Running and debugging the app on an Android emulator

To run your app on the default Android emulator, follow these steps:

  1. In Android Studio, go to the menu bar and select Tools > AVD Manager. AVD stands for Android Virtual Device, which is an emulator. You’ll see a list of available emulators.
AVD Manager
AVD Manager
  • There should be an emulator listed (like “Pixel_3a_API_30_x…”). Your emulator might be named differently, but that’s okay.
  1. Click the green play icon next to the emulator’s name to start it. Wait for the emulator to boot up.
 Play icon
Play icon
  1. Once the emulator is running, click the play icon on the Android Studio quick launch bar. If asked, select your emulator (e.g., “Pixel_3a_API_30_x…”) to launch the app.
What the app looks like so far
What the app looks like so far

That’s it! Your app should now be running on the emulator. Don’t worry if your emulator looks different; that’s fine.

Right now, the app is very basic and displays a message, “Hello first fragment.” A fragment is a common part of Android apps, and we’ll learn more about them later. If you click “Next,” a new empty screen will appear; “Previous” takes you back to the first screen. Not bad, considering we haven’t written any code yet!

Why Use an Emulator?

Testing and debugging are important throughout development to find errors, crashes, and ensure the app works correctly on different devices.

Emulators are great for this because they can mimic many different Android devices, but they might be slower than real devices. To get the best idea of how your app feels for users, you’ll want to test on both real devices and emulators.

How to Create a New Emulator

If you want to try your app on a different device, like a tablet, you can create a new emulator:

  1. Go to Tools > AVD Manager.
  2. Click Create Virtual Device.
  3. Choose the device type (TV, Phone, Wear OS, or Tablet).
  4. Click Next and follow the steps to create your new emulator.
Play icon from the Android Studio toolbar
Play icon from the Android Studio toolbar

Next time you run your app, you’ll see the new emulator as an option.

Now, let’s learn how to run the app on a real device.

Running the app on a real device

First, visit your device manufacturer’s website to download and install any necessary drivers for your device and operating system.

Next, follow these steps to set up your Android device for debugging. The exact steps may vary slightly depending on your device, but this should be similar for most:

  1. Open the Settings menu on your phone or tablet.
  2. Go to About device or About Phone.
  • Find the Build Number option and tap it repeatedly until you see a message saying, “You are now a developer!” This unlocks the Developer options menu.
  1. Go back to the Settings menu.
  2. Tap Developer options.
  3. Enable USB Debugging by checking the box.
  4. Connect your Android device to your computer using a USB cable.
  5. Click anywhere in Android Studio to detect your connected device. You will see a prompt on your device asking, “Allow USB debugging?” — tap Allow.
  6. Click the play icon on the Android Studio toolbar.

When prompted, click OK to run the app on your device.

Now you’re ready to learn Java and start adding your own code to the “Hello World” project in the next chapter!

Leave a Comment