Android Stack
Android operating system consists of applications, run-time environment, middleware, services and libraries arranged in the form of tightly integrated and carefully tuned layers in a stack. Each layer further contains several programs to provide the optimal application development and execution environment.
A stack refers to a container of objects, which you can add and remove according to the last-in first-out (LIFO) principle. As per LIFO, you can add and remove the objects from the stack only at the top. For example, consider a book shelf in which you can add a new book at the top and remove a book only from the top.
Android is Linux based software stack, which is created for wide range of devices and form factors. The Android stack consists of the following layers :
System Apps - The top layer of Android Stack is of System Apps or simply Applications. These are a set of core applications like calendar, contacts, SMS messaging and more. These applications have dual functionality, they work as utility applications for the user and also provide key capabilities to developers who can access these applications for their own applications. All these applications use Native Libraries and Android Runtime to execute their processes.
Java API Framework - This layer is also known as Applications Framework. Android applications interact directly with this layer. It basically contains all the features of the Android operating system, made accessible through APIs written in Java. APIs are the basic building blocks required for developing applications.
The Important blocks of Java API Framework are :
- View System - This is a set of views like lists, text boxes, grids, buttons and so on. These are used to create user interfaces of applications.
- Content Providers - This block enables applications to share data with other applications.
- Resource Manager - This block manages the resources used in the applications. It allows applications to access non-coded resources like color strings, strings and user interface layouts.
- Notification Manager - This block enables applications to sent notifications and alerts to the user.
- Activity Manager - This block manages the lifecycle of the applications.
- Package Manager – This block has a system using which applications can find out about other applications currently installed on a device.
- Telephony Manager – This block gives information to an application about the available telephony services on a device.
- Location Manager – This block gives access to location services, thus allowing an application to receive information about location change of a device.
Native C / C++ Libraries
Many core components and services of the Android system such as Hardware Extraction Layer and Android Runtime are built from native code, which require native C and C++ libraries. Android platform also supports and provides Java Framework APIs to make the functionality of these native libraries available to applications.
Some of the open - source libraries in the system are :
- Open GL|ES - Supports 2D and 3D Library
- Media Framework - Supports recordings and playbacks of audios and videos and also suupports picture formats.
- Free Type - Supports font rendering
- WebKit - Supports browser engine
- libc - These are system C libraries
- SQLite - Provides for sharing and storing of application data
- Open SSL - Provide internet security
- Android Libraries - These include Java - based libraries, which are essential for Android development.
Some of the core Android libraries are as follows :
- android.app − This library provides access to the application model and is the base of all Android applications.
- android.content − This library facilitates content access, messaging and publishing between applications. android.database − This Library is used to access data published by content providers and includes management classes of SQLite database.
- android.opengl − This facilitates Java interface to the OpenGL ES 2D and 3D graphics rendering API.
- android.os − This library provides support to applications to access the standard Android operating system services including system services, messages and inter-process communication.
- android.text − This library provides for rendering and manipulation of text on a device display.
- android.view − This library provides the fundamental building blocks of application user interfaces.
- android.widget − This library is an extensive collection of pre-built user interface components such as labels, buttons, layout managers, list views, radio buttons etc.
- android.webkit − This library provides a set of classes which allow web-browsing capabilities to be built into applications.
Android Runtime - In devices with Android 5.0 or higher version, all applications have their own specific process with own instance of Android Runtime ( ART ). Android Runtime can run on multiple virtual machines with a bytecode specifically designed for Android. It is also optimized for minimal memory footprint. In devices which have lower versions of Android the runtime process is handled by Dalvik Virtual Machine (VM) and core libraries. It also has a set of core runtime libraries that provide most of the functional features of Java.
Hardware Extraction Layer - This layer provides standard interfaces that expose the hardware capabilities of a device to the Java API framework. This layer comprises of multiple library modules, each module is capable of implementing an interface for a specific hardware component, such as bluetooth module, camera module and many more. In execution when an API calls to access the hardware of the device, the Android system immediately loads the library module for that specific hardware component.
Linux Kernel - Linux Kernel is the foundation layer of Android platform. This layer does not directly interact with the users or developers, but is the backbone of the whole setup. It contains all the essential hardware drivers. It assists in providing the following facilities :
- Hardware Abstraction
- Memory Management Programs
- Security Settings
- Power Management Software
- Support for Shared Libraries
- Network Stack
- Other Hardware Drivers
Android Application Structure
All Android applications installed as application package files, known as APK files. These files are container files, which contain the application code, application manifest file and resources.
The application package files ( APK ) include AndroidManifest.xml file, which contains and declares the applications package name, version of the components and other metadata.
- AndroidManifest.xml - This is the main manifest file in binary XML format.
- classes.dex - This contains the application code compiled in the dex format.
- resources.arsc - This folder contains the application resources precompiled in binary XML format.
- res/ - This folder contains resources which have not been complied into resources.arsc.
- assets/ - This is an optional folder which contains application assets.
- lib/ - This folder contains the native code libraries.
- META-INF/ - This folder contains the MANIFEST.MF file, which contains meta data of the contents of JAR.
Android Application Components
All these components are contained in the AndroidManifest.xml file, which is located in the root directory, in addition to the information of your package. This file provides necessary permissions to the application and declares the Android Application Programming Interface (API) for the application.
Let's discuss the components of Android application structure.
Activity and Fragment
An activity can be defined as an interactive user interface of an application on a single screen. Almost all Android activities can interact with the end user. It also hides the program logic from you. For example, in an e-commerce Website, exploring the items can be one activity and filtering the can be another.
You can create an activity using the in-built Activity class or Android Studio templates. You just need to define the code in the AndroidManifest.xml file as shown in the code snippet given below:
Code Snippet 2.1
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
You can use the following code to implement an activity as a subclass of the Activity class:
public class MainActivity extends Activity {
}
The order of methods used in an Android application's activity lifecycle, the methods used in the activity perform the following functions :
- onCreate () - This method is called when the activity is first created, it is called only once in the lifecycle of an activity.
- onStart () - This method is called when the activity goes into started state. This callback makes the activity visible to the user.
- onResume () - When the activity is in the foreground and interacts with the user, it is said to be in resumed state. The application will stay in this state till the time focus is not taken away from the activity, like an incoming phone call. Once the user returns to the activity, the system will call onResume method.
- onPause () - The system will call this method when it receives an indication that the user is leaving the application. It does not always mean that the application is being stopped or destroyed, it may indicate that the activity is not in foreground.
- onStop () - This system calls this method when the activity goes into stopped state and is no longer visible to the user.
- onDestroy () - The system will receive the onDestroy event before the activity is finished. It cleans up all the resources used by the activity.
Fragments are an extension to the Activity class and were introduced with Android 3.0 to overcome the limitation of showing single activity at a time on the screen. A fragment (also known as sub-activity) enables you to display multiple UI segments on a single screen. Fragments allow easy application navigation and communication across different sections of the application. In simple words, an activity can have one or more fragment.
You can create fragments by extending the Fragment class and can insert a fragment into your activity layout by declaring the fragment in the activity's layout file, as a <fragment> element.
Fragments Lifecycle
A Fragment’s life cycle resembles the life cycle of an Activity with a few additional callback methods. The onAttach() and onDetach() methods are called when a fragment is added or removed from an Activity. On the other hand, the onCreateView() and onDestroyView() methods are called when you create or remove an instance of the fragment.
Services
A service is an application component that executes in the background and is not visible to users for any kind of interaction. The execution of the service continues even when the application is destroyed. The examples include checking for new data and handling network interactions.
The services have high priority than Activities and Fragments. A service can be a started service as well as a bound service. A started service is a service an application component, such as Activity or Fragment starts itself by using the startService() method. On the other hand, a bound service is a service when an application component binds to it by using the bindService() method.
A bound service supports the client-server architecture in a sense that it allows components to bind with the service and execute interprocess communication.
You need to declare a service in the AndroidManifest.xml file and implement the Service class or its subclass.
Use the following code snippet to declare and implement a service:
Code Snippet 2.2
<service
android:name="DemoService"
android:icon="@drawable/icon"
android:label="@string/service_name"
>
</service>
javapublic class MyService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return Service.START_NOT_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
In this code, START_NOT_STICKY is a service restart behavior.
Content Providers
This component uses the methods of the ContentResolver class to execute requests and supply data from one application to another. In simple words, Content Provider enables transfer of data across applications. Content Provides encapsulates data and maintains security during data transfer.
Content Providers get data from the database and shares it as per the request received. You can use in-built Content Providers or create your own custom Content Providers.
Traditionally Android uses SQLite database for content providers, but Firebase Realtime Database is the new choice of developers. Firebase is a cloud based database which allows data to by synced across all platforms in realtime and is also available offline.
You can implement a content provider as a subclass of the ContentProvider class. In addition, you must also implement standard APIs to enable other applications to perform transactions.
Use the following code snippet to implement the Content Provider class:
Code Snippet 2.3
public class DemoApp extends ContentProvider{
}
The Android framework includes content providers that manage data, such as audio, video, images, and calendar events. Most of these content providers are listed in the android.provider package.
You can also query a content provider. Use the following query string to query a content provider:
<prefix>://<authority>/<data_type>/<id>
In this string, it is always recommended to set the prefix is always as content://. The authority part defines the name of the content provider, such as contacts and browsers. The data type part identifies the type of data that this provider provides and the last part of the string, id defines the record requested.
Broadcasting
Android applications enable broadcasting by sending or receiving messages from the Android system or other applications. The messages are broadcasted when an event occurs. Consider a scenario where you receive broadcasts for system restart, battery charging, or device shutdown.
Android applications have the capability to broadcast certain standard messages as well as custom messages. However, the applications need to subscribe to receive these broadcasts.
Use the following code snippet to create a broadcast receiver:
Code Snippet 2.4
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Intent Detected.", Toast.LENGTH_LONG).show();
}
}
You can register a broadcasting receiver either statically via the AndroidManifest.xml file or dynamically via the Context.registerReceiver() method. You need to extend the BroadcastReceiver class regardless of the registration method.
Use the following code snippet to register the broadcast receiver:
Code Snippet 2.5
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<receiver android:name="MyReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED">
</action>
</intent-filter>
</receiver>
</application>
When the event for which the broadcast receiver has registered occurs, the system calls the onReceive() method of the receiver.
Java for Android
You can use Java as a programming language to develop Android applications. Java has been used for programming applications in Android. To develop Android applications using Java, you need to use an Integrated Development Environment (IDE), such as Eclipse.
Using Core Java
Java, a general purpose programming language incorporates features of many programming languages (for example, C and C++). Java allows you to write platform independent code, which means that your code can run anywhere. When you compile a Java program, Java Virtual Machine (JVM) compiles and interprets the code.
Java allows you to create Standalone applications, Web applications, Enterprise applications, and Mobile applications.
A basic Java program consists of an object, a class, methods, and instance variables. An object is an entity that has its own state and behavior and a class is a definition of an object. A class can have several methods in it. Each method defines the logic to manipulate the data. At the last, an object can have any number of variables that when assigned values create an object’s state. The names that you use in your program for objects, classes, methods, and instance variables are called identifiers.
Once defined, you can modify the objects, classes, methods, and instance variables depending on the modifier type. There are two types of modifiers, access modifiers and non-access modifiers. Access modifiers are default, public, protected, and private and non-access modifiers are final, abstract, and strictfp.
The following code snippet shows the simplest Java program:
Code Snippet 2.6
public class JavaProgram {
public static void main(String []args) {
System.out.println("Sample Program");
}
}
This code has the JavaProgram class, and main method.
Intent, Toast, Resource, View
Android together with Java provides objects and classes that you can use to develop enriched Android applications. The details of these objects and classes are as follows:
Intent: An Intent is an asynchronous messaging object that allows you to connect an Android application component with other components of the same application or other Android applications or request an action from other components. You can use the Intent object to start the service, launch an activity, display a Web page, display a list of contacts, broadcast a message, and dial a phone call. Intents can be implicit as well as explicit. Explicit intents specify the application that satisfies the intent by supplying either the target app's package name or a fully-qualified component class name. Using intent objects to connect components of same application are explicit intents. On the other hand, implicit intents declare a general action to perform. Using intent objects to connect components of an application with other applications are implicit intents. You can use the Intent object with the startActivity method to launch an Activity, with the broadcastIntent method to send it to the BroadcastReceiver components, and the startService (Intent) or bindService (Intent, ServiceConnection, int) methods to communicate with a background Service.
Toast: A Toast is a class, which is used to display a notification for a short period of time. You can continue interacting with the application even if the notification disappears. The android.widget.Toast class is a subclass of the java.lang.Object class. For example, when you make online payment and click the Pay button, the application displays the Making Payment notification and hides it when process completes. The Toast class contains the public static Toast makeText(Context context, CharSequence text, int duration), public void show(), and public void setMargin (float horizontalMargin, float verticalMargin) methods.
Resource: The Resource class helps you access resources of an application, such as bitmaps, colors, layout definitions, user interface strings, and animation instructions. You can use the following code to refer to a resource:
@package_name:resource_type/resource_name
In this code, the package_name is the name of the package where resource is located, resource_type is the subclass for the resource type, and resource_name is the resource filename without the extension.
View: A view is a screen element that is visible to users on an application's UI. The Android View class is a base class that provides interactive UI components, such as buttons, checkboxes, scrollable text, and text input fields. To define a view, it is mandatory to specify location coordinates and dimensions in device-independent pixel (dp).
Using Classes and Interfaces
An interface is not a class. Writing an interface is similar to writing a class, but they are two different concepts. A class contains objects and describes the attributes and behaviors of the objects whereas an interface defines behaviors that a class implements.
In simple words, an interface can be defined as a protocol that defines the scope of classes.
The following are the significant Android classes and interfaces:
- android.app.Activity: To create a content in your Android application.
- android.view.View: To add a UI component.
- android.view.View.OnClickListener: To let the application respond when you tap at the screen.
- android.view.MotionEvent: To let the application respond when you drag, zoom, or pinch on the screen.
- android.view.animation.Animation: To move or rotate items on the screen.
- java.text.NumberFormat: To make numbers look good on the screen.
- java.lang.String: To perform tasks on strings, such as find characters, find substrings, replace substrings, change casing etc.
- java.lang.Math: To add mathematical capabilities, such as pi, e, logarithms, and square roots.
Using Polymorphism
Polymorphism refers to an ability of assigning different meaning to a class, object, or method. In simple words, polymorphism is the property by which a message is send to several objects of different classes but the objects behave differently. Polymorphism can be achieved at the time compilation or execution of application.
You can access a polymorphic object via a reference variable. The important thing to note is once you declare a reference variable, you cannot change its type. However, you can reassign a reference variable to other objects only if it is not declared final.
XML for UI Interface
As mentioned at the beginning of this session, all the required components of an Android application are defined in an xml file. When you compile this file, each element is compiled into equivalent Android Graphical User Interface (GUI) class.
Before you define your UI components in the XML file, you need to understand the required layout of the application. A layout defines the overall UI structure of the application. All the elements of the layout lie under either View or ViewGroup objects. The View object defines what you can see, such as a widget on an Android device whereas ViewGroup acts as a container or layout for views. You cannot view a ViewGroup.
Relationship between layouts, views, and view groups.
The layout that you define for your application can be any of the following types:
Linear - A layout that lets you arrange text in a single column or row horizontally or vertically. A linear layout has two types of orientation:
- Vertical
- Horizontal
Use the following code snippet to define linear layout with vertical orientation, in this example we are creating two buttons with vertical orientation :
Code Snippet 2.7 :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"> <!-- Vertical Orientation set -->
<!-- Child Views(In this case 2 Button) are here -->
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button1"
android:id="@+id/button"
android:background="#358a32" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button2"
android:id="@+id/button2"
android:background="#0058b6" />
</LinearLayout>
Use the following code snippet to define linear layout with horizontal orientation, in this example we are creating two buttons with horizontal orientation :
Code Snippet 2.8 :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"> <!-- Horizontal Orientation set -->
<!-- Child Views(In this case 2 Button) are here -->
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button1"
android:id="@+id/button"
android:background="#358a32" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button2"
android:id="@+id/button2"
android:background="#0058b6" />
</LinearLayout>
Absolute: A layout that lets you specify the exact location ( X and Y coordinates ) of its children views. Use the following syntax code to define absolute layout:
Code Snippet 2.9 :
Android Absolute Layout Syntax Code:
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<!-- add child view’s here -->
</AbsoluteLayout>
Table: A layout that lets you group views into rows and columns. The containers of Table Layout do not display the outside borderline of their rows, columns or cells.
Frame: A layout that lets you add a placeholder to display a single view. This the simplest of all the layouts and is specially designed to block an area on the screen
Relative: A layout that lets you specify the position of children views relative to each other.
Building Basic Application
You need to perform the following steps to develop your first Android application:
- Installing required software
- Creating the application
- Creating a virtual device
- Running the application
- Installing Required Software
Firstly, you need to install Java Development Kit (JDK) 7 or higher version and then install Android Studio. Android Studio is Google's Integrated Development Environment (IDE) for creating Android applications. Android Studio provides an advanced code editor, a set of templates, and tools for development, debugging, testing, and performance.
No comments:
Post a Comment