Fundamentals of Android Programming
Fundamentals of Android Programming
Android is a software package and linux based operating system for mobile devices such as
tablet computers and smartphones.
Android is a complete set of software for mobile devices such as tablet computers, notebooks,
smartphones, electronic book readers, set-top boxes etc.
It can be thought of as a mobile operating system. But it is not limited to mobile only. It is
currently used in various devices such as mobiles, tablets, televisions etc.
Features of Android
Android is a powerful open-source operating system that open-source provides immense
features and some of these are listed below.
Android Open Source Project so we can customize the OS based on our requirements.
Android supports different types of connectivity for GSM, CDMA, Wi-Fi, Bluetooth,
etc. for telephonic conversation or data transfer.
Using wifi technology we can pair with other devices while playing games or using
other applications.
It contains multiple APIs to support location-tracking services such as GPS.
We can manage all data storage-related activities by using the file manager.It contains a
wide range of media supports like AVI, MKV, FLV, MPEG4, etc. to play or record a
variety of audio/video.
It also supports different image formats like JPEG, PNG, GIF, BMP, MP3, etc.
It supports multimedia hardware control to perform playback or recording using a
camera and microphone.
Android has an integrated open-source WebKit layout-based web browser to support
User Interfaces like HTML5, and CSS3.
Android supports multi-tasking means we can run multiple applications at a time and
can switch between them.
It provides support for virtual reality or 2D/3D Graphics.
Android Architecture
Android architecture or Android software stack is categorized into five parts:
1. linux kernel
2. native libraries (middleware),
3. Android Runtime
4. Application Framework
5. Applications
2) Native Libraries
On the top of Linux kernel, there are Native libraries such as WebKit, OpenGL, FreeType,
SQLite, Media, C runtime library (libc), etc.
The WebKit library is responsible for browser support, SQLite is for database, FreeType for
font support, Media for playing and recording audio and video formats.
3) Android Runtime
In android runtime, there are core libraries and DVM (Dalvik Virtual Machine) which is
responsible to run android application. DVM is like JVM but it is optimized for mobile devices.
It consumes less memory and provides fast performance.
4) Android Framework
On the top of Native libraries and android runtime, there is android framework. Android
framework includes Android API's such as UI (User Interface), telephony, resources,
locations, Content Providers (data) and package managers. It provides a lot of classes and
interfaces for android application development .
5) Applications
On the top of android framework, there are applications. All applications such as home, contact,
settings, games, browsers are using android framework that uses android runtime and libraries.
Android runtime and native libraries are using linux kernal.
Android - Environment Setup
operating systems −
Second point is that all the required tools to develop Android applications are freely available
and can be downloaded from the Web. Following is the list of software's you will need before
you start your Android application programming.
Here last two components are optional and if you are working on Windows machine then
these components make your life easy while doing Java based application development. So
let us have a look how to proceed to set required environment.
You can download the latest version of Java JDK from Oracle's Java site − Java SE
Downloads. You will find instructions for installing JDK in downloaded files, follow the
given instructions to install and configure the setup. Finally set PATH and JAVA_HOME
environment variables to refer to the directory that contains java and javac, typically
java_install_dir/bin and java_install_dir respectively.
If you are running Windows and installed the JDK in C:\jdk1.8.0_102, you would have to put
the following line in your C:\autoexec.bat file.
set PATH=C:\jdk1.8.0_102\bin;%PATH%
set JAVA_HOME=C:\jdk1.8.0_102
Alternatively, you could also right-click on My Computer, select Properties, then Advanced,
then Environment Variables. Then, you would update the PATH value and press the OK
button.
On Linux, if the SDK is installed in /usr/local/jdk1.8.0_102 and you use the C shell, you
would put the following code into your .cshrc file.
Alternatively, if you use Android studio, then it will know automatically where you have
installed your Java.
Android IDEs
There are so many sophisticated Technologies are available to develop android applications,
the familiar technologies, which are predominantly using tools as follows
Android Studio
Eclipse IDE(Deprecated)
Android SDK
The Android SDK (Software Development Kit) is a set of development tools provided by
Google that enables developers to create applications for the Android operating system. It
includes a variety of essential components that allow developers to build, test, and debug
Android apps.
1. Libraries and APIs: These are the fundamental building blocks for creating Android
apps. They provide the functions needed to access features like the user interface,
sensors, networking, data storage, and more.
2. Android Emulator: A tool that allows developers to simulate Android devices on
their computer. It is used for testing applications without needing a physical Android
device.
3. SDK Tools: These are command-line tools that help developers interact with Android
Studio and manage Android app projects. They include tools for building, testing, and
debugging apps, such as adb (Android Debug Bridge), fastboot, and avdmanager.
4. Android Studio: The official integrated development environment (IDE) for Android
development. It provides features like code editing, UI design, debugging, and
performance analysis.
5. Platform Tools: These tools help in developing and testing apps on specific versions
of Android. They provide the necessary files to interact with Android devices running
different versions of the OS.
6. Build Tools: These are the tools used for compiling and building APK files (the
Android app package format) from source code. They handle tasks like optimizing
resources and packaging the app.
7. Sample Code: The SDK includes sample projects and code snippets that help
developers understand how to implement different features in their apps.
In short, the Android SDK provides everything necessary to develop Android apps, from the
core libraries to testing tools and platform-specific features. It's commonly used in
combination with Android Studio, although other IDEs can also support Android
development with the SDK.
Android Emulator
The Android emulator is an Android Virtual Device (AVD), which represents a specific
Android device. We can use the Android emulator as a target device to execute and test our
Android application on our PC. The Android emulator provides almost all the functionality of
a real device. We can get the incoming phone calls and text messages. It also gives the location
of the device and simulates different network speeds. Android emulator simulates rotation and
other hardware sensors. It accesses the Google Play store, and much more
Testing Android applications on emulator are sometimes faster and easier than doing on a real
device. For example, we can transfer data faster to the emulator than to a real device connected
through USB.
The Android emulator comes with predefined configurations for several Android phones, Wear
OS, tablet, Android TV devices.
1. In Android Studio, we need to create an Android Virtual Device (AVD) that the emulator
can use to install and run your app. To create a new AVD:-
1.1 Open the AVD Manager by clicking Tools > AVD Manager.
1.2 Click on Create Virtual Device, at the bottom of the AVD Manager dialog. Then Select
Hardware page appears.
Advertisement
1.3 Select a hardware profile and then click Next. If we don?t see the hardware profile we
want, then we can create or import a hardware profile. The System Image page appears.
1.4 Select the system image for the particular API level and click Next. This leads to open
a Verify Configuration page.
1.5 Change AVD properties if needed, and then click Finish.
2. In the toolbar, choose the AVD, which we want to run our app from the target device
from the drop-down menu.
3. Click Run.
While the emulator is running, we can run the Android Studio project and select the emulator
as the target device. We can also drag an APKs file to install on an emulator, and then run
them.
1. $ emulator -list-avds
Run and stop an emulator, and clear data
From the Virtual Device page, we can perform the following operation on emulator:
o To run an Android emulator that uses an AVD, double-click the AVD, or click Launch
o To stop the running emulator, right-click and select Stop, or click Menu ▼ and select
Stop.
o If we want to clear the data from an emulator and return it to the initial state when it
was first defined, then right-click an AVD and select Wipe Data. Or click menu ▼ and
select Wipe Data.
Now double click on the exe file, it will be installed. I am using the android 2.2 version here.
1) Start the eclipse IDE, then select Help > Install new software...
5) click finish
Now select the android from the left panel. Here you may see a dialog box asking if you want
to send the statistics to the google. Click proceed.
Click on the browse button and locate your SDK directory e.g. my SDK location is C:\Program
Files\Android\android-sdk .
2) Provide the following information: Application name, Company domain, Project location and
Package name of application and click next.
3) Select the API level of application and click next.
4) Select the Activity type (Empty Activity).
5) Provide the Activity Name and click finish.
After finishing the Activity configuration, Android Studio auto generates the activity class and
other required configuration files.
Now an android project has been created. You can explore the android project and see the simple
program, it looks like this:
2) Write the message
File: activity_main.xml
Android studio auto generates code for activity_main.xml file. You may edit this file according
to your requirement.
1. package first.javatpoint.com.welcome;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5.
6. public class MainActivity extends AppCompatActivity {
7. @Override
8. protected void onCreate(Bundle savedInstanceState) {
9. super.onCreate(savedInstanceState);
10. setContentView(R.layout.activity_main);
11. }
12. }
To understand the first android application, visit the next page (internal details
of hello android example).
Android Components
There are some necessary building blocks that an Android application consists of.
These loosely coupled components are bound by the application manifest file
which contains a description of each component and how they interact.
Activity:
o Activity life cycle
o Handle Activity State Changes
o Understand Tasks and Back Stack
o Processes and Application Lifecycle
Services:
Types of Android Services
o
o The Life Cycle of Android Services
Content Provider:
o Content URI
o Operations in Content Provider
o Working of the Content Provider
o Creating a Content Provider
Broadcast Receiver:
o Implicit Broadcast Exceptions
Definition: An Activity represents a single screen with a user interface in an Android app. It
is where most of the user interaction happens. Each activity is responsible for managing the
user interface (UI) elements and responding to user inputs like clicks, gestures, etc.
Lifecycle: Activities have a lifecycle, which determines the state of the activity as it is
created, paused, resumed, or destroyed. Understanding the activity lifecycle is essential for
managing memory and resources efficiently in your app.
Example: The home screen of a messaging app or the settings screen is typically an activity.
2. Services
Definition: A Service is a component that runs in the background and does not have a user
interface. It can perform long-running tasks like downloading files, playing music, or
interacting with a web API while the user is interacting with other parts of the app.
Types:
o Started Service: A service that is started by an application component and runs until
it's explicitly stopped.
o Bound Service: A service that allows other components (such as activities) to bind to
it and interact with it in real time.
Example: A music player app running in the background to play music even when the user
navigates to another screen.
3. Broadcast Receivers
4. Content Providers
5. Intents
Definition: An Intent is a messaging object that is used to request an action from another app
component. Intents can be used to start activities, services, or broadcast receivers.
Types:
o Explicit Intent: Specifies the exact component (such as a specific activity or service)
to be started.
o Implicit Intent: Does not specify a specific component but allows the system to
choose the appropriate component based on the intent's action and data.
Example: An implicit intent could be used to open a URL in the web browser, or an explicit
intent could start a specific activity in your app to display a list of contacts.
6. Resources
Definition: Resources in Android are non-code assets that an app can use, such as layouts,
strings, images, colors, and styles. These resources are stored in the res/ directory and are
accessed by the app's components.
Types:
o Layout Resources: Defines the UI layout using XML files (e.g., activity_main.xml).
o String Resources: Stores strings used in the app, such as text labels (e.g., strings.xml).
o Drawable Resources: Stores images and icons used in the app (e.g., drawable/
folder).
o Style Resources: Defines UI appearance settings (e.g., styles.xml).
o Raw Resources: Stores raw files like audio files, JSON files, etc.
Definition: The AndroidManifest.xml file is a critical part of every Android app. It declares
essential information about the app to the Android system, including:
o The permissions required by the app (e.g., internet access, location data).
o The components (activities, services, receivers, content providers) used in the app.
o The app’s theme and UI configurations.
o The app’s entry point (e.g., which activity is the launcher).
Example: The manifest specifies which activity should be launched when the app is started.
8. Fragments
Definition: A Fragment is a reusable portion of an activity’s user interface (UI) and logic.
Fragments allow developers to build flexible and modular UI components that can be reused
across different activities. Fragments have their own lifecycle and can be dynamically added
or removed from activities.
Example: In a tablet app, you might use fragments to display a list of items on the left side of
the screen and the details of a selected item on the right side.
Views: A View is a basic building block for user interface elements in Android. It represents
individual UI components like buttons, text fields, images, and so on.
ViewGroups: A ViewGroup is a container that holds and manages other views (including
other view groups). Examples of ViewGroups are LinearLayout, RelativeLayout,
ConstraintLayout, and FrameLayout.
Example: A Button is a View that can be placed inside a LinearLayout ViewGroup.
10. SharedPreferences
Definition: Android provides an embedded database system called SQLite to store structured
data locally in a device. You can create tables, insert, update, and query the data using SQL
queries.
Example: A shopping list app that stores items in a local SQLite database.
When you create a new Android project using Android Studio, the project folder will have a
structure that looks like this:
bash
Copy code
MyAndroidApp/ # Root folder of the project
├── .git/ # Git version control directory (if using Git)
├── .gradle/ # Gradle wrapper and build-related files
├── build/ # Generated build files (e.g., APKs, intermediates, etc.)
├── gradle/ # Gradle-specific files and wrapper
├── app/ # Main Android app module folder (contains source code, resources, etc.)
├── build.gradle # Root-level Gradle build file (for project-wide configuration)
├── settings.gradle # Specifies which modules to include in the project
└── gradle.properties # Project-level properties for Gradle build
The app/ Folder (Main Module)
The app/ folder contains all the essential files for the Android app itself, including code,
resources, and configuration. Here’s the detailed folder structure inside the app/ directory:
bash
Copy code
app/
├── src/ # Source code folder
│ ├── main/ # Main source set for the app
│ │ ├── java/ # Java source code for your app
│ │ │ └── com/
│ │ │ └── example/
│ │ │ └── myandroidapp/
│ │ │ ├── MainActivity.java # Activity files (Java classes)
│ │ │ ├── SecondActivity.java
│ │ │ └── ... # Other classes, e.g., utilities, model, etc.
│ │ ├── res/ # Resources folder (layouts, images, strings, etc.)
│ │ │ ├── drawable/ # Images and drawable resources (PNG, XML, etc.)
│ │ │ │ └── logo.png
│ │ │ ├── layout/ # XML files for UI layout
│ │ │ │ └── activity_main.xml
│ │ │ ├── mipmap/ # App icons (for various resolutions)
│ │ │ ├── values/ # Resource files (colors, strings, styles, themes, etc.)
│ │ │ │ ├── colors.xml
│ │ │ │ ├── strings.xml
│ │ │ │ └── styles.xml
│ │ │ └── raw/ # Raw resources (audio, JSON files, etc.)
│ │ │ └── data.json
│ │ ├── AndroidManifest.xml # The manifest file declaring app components and permissions
│ │ └── assets/ # Assets folder for non-resource files (e.g., fonts, HTML files, etc.)
│ └── test/ # Unit tests for your app
│ └── androidTest/ # UI tests for your app
├── build.gradle # Module-level Gradle build file (specific to the app module)
└── proguard-rules.pro # Proguard configuration file (if minification or obfuscation is used)
Explanation of Key Folders and Files
1. src/ Folder
2. AndroidManifest.xml
This is a critical configuration file that declares essential information about the app, such as:
o Permissions: Declares which permissions the app requires (e.g., camera, location).
o Components: Declares the activities, services, and receivers that make up the app.
o App entry point: Declares which activity is launched when the app starts.
o Themes and settings: Defines themes, app metadata, and configuration.
3. build.gradle Files
Root build.gradle: Defines project-level settings like the Gradle plugin version and
repositories.
Module-level build.gradle (app/): Defines settings specific to the app module, including
dependencies, build types (debug/release), and version information.
4. assets/ Folder
A folder used to store raw files that your app may need to access (e.g., fonts, custom HTML
files, or databases). These files are not processed or indexed by Android’s resource
management system, so they are accessed via the AssetManager.
5. proguard-rules.pro
This file contains ProGuard (or R8) rules for obfuscating, minifying, and optimizing the
app's code. It’s often used to shrink the app's size and protect it from reverse engineering.
6. gradle.properties
A file to define Gradle properties specific to the project. You can define global properties or
variables to control the build process.
7. settings.gradle
This file specifies which modules are included in the project. For single-module projects, this
file typically contains a simple configuration like:
gradle
Copy code
include ':app'
8. Test Folders (test/ and androidTest/)
test/: Contains unit tests (JUnit tests) that test the app’s logic.
androidTest/: Contains UI tests or instrumentation tests that test your app’s behavior on an
actual or virtual Android device.
src/ Contains the source code (Java/Kotlin files) and resources (layout, drawable).
res/ Stores all non-code assets (images, layouts, strings, colors, etc.).
AndroidManifest.xml Describes essential information about the app (components, permissions, etc.).