SlideShare a Scribd company logo
How Java is used in Android Application Development
Java is the technology of choice for building applications using managed code that can execute
on mobile devices.
Android is an open source software platform and Linux-based operating system for mobile
devices. The Android platform allows developers to write managed code using Java to manage
and control the Android device. Android applications can be developed by using the Java
programming language and the Android SDK. So, familiarity with the basics of the Java
programming language is a prerequisite for programming on the Android platform.
Here we discuss where Java fits in mobile application development and how we can use
Java and Android SDK to write applications that can work on Android devices.
The Choice of Java
What made Java be the technology of choice for mobile development for the Android
platform?
The Java Programming Language emerged in the mid-1990s; it was created by James Gosling of
Sun Microsystems. Incidentally, Sun Microsystems was since bought by Oracle. Java has been
widely popular the world over, primarily because of a vast array of features it provides. Java’s
promise of “Write once and run anywhere”(WORA) was one of the major factors for the success
of Java over the past few decades.
Java even made inroads into embedded processors technology as well; the Java Mobile
Edition(JME) was built for creating applications that can run on mobile devices. All these, added
to Java’s meteoric rise, were the prime factors that attributed to the decision of adopting Java as
the primary development language for building applications that run on Android. Java programs
are secure because they run within a sandbox environment[sandbox environment is an isolated
virtual machine in which potentially unsafe software code can execute without affecting
network resources or local applications. Cybersecurity researchers use sandboxes to run
suspicious code from unknown attachments and URLs and observe its behavior]. Programs
written in Java are compiled into intermediate code known as bytecode. This bytecode is then
executed inside the context of the Java Virtual Machine.
Using Java for Building Mobile Applications
The mobile edition of Java is called Java ME. Java ME is based on Java SE and is supported by
most smartphones and tablets. The Java Platform Micro Edition (Java ME) provides a flexible,
secure environment for building and executing applications that are targeted at embedded and
mobile devices. The applications that are built using Java ME are portable, secure, and can take
advantage of the native capabilities of the device. Java ME addresses the constraints that are
involved in building applications that are targeted at mobile devices. In essence, Java ME
addresses the challenge of executing applications on devices that are low on available memory,
display, and power.
There are various ways to build applications for Android devices, but the recommended
approach is to leverage the Java programming language and the Android SDK
The Dalvik Virtual Machine (Dalvik VM)
The Android platform leverages the Dalvik Virtual machine (Dalvik VM) for memory, security,
device, and process management. Although the internal intricacies of how the Dalvik Virtual
Machine works is not that important to an average developer, you can think of the Dalvik VM as
a box that provides the necessary environment for you to execute an Android application sans the
need of having to worry about the target device.
To get started using Java for Android, you should first download and install Android Studio. You
then may want to take advantage of the SDK Manager to download and install the latest SDK
tools and platforms.
The purpose of the DVM is to hide the complexity and diversity of hardware and software that
Android runs on, but, at the same time, exposing all its useful features. This exposing of features
works in two ways:
1. First, the DVM itself must have access to the hardware, which it does.
2. Second, this access must be programmer friendly and easy to use, and it is because of the
Android Application Programming Interface or API.
Summary
Programs that are targeted at the Android platform are written in Java and executed by the
Dalvik Virtual Machine (DVM).
The Android API
The Android API is code that makes it easy to do exceptional things. A simple analogy could be
drawn with a machine, perhaps a car. When you press on the accelerator, a whole bunch of
things happen under the hood. We don’t need to understand about combustion or fuel pumps
because some smart engineer has made an interface for us—in this case a mechanical interface—
the accelerator pedal.
The following line of Java code serves as a good example of how the Android API helps us:
locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER)
Once you learn that this single line of code searches for available satellites in space, then
communicates with them in their orbits around the Earth, and then retrieves your precise latitude
and longitude on the surface of the planet, it becomes easy to begin to glimpse the power and
depth of the Android API in conjunction with the DVM.
For sure, that code does look a little challenging, even mind boggling, but imagine trying to talk
to a satellite some other way!
The Android API has a whole bunch of Java code that has already been written for us to use as
we like.
Java is object-oriented
Java is a programming language that has been around a lot longer than Android. It is an object-
oriented language. This means it uses the concept of reusable programming objects. If this
sounds like technical jargon, another analogy will help. Java enables us and others (like the
Android development team) to write Java code that can be structured based on real-world things,
and here is the important part: it can be reused.
Features: Robust, Secure, Dynamic, flexible, Platform Independent etc.,
Run that by me again – What exactly is Android?
To get things done on Android, we write Java code of our own, which also uses the Java code of
the Android API. This is then compiled into DEX code and run by the DVM, which in turn has
connections to an underlying operating system called Linux that handles the complex and
extremely diverse range of hardware that are the different Android devices.
The manufacturers of the Android devices and of the individual hardware components obviously
know this too, and they write advanced software called drivers that ensure that their hardware
(for example, CPU, GPU, GPS receivers, memory chips, and hardware interfaces) can run on the
underlying Linux operating system.
The DEX code (along with some other resources) is placed in a bundle of files called an
Android application PacKage (APK), and this is what the DVM needs to run our app.
Android
Android is an open source and Linux-based operating system for mobile devices such as
smartphones and tablet computers. Android was developed by the Open Handset Alliance, led by
Google, and other companies.
Android offers a unified approach to application development for mobile devices which means
developers need only develop for Android, and their applications should be able to run on
different devices powered by Android.
Android IDE
Android Studio: Google’s official IDE for Android based on Intellij IDEA.
Eclipse: This open source IDE is the second most popular in the world.
Visual Studio (with Xamarin): Microsoft’s flagship IDE comes in multiple versions, but when
integrated with Xamarin (which Microsoft purchased last year), it enables cross-platform native
development.
IntelliJ IDEA: IntelliJ IDEA is described as a “capable and ergonomic IDE for JVM.”
Komodo: ActiveState’s Komodo humbly proclaims itself “the best IDE for Web and mobile app
development.
Cordova: First developed by a company called Nitobi, Cordova was originally known as
PhoneGap.
PhoneGap: PhoneGap is Adobe’s implementation of the Apache Cordova open source mobile
development framework.
App Inventor: App Inventor aims at helping students and other new developers create their first
Android apps.
AIDE: AIDE allows you to develop Android apps or Web sites from your Android device.
Android Studio
A development environment is a term that refers to having everything you need to develop, set
up, and be ready to go in one place. We need two things to get started.
1. Java code, into DEX code that will run on the DVM on the user’s Android device. To use
Java code, we need some free software called the Java Development Kit (JDK).
2. Android API
This whole suite of requirements is collectively known as the Android Software
Development Kit(SDK). Fortunately, downloading and installing a single application
will give us these things all bundled together. The application is called Android Studio.
Android Studio is an integrated development environment (IDE) that will take care of all the
complexities of compiling our code and linking with the JDK and the Android API. Android
Studio provides more features that enhance our productivity while building Android apps.
Gradle is the build system. You can use it with a lot of plugins. One of these is the Android
Gradle plugin. It is used to provide processes and configurable settings that are specific to
building and testing Android applications.
Note:Eclipse IDE-ADT bundle(instead of gradle plug in.)
API Level is an integer value that uniquely identifies the framework API revision offered
by a version of the Android platform. The Android platform provides a framework API that
applications can use to interact with the underlying Android system. The framework API
consists of: A core set of packages and classes
Codename Version API level/NDK release
Android13 13 API level 33
Android12L 12 API level 32
Android12 12 API level 31
Android11 11 API level 30
Android10 10 API level 29
Pie 9 API level 28
Oreo 8.1.0 API level 27
Oreo 8.0.0 API level 26
Nougat 7.1 API level 25
Nougat 7.0 API level 24
Codename Version API level/NDK release
Marshmallow 6.0 API level 23
Lollipop 5.1 API level 22
Lollipop 5.0 API level 21
KitKat 4.4 - 4.4.4 API level 19
Jelly Bean 4.3.x API level 18
Jelly Bean 4.2.x API level 17
Jelly Bean 4.1.x API level 16
Ice Cream Sandwich 4.0.3 - 4.0.4 API level 15, NDK 8
Ice Cream Sandwich 4.0.1 - 4.0.2 API level 14, NDK 7
Honeycomb 3.2.x API level 13
Honeycomb 3.1 API level 12, NDK 6
Honeycomb 3.0 API level 11
Gingerbread 2.3.3 - 2.3.7 API level 10
Gingerbread 2.3 - 2.3.2 API level 9, NDK 5
Froyo 2.2.x API level 8, NDK 4
Eclair 2.1 API level 7, NDK 3
Eclair 2.0.1 API level 6
Eclair 2.0 API level 5
Donut 1.6 API level 4, NDK 2
Cupcake 1.5 API level 3, NDK 1
(no codename) 1.1 API level 2
(no codename) 1.0 API level 1
Android - Application Components
Application components are the essential building blocks of an Android application. These
components are loosely coupled by the application manifest file AndroidManifest.xml that
describes each component of the application and how they interact.
Sr.No Components & Description
1
Activities
They dictate the UI and handle the user interaction to the smart phone
screen.
2
Services
They handle background processing associated with an application.
3
Broadcast Receivers
They handle communication between Android OS and applications.
4
Content Providers
They handle data and database management issues.
Activities
An activity represents a single screen with a user interface,in-short Activity performs actions on
the screen. For example, an email application might have one activity that shows a list of new
emails, another activity to compose an email, and another activity for reading emails. If an
application has more than one activity, then one of them should be marked as the activity that is
presented when the application is launched.
An activity is implemented as a subclass of Activity class as follows −
public class MainActivity extends Activity {
}
Services
A service is a component that runs in the background to perform long-running operations.
For example, a service might play music in the background while the user is in a different
application, or it might fetch data over the network without blocking user interaction with an
activity.
A service is implemented as a subclass of Service class as follows −
public class MyService extends Service {
}
Broadcast Receivers
Broadcast Receivers simply respond to broadcast messages from other applications or from
the system. For example, applications can also initiate broadcasts to let other applications know
that some data has been downloaded to the device and is available for them to use, so this is
broadcast receiver who will intercept this communication and will initiate appropriate action.
A broadcast receiver is implemented as a subclass of BroadcastReceiver class and each
message is broadcaster as an Intent object.
public class MyReceiver extends BroadcastReceiver {
public void onReceive(context,intent){}
}
Content Providers
A content provider component supplies data from one application to others on request. Such
requests are handled by the methods of the ContentResolver class. The data may be stored in the
file system, the database or somewhere else entirely.
A content provider is implemented as a subclass of ContentProvider class and must implement
a standard set of APIs that enable other applications to perform transactions.
public class MyContentProvider extends ContentProvider {
public void onCreate(){}
}
Additional Components
There are additional components which will be used in the construction of above mentioned
entities, their logic, and wiring between them. These components are −
S.No Components & Description
1 Fragments
Represents a portion of user interface in an Activity.
2 Views
UI elements that are drawn on-screen including buttons, lists forms etc.
3 Layouts
View hierarchies that control screen format and appearance of the views.
4
Intents
Messages wiring components together.
5
Resources
External elements, such as strings, constants and drawable pictures.
6
Manifest
Configuration file for the application.
Anatomy of Android Application or Structure of Android Application
Sr.No. Folder, File & Description
1
Java
This contains the .java source files for your project. By default, it includes
an MainActivity.java source file having an activity class that runs when your
app is launched using the app icon.
2
res/drawable-hdpi
This is a directory for drawable objects that are designed for high-density
screens. A drawable resource is a general concept for a graphic that can be
drawn to the screen and which you can retrieve with APIs such as
getDrawable(int) or apply to another XML resource with attributes such as
android:drawable and android:icon.
Eg. Bitmap file
A bitmap file is a .png, .webp, .jpg, or .gif file. Android creates a Drawable
resource for any of these files when you save them in the res/drawable/
directory.
3
res/layout
This is a directory for files that define your app's user interface.
4
res/values
This is a directory for other various XML files that contain a collection of
resources, such as strings and colours definitions.
5
AndroidManifest.xml
This is the manifest file which describes the fundamental characteristics of
the app and defines each of its components.
6
Build.gradle
This is an auto generated file which contains compileSdkVersion,
buildToolsVersion, applicationId, minSdkVersion, targetSdkVersion,
versionCode and versionName
The Main Activity File
The main activity code is a Java file MainActivity.java. This is the actual application file which
ultimately gets converted to a Dalvik executable and runs your application. Following is the
default code generated by the application wizard for Hello World! application −
package com.example.helloworld;
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);
}
}
Here, R.layout.activity_main refers to the activity_main.xml file located in the res/layout folder.
The onCreate() method is one of many methods that are figured when an activity is loaded.
The Manifest File
Whatever component you develop as a part of your application, you must declare all its
components in a manifest.xml which resides at the root of the application project directory. This
file works as an interface between Android OS and your application, so if you do not declare
your component in this file, then it will not be considered by the OS. For example, a default
manifest file will look like as following file −
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.tutorialspoint7.myapplication">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
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>
Here <application>...</application> tags enclosed the components related to the
application. Attribute android:icon will point to the application icon available
under res/drawable-hdpi. The application uses the image named ic_launcher.png located in the
drawable folders
The <activity> tag is used to specify an activity and android:name attribute specifies the fully
qualified class name of the Activity subclass and the android:label attributes specifies a string to
use as the label for the activity. You can specify multiple activities using <activity> tags.
The action for the intent filter is named android.intent.action.MAIN to indicate that this activity
serves as the entry point for the application. The category for the intent-filter is
named android.intent.category.LAUNCHER to indicate that the application can be launched
from the device's launcher icon.
The @string refers to the strings.xml file explained below. Hence, @string/app_name refers to
the app_name string defined in the strings.xml file, which is "HelloWorld". Similar way, other
strings get populated in the application.
Following is the list of tags which you will use in your manifest file to specify different Android
application components −
 <activity>elements for activities
 <service> elements for services
 <receiver> elements for broadcast receivers
 <provider> elements for content providers
The Strings File
The strings.xml file is located in the res/values folder and it contains all the text that your
application uses. For example, the names of buttons, labels, default text, and similar types of
strings go into this file. This file is responsible for their textual content. For example, a default
strings file will look like as following file −
<resources>
<string name="app_name">HelloWorld</string>
<string name="hello_world">Hello world!</string>
<string name="menu_settings">Settings</string>
<string name="title_activity_main">MainActivity</string>
</resources>
The Layout File
The activity_main.xml is a layout file available in res/layout directory, that is referenced by
your application when building its interface. You will modify this file very frequently to change
the layout of your application. For your "Hello World!" application, this file will have following
content related to default layout −
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:padding="@dimen/padding_medium"
android:text="@string/hello_world"
tools:context=".MainActivity" />
</RelativeLayout>
This is an example of simple RelativeLayout . The TextView is an Android control used to build
the GUI and it have various attributes like android:layout_width, android:layout_height etc
which are being used to set its width and height etc.. The @string refers to the strings.xml file
located in the res/values folder. Hence, @string/hello_world refers to the hello string defined in
the strings.xml file, which is "Hello World!".
Running the Application
To run the app from Android studio, open one of your project's activity files and click Run
icon from the tool bar. Android studio installs the app on your AVD and starts it and if
everything is fine with your set-up and application, it will display following Emulator window −
Android_Studio_Structure.docx

More Related Content

Android_Studio_Structure.docx

  • 1. How Java is used in Android Application Development Java is the technology of choice for building applications using managed code that can execute on mobile devices. Android is an open source software platform and Linux-based operating system for mobile devices. The Android platform allows developers to write managed code using Java to manage and control the Android device. Android applications can be developed by using the Java programming language and the Android SDK. So, familiarity with the basics of the Java programming language is a prerequisite for programming on the Android platform. Here we discuss where Java fits in mobile application development and how we can use Java and Android SDK to write applications that can work on Android devices. The Choice of Java What made Java be the technology of choice for mobile development for the Android platform? The Java Programming Language emerged in the mid-1990s; it was created by James Gosling of Sun Microsystems. Incidentally, Sun Microsystems was since bought by Oracle. Java has been widely popular the world over, primarily because of a vast array of features it provides. Java’s promise of “Write once and run anywhere”(WORA) was one of the major factors for the success of Java over the past few decades. Java even made inroads into embedded processors technology as well; the Java Mobile Edition(JME) was built for creating applications that can run on mobile devices. All these, added to Java’s meteoric rise, were the prime factors that attributed to the decision of adopting Java as the primary development language for building applications that run on Android. Java programs are secure because they run within a sandbox environment[sandbox environment is an isolated virtual machine in which potentially unsafe software code can execute without affecting network resources or local applications. Cybersecurity researchers use sandboxes to run suspicious code from unknown attachments and URLs and observe its behavior]. Programs written in Java are compiled into intermediate code known as bytecode. This bytecode is then executed inside the context of the Java Virtual Machine. Using Java for Building Mobile Applications The mobile edition of Java is called Java ME. Java ME is based on Java SE and is supported by most smartphones and tablets. The Java Platform Micro Edition (Java ME) provides a flexible, secure environment for building and executing applications that are targeted at embedded and mobile devices. The applications that are built using Java ME are portable, secure, and can take advantage of the native capabilities of the device. Java ME addresses the constraints that are involved in building applications that are targeted at mobile devices. In essence, Java ME addresses the challenge of executing applications on devices that are low on available memory, display, and power.
  • 2. There are various ways to build applications for Android devices, but the recommended approach is to leverage the Java programming language and the Android SDK The Dalvik Virtual Machine (Dalvik VM) The Android platform leverages the Dalvik Virtual machine (Dalvik VM) for memory, security, device, and process management. Although the internal intricacies of how the Dalvik Virtual Machine works is not that important to an average developer, you can think of the Dalvik VM as a box that provides the necessary environment for you to execute an Android application sans the need of having to worry about the target device. To get started using Java for Android, you should first download and install Android Studio. You then may want to take advantage of the SDK Manager to download and install the latest SDK tools and platforms. The purpose of the DVM is to hide the complexity and diversity of hardware and software that Android runs on, but, at the same time, exposing all its useful features. This exposing of features works in two ways: 1. First, the DVM itself must have access to the hardware, which it does. 2. Second, this access must be programmer friendly and easy to use, and it is because of the Android Application Programming Interface or API. Summary Programs that are targeted at the Android platform are written in Java and executed by the Dalvik Virtual Machine (DVM). The Android API The Android API is code that makes it easy to do exceptional things. A simple analogy could be drawn with a machine, perhaps a car. When you press on the accelerator, a whole bunch of things happen under the hood. We don’t need to understand about combustion or fuel pumps because some smart engineer has made an interface for us—in this case a mechanical interface— the accelerator pedal. The following line of Java code serves as a good example of how the Android API helps us: locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER) Once you learn that this single line of code searches for available satellites in space, then communicates with them in their orbits around the Earth, and then retrieves your precise latitude and longitude on the surface of the planet, it becomes easy to begin to glimpse the power and depth of the Android API in conjunction with the DVM.
  • 3. For sure, that code does look a little challenging, even mind boggling, but imagine trying to talk to a satellite some other way! The Android API has a whole bunch of Java code that has already been written for us to use as we like. Java is object-oriented Java is a programming language that has been around a lot longer than Android. It is an object- oriented language. This means it uses the concept of reusable programming objects. If this sounds like technical jargon, another analogy will help. Java enables us and others (like the Android development team) to write Java code that can be structured based on real-world things, and here is the important part: it can be reused. Features: Robust, Secure, Dynamic, flexible, Platform Independent etc., Run that by me again – What exactly is Android? To get things done on Android, we write Java code of our own, which also uses the Java code of the Android API. This is then compiled into DEX code and run by the DVM, which in turn has connections to an underlying operating system called Linux that handles the complex and extremely diverse range of hardware that are the different Android devices. The manufacturers of the Android devices and of the individual hardware components obviously know this too, and they write advanced software called drivers that ensure that their hardware (for example, CPU, GPU, GPS receivers, memory chips, and hardware interfaces) can run on the underlying Linux operating system. The DEX code (along with some other resources) is placed in a bundle of files called an Android application PacKage (APK), and this is what the DVM needs to run our app. Android Android is an open source and Linux-based operating system for mobile devices such as smartphones and tablet computers. Android was developed by the Open Handset Alliance, led by Google, and other companies. Android offers a unified approach to application development for mobile devices which means developers need only develop for Android, and their applications should be able to run on different devices powered by Android.
  • 4. Android IDE Android Studio: Google’s official IDE for Android based on Intellij IDEA. Eclipse: This open source IDE is the second most popular in the world. Visual Studio (with Xamarin): Microsoft’s flagship IDE comes in multiple versions, but when integrated with Xamarin (which Microsoft purchased last year), it enables cross-platform native development. IntelliJ IDEA: IntelliJ IDEA is described as a “capable and ergonomic IDE for JVM.” Komodo: ActiveState’s Komodo humbly proclaims itself “the best IDE for Web and mobile app development. Cordova: First developed by a company called Nitobi, Cordova was originally known as PhoneGap. PhoneGap: PhoneGap is Adobe’s implementation of the Apache Cordova open source mobile development framework. App Inventor: App Inventor aims at helping students and other new developers create their first Android apps.
  • 5. AIDE: AIDE allows you to develop Android apps or Web sites from your Android device. Android Studio A development environment is a term that refers to having everything you need to develop, set up, and be ready to go in one place. We need two things to get started. 1. Java code, into DEX code that will run on the DVM on the user’s Android device. To use Java code, we need some free software called the Java Development Kit (JDK). 2. Android API This whole suite of requirements is collectively known as the Android Software Development Kit(SDK). Fortunately, downloading and installing a single application will give us these things all bundled together. The application is called Android Studio. Android Studio is an integrated development environment (IDE) that will take care of all the complexities of compiling our code and linking with the JDK and the Android API. Android Studio provides more features that enhance our productivity while building Android apps. Gradle is the build system. You can use it with a lot of plugins. One of these is the Android Gradle plugin. It is used to provide processes and configurable settings that are specific to building and testing Android applications. Note:Eclipse IDE-ADT bundle(instead of gradle plug in.) API Level is an integer value that uniquely identifies the framework API revision offered by a version of the Android platform. The Android platform provides a framework API that applications can use to interact with the underlying Android system. The framework API consists of: A core set of packages and classes Codename Version API level/NDK release Android13 13 API level 33 Android12L 12 API level 32 Android12 12 API level 31 Android11 11 API level 30 Android10 10 API level 29 Pie 9 API level 28 Oreo 8.1.0 API level 27 Oreo 8.0.0 API level 26 Nougat 7.1 API level 25 Nougat 7.0 API level 24
  • 6. Codename Version API level/NDK release Marshmallow 6.0 API level 23 Lollipop 5.1 API level 22 Lollipop 5.0 API level 21 KitKat 4.4 - 4.4.4 API level 19 Jelly Bean 4.3.x API level 18 Jelly Bean 4.2.x API level 17 Jelly Bean 4.1.x API level 16 Ice Cream Sandwich 4.0.3 - 4.0.4 API level 15, NDK 8 Ice Cream Sandwich 4.0.1 - 4.0.2 API level 14, NDK 7 Honeycomb 3.2.x API level 13 Honeycomb 3.1 API level 12, NDK 6 Honeycomb 3.0 API level 11 Gingerbread 2.3.3 - 2.3.7 API level 10 Gingerbread 2.3 - 2.3.2 API level 9, NDK 5 Froyo 2.2.x API level 8, NDK 4 Eclair 2.1 API level 7, NDK 3 Eclair 2.0.1 API level 6 Eclair 2.0 API level 5 Donut 1.6 API level 4, NDK 2 Cupcake 1.5 API level 3, NDK 1 (no codename) 1.1 API level 2 (no codename) 1.0 API level 1
  • 7. Android - Application Components Application components are the essential building blocks of an Android application. These components are loosely coupled by the application manifest file AndroidManifest.xml that describes each component of the application and how they interact. Sr.No Components & Description 1 Activities They dictate the UI and handle the user interaction to the smart phone screen. 2 Services They handle background processing associated with an application. 3 Broadcast Receivers They handle communication between Android OS and applications. 4 Content Providers They handle data and database management issues. Activities An activity represents a single screen with a user interface,in-short Activity performs actions on the screen. For example, an email application might have one activity that shows a list of new emails, another activity to compose an email, and another activity for reading emails. If an application has more than one activity, then one of them should be marked as the activity that is presented when the application is launched. An activity is implemented as a subclass of Activity class as follows − public class MainActivity extends Activity { }
  • 8. Services A service is a component that runs in the background to perform long-running operations. For example, a service might play music in the background while the user is in a different application, or it might fetch data over the network without blocking user interaction with an activity. A service is implemented as a subclass of Service class as follows − public class MyService extends Service { } Broadcast Receivers Broadcast Receivers simply respond to broadcast messages from other applications or from the system. For example, applications can also initiate broadcasts to let other applications know that some data has been downloaded to the device and is available for them to use, so this is broadcast receiver who will intercept this communication and will initiate appropriate action. A broadcast receiver is implemented as a subclass of BroadcastReceiver class and each message is broadcaster as an Intent object. public class MyReceiver extends BroadcastReceiver { public void onReceive(context,intent){} } Content Providers A content provider component supplies data from one application to others on request. Such requests are handled by the methods of the ContentResolver class. The data may be stored in the file system, the database or somewhere else entirely. A content provider is implemented as a subclass of ContentProvider class and must implement a standard set of APIs that enable other applications to perform transactions. public class MyContentProvider extends ContentProvider { public void onCreate(){} }
  • 9. Additional Components There are additional components which will be used in the construction of above mentioned entities, their logic, and wiring between them. These components are − S.No Components & Description 1 Fragments Represents a portion of user interface in an Activity. 2 Views UI elements that are drawn on-screen including buttons, lists forms etc. 3 Layouts View hierarchies that control screen format and appearance of the views. 4 Intents Messages wiring components together. 5 Resources External elements, such as strings, constants and drawable pictures. 6 Manifest Configuration file for the application.
  • 10. Anatomy of Android Application or Structure of Android Application Sr.No. Folder, File & Description 1 Java This contains the .java source files for your project. By default, it includes an MainActivity.java source file having an activity class that runs when your app is launched using the app icon. 2 res/drawable-hdpi This is a directory for drawable objects that are designed for high-density screens. A drawable resource is a general concept for a graphic that can be drawn to the screen and which you can retrieve with APIs such as getDrawable(int) or apply to another XML resource with attributes such as android:drawable and android:icon. Eg. Bitmap file A bitmap file is a .png, .webp, .jpg, or .gif file. Android creates a Drawable resource for any of these files when you save them in the res/drawable/ directory. 3 res/layout This is a directory for files that define your app's user interface. 4 res/values This is a directory for other various XML files that contain a collection of resources, such as strings and colours definitions. 5 AndroidManifest.xml This is the manifest file which describes the fundamental characteristics of the app and defines each of its components. 6 Build.gradle This is an auto generated file which contains compileSdkVersion, buildToolsVersion, applicationId, minSdkVersion, targetSdkVersion, versionCode and versionName
  • 11. The Main Activity File The main activity code is a Java file MainActivity.java. This is the actual application file which ultimately gets converted to a Dalvik executable and runs your application. Following is the default code generated by the application wizard for Hello World! application − package com.example.helloworld; 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); } } Here, R.layout.activity_main refers to the activity_main.xml file located in the res/layout folder. The onCreate() method is one of many methods that are figured when an activity is loaded. The Manifest File Whatever component you develop as a part of your application, you must declare all its components in a manifest.xml which resides at the root of the application project directory. This file works as an interface between Android OS and your application, so if you do not declare your component in this file, then it will not be considered by the OS. For example, a default manifest file will look like as following file − <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.tutorialspoint7.myapplication"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" 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>
  • 12. </application> </manifest> Here <application>...</application> tags enclosed the components related to the application. Attribute android:icon will point to the application icon available under res/drawable-hdpi. The application uses the image named ic_launcher.png located in the drawable folders The <activity> tag is used to specify an activity and android:name attribute specifies the fully qualified class name of the Activity subclass and the android:label attributes specifies a string to use as the label for the activity. You can specify multiple activities using <activity> tags. The action for the intent filter is named android.intent.action.MAIN to indicate that this activity serves as the entry point for the application. The category for the intent-filter is named android.intent.category.LAUNCHER to indicate that the application can be launched from the device's launcher icon. The @string refers to the strings.xml file explained below. Hence, @string/app_name refers to the app_name string defined in the strings.xml file, which is "HelloWorld". Similar way, other strings get populated in the application. Following is the list of tags which you will use in your manifest file to specify different Android application components −  <activity>elements for activities  <service> elements for services  <receiver> elements for broadcast receivers  <provider> elements for content providers The Strings File The strings.xml file is located in the res/values folder and it contains all the text that your application uses. For example, the names of buttons, labels, default text, and similar types of strings go into this file. This file is responsible for their textual content. For example, a default strings file will look like as following file − <resources> <string name="app_name">HelloWorld</string> <string name="hello_world">Hello world!</string> <string name="menu_settings">Settings</string> <string name="title_activity_main">MainActivity</string> </resources> The Layout File The activity_main.xml is a layout file available in res/layout directory, that is referenced by your application when building its interface. You will modify this file very frequently to change the layout of your application. For your "Hello World!" application, this file will have following content related to default layout −
  • 13. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:padding="@dimen/padding_medium" android:text="@string/hello_world" tools:context=".MainActivity" /> </RelativeLayout> This is an example of simple RelativeLayout . The TextView is an Android control used to build the GUI and it have various attributes like android:layout_width, android:layout_height etc which are being used to set its width and height etc.. The @string refers to the strings.xml file located in the res/values folder. Hence, @string/hello_world refers to the hello string defined in the strings.xml file, which is "Hello World!". Running the Application To run the app from Android studio, open one of your project's activity files and click Run icon from the tool bar. Android studio installs the app on your AVD and starts it and if everything is fine with your set-up and application, it will display following Emulator window −