Mobile Application Development New
Mobile Application Development New
Department of Computer
Science
E -NOTES
Notes Prepared by
S. Parsuvanathan M.Sc., M.Phil,
Assr. Professor,
Department of Computer Science.
3. Accessibility
While a native app works as a standalone entity, the problem is that the user has to keep downloading
updates. A web app, on the other hand, updates itself without the need for user intervention. However, it
necessarily needs to be accessed via a mobile device‘s browser.
4. Efficiency
Native apps are more expensive to develop. However, they are faster and more efficient, as they
work in tandem with the mobile device they are developed for. Also, they are assured of quality, as users can
access them only via app stores online.
4. Symbian OS (Nokia)
Symbian is a mobile operating system (OS) targeted at mobile phones that offers a high-level of
integration with communication and personal information management (PIM) functionality. Symbian OS
combines middleware with wireless communications through an integrated mailbox and the integration of
Java and PIM functionality (agenda and contacts). Nokia has made the Symbian platform available under an
Own Devices.
5. webOS (Palm/HP)
WebOS is a mobile operating system that runs on the Linux kernel. WebOS was initially developed
by Palm as the successor to its Palm OS mobile operating system. HP uses webOS in a number of devices
including several smartphones and HP TouchPads. HP has pushed its webOS into the enterprise mobile
market by focusing on improving security features and management with the release of webOS 3.x.
ANDROID
Android is an operating system and programming platform developed by Google for smartphones
and other mobile devices (such as tablets). It can run on many different devices from many different
manufacturers. Android includes a software development kit for writing original code and assembling
software modules to create apps for Android users. It also provides a marketplace to distribute apps.
Features of Android
Apps are developed for a variety of reasons: addressing business requirements, building new
services, creating new businesses, and providing games and other types of content for users. Developers
choose to develop for Android in order to reach the majority of mobile device users.
Most popular platform for mobile apps: Android powers hundreds of millions of mobile devices
in more than 190 countries around the world. It has the largest installed base of any mobile platform
and is still growing fast.
Best experience for app users: Android provides a touch-screen user interface (UI) for interacting
with apps. Android's user interface is mainly based on direct manipulation, using touch gestures such
as swiping, tapping and pinching to manipulate on-screen objects.
Easy to develop apps: Use the Android software development kit (SDK) to develop apps that take
advantage of the Android operating system and UI. The SDK includes a comprehensive set of
development tools including a debugger, software libraries of prewritten code, a device emulator,
documentation, sample code, and tutorials.
Many distribution options: You can distribute your Android app in many different ways: email,
website or an app marketplace such as Google Play. Android users download billions of apps and
games from the Google Play store
Attractive UI - Provides beautiful Screen and Perceptive UI.
Connectivity - CDMA,GSM/EDGE, UMTS,IDEN, EV-DO, Wi-Fi, Bluetooth, LTE and NFC.
Storage - A light weight relational database SQLite.
History of Android
The history and versions of android are interesting to know. The code names of android ranges from
A to P currently. Let's understand the android history in a sequence.
Initially, Andy Rubin founded Android Incorporation in Palo Alto, California, United States in
October, 2003.
In 17th August 2005, Google acquired android Incorporation. Since then, it is in the subsidiary of
Google Incorporation.
Show battery level in "Quick Settings" for devices connected via Bluetooth
Navigation buttons dim when not in use
UI updates to 'Power Off' and 'Restart'
Toast messages are now white in color with same existing transparency
5. Android 5, 5.0.1, 5.0.2, 5.1 and 5.1.1 – Lollipop (API – 21, 22)
Screen recording
Enhanced notification access
System-wide settings for closed captioning
Performance improvements
8. Android 4.0, 4.0.1 – 4.0.4 and 4.3 – Ice Cream Sandwich (API – 14, 15)
UI improvements
USB host API
Mice, joysticks, gamepads... support
Resizable Home screen widgets
MTP notifications
Updated UI
Improved keyboard ease of use
Improved copy/paste
Improved power management
Social networking features
Near Field Communication support
Native VoIP/SIP support
Video call support
Speed improvements
USB Tethering
Applications installation to the expandable memory
HTML
Digital zoom
Microsoft Exchange support
Bluetooth 2.1
Live Wallpapers
Updated UI
13. Android 1.0 – 1.6 – Apple Pie, Bananabread, Cupcake, Donut (API – 1, 2, 3, 4)
Android Devices
An Android device is a device that runs on the Android operating system. Android is an array of
software intended for mobile devices that features an operating system, core applications and middleware.
An Android device may be a smartphone, tablet PC, e-book reader or any type of mobile device that requires
an OS.
Android is developed by the Open Handset Alliance, which is led by Google. Some of the well-
known Android device manufacturers include Acer, HTC, Samsung, LG, Sony Ericsson and Motorola.
Popular Android devices include smartphones, tablets and e-readers. The Android OS is also built
into a limited number of other devices, such as netbooks, portable music players, the Binatone iHome Phone
and Odroid handheld game consoles.
Within a short period, the Android platform became so popular that it surpassed Windows Mobile
and Symbian for a number of applications. The reasons behind this success are as follows:
Setting up software
System Requirements
We can start your Android application development on either of the following operating systems −
Need to check the components, which are required to create applications, below the image has
selected Android Studio, Android SDK, Android Virtual Machine and performance(Intel chip).
Need to specify the ram space for Android emulator by default it would take 512MB of local machine RAM.
At final stage, it would extract SDK packages into our local machine, it would take a while time to finish the
task and would take 2626MB of Hard disk space.
1. The toolbar lets you carry out a wide range of actions, including running your app and launching
Android tools.
2. The navigation bar helps you navigate through your project and open files for editing. It provides a
more compact view of the structure visible in the Project window.
Android Architecture
1. Linux kernel
At the bottom of the layers is Linux - Linux 3.6 with approximately 115 patches. This provides a
level of abstraction between the device hardware and it contains all the essential hardware drivers like
camera, keypad, display etc. Also, the kernel handles all the things that Linux is really good at such as
networking and a vast array of device drivers, which take the pain out of interfacing to peripheral hardware.
3. Android Libraries
This category encompasses those Java-based libraries that are specific to Android development.
Examples of libraries in this category include the application framework libraries in addition to those that
facilitate user interface building, graphics drawing and database access. A summary of some key core
Android libraries available to the Android developer is as follows −
android.app − Provides access to the application model and is the cornerstone of all Android
applications.
android.content − Facilitates content access, publishing and messaging between applications and
application components.
android.database − Used to access data published by content providers and includes SQLite
database management classes.
android.opengl − A Java interface to the OpenGL ES 3D graphics rendering API.
android.os − Provides applications with access to standard operating system services including
messages, system services and inter-process communication.
android.text − Used to render and manipulate text on a device display.
android.view − The fundamental building blocks of application user interfaces.
android.widget − A rich collection of pre-built user interface components such as buttons, labels, list
views, layout managers, radio buttons etc.
android.webkit − A set of classes intended to allow web-browsing capabilities to be built into
applications.
Having covered the Java-based core libraries in the Android runtime, it is now time to turn our attention to
the C/C++ based libraries contained in this layer of the Android software stack.
4. Android Runtime
This is the third section of the architecture and available on the second layer from the bottom. This
section provides a key component called Dalvik Virtual Machine which is a kind of Java Virtual Machine
specially designed and optimized for Android.
The Dalvik VM makes use of Linux core features like memory management and multi-threading,
which is intrinsic in the Java language. The Dalvik VM enables every Android application to run in its own
process, with its own instance of the Dalvik virtual machine.
5. Application Framework
The Application Framework layer provides many higher-level services to applications in the form of
Java classes. Application developers are allowed to make use of these services in their applications.
The Android framework includes the following key services −
Activity Manager − Controls all aspects of the application lifecycle and activity stack.
Content Providers − Allows applications to publish and share data with other applications.
Resource Manager − Provides access to non-code embedded resources such as strings, color
settings and user interface layouts.
Notifications Manager − Allows applications to display alerts and notifications to the user.
View System − An extensible set of views used to create application user interfaces.
6. Applications
You will find all the Android application at the top layer. You will write your application to be
installed on this layer only. Examples of such applications are Contacts Books, Browser, Games etc.
7. Android Emulator
The Android SDK includes a virtual mobile device emulator that runs on your computer. The
emulator lets you prototype, develop and test Android applications without using a physical device.
If you want to emulate a real device, first crate an AVD with the same device configurations as real
device, then launch this AVD from AVD manager.
Usually by default when you launch the emulator, its orientation is vertical,
but you can change it orientation by pressing Ctrl+F11 key from keyboard.
Home - Shifts to main screen
F4 - End call
F5 - Search
F7 - Power button
Java:
Android applications are developed using the Java language. Java is a very popular programming
language developed by Sun Microsystems (now owned by Oracle). Developed long after C and C++, Java
incorporates many of the powerful features of those powerful languages while addressing some of their
drawbacks. Still, programming languages are only as powerful as their libraries. These libraries exist to help
developers build applications.
It‘s object-oriented
Android relies heavily on these Java fundamentals. The Android SDK includes many standard Java
libraries (data structure libraries, math libraries, graphics libraries, networking libraries and everything else
you could want) as well as special Android libraries that will help you develop awesome Android
applications.
With many programming languages, you need to use a compiler to reduce your code down into
machine language that the device can understand. The Java compilers convert your code from human
readable Java source files to something called ―bytecode‖ in the Java world. These are interpreted by a Java
Virtual Machine, which operates much like a physical CPU might operate on machine code, to actually
execute the compiled code.
Android applications run in a special virtual machine called the Dalvik VM. It can allowing you to
not have to worry about whether the device is a Motorola or HTC, or the latest toaster running Android. You
don‘t care so long as the device is Dalvik VM friendly
Java is Secure:
A virtual machine can encapsulate, contain, and manage code execution in a safe manner compared
to languages that operate in machine code directly. Each Android application runs on the (Linux-based)
operating system using a different user account and in its own instance of the Dalvik VM. Android
applications are closely monitored by the operating system and shut down if they don‘t play nice. Therefore,
it‘s important to develop applications that are stable and responsive.
OOP is a programming style or technique that relies upon the definition of data structures called
objects. For those new to OOP, an object can be thought of much like a custom data type.
A class typically describes the data and behaviour of an object. The behaviour is defined using
class methods. Method is the common term for a subroutine in an OOP language. Many common object
classes are defined in shared class libraries like software development kits (SDKs), whereas others are
S. Parsuvanathan M.Sc., M.Phil Page 21
defined by you, the developer, for your own purposes. Software is then built up by using and manipulating
object instances in different ways.
Class hierarchies, such as our fish classes, can then be organized into packages. A package is simply
a set of classes and interfaces, bundled together. Developers use namespaces to uniquely name packages.
Android Studio contains tools such as the Android Virtual Device Manager and the Android Device
Monitor. It also contains Gradle, which helps you configure your Android application seamlessly. Some of
the interesting features of Android Studio include the following:
We will explore how we can create a simple application using Android Studio in the section. Android
applications are based on the Java programming language and make extensive use of XML. To create an
Android application using Android Studio, follow these simple steps:
Eclipse
Eclipse is a IDE for Android Development, a multi-language software development environment
featuring an extensible plug-in system. It can be used to develop various types of applications, using
languages such as Java, Ada, C, C++, COBOL, Python, and others.
For Android development, you should download the Eclipse IDE for Java EE Developers
(www.eclipse.org/downloads/). Six editions are available: Windows (32- and 64-bit), Mac OS X (Cocoa 32-
and 64), and Linux (32- and 64-bit). Simply select the relevant one for your operating system.
Once the Eclipse IDE is downloaded, unzip its content (the eclipse folder) into a folder, say
C:\Android 4.0\. Figure 1-14 shows the content of the eclipse folder. To launch Eclipse, double-click on the
eclipse.exe fi le. You are fi rst asked to specify your workspace. In Eclipse, a workspace is a folder where
you store all your projects. Take the default suggested (or you can specify your own folder as the workspace)
and click OK.
Virtualization:
The Android Virtual Device Manager allows you to create Android Virtual Devices (AVDs), which
you can then run to emulate a device on your computer. There‘s an important but subtle distinction between
simulation and emulation. Simulation means that the virtual device is merely a façade that simulates how an
actual physical device might behave, but does not run the targeted operating system. The iOS development
environment uses simulation.
With emulation, however, your computer sets aside a block of memory to reproduce the environment
found on the device that the emulator is emulating. Android Studio uses emulation, which means the
Android Virtual Device Manager launches a sandboxed version of the Linux kernel and the entire Android
stack in order to emulate the environment found on the physical Android device. Although emulation
provides a much more faithful environment on which to test your apps than simulation does, booting up an
AVD can drag into the minutes, depending on the speed of your computer.
That said, let‘s first set up an AVD using the Android Virtual Device Manager.
Click the Android Virtual Device Manager icon encircled in Figure 1-25. On the first screen of the
Andriod Virtual Device Manager Wizard, click the Create Virtual Device button.
On the next screen, click the Finish button to verify your AVD settings. Congratulations, you just
created a new AVD.
Android ships with a debugging tool called the Dalvik Debug Monitor Service (DDMS), which
provides port-forwarding services, screen capture on the device, thread and heap information on the device,
logcat, process, and radio state information, incoming call and SMS spoofing, location data spoofing, and
more.
DDMS ships in the tools/ directory of the SDK. Enter this directory from a terminal/console and type
ddms (or ./ddms on Mac/Linux) to run it. DDMS will work with both the emulator and a connected device.
If both are connected and running simultaneously, DDMS defaults to the emulator.
DDMS acts as a middleman to connect the IDE to the applications running on the device. When it
starts, DDMS connects to adb and starts a device monitoring service between the two, which will notify
DDMS when a device is connected or disconnected.
When a device is connected, a VM monitoring service is created between adb and DDMS, which will
notify DDMS when a VM on the device is started or terminated.
Once a VM is running, DDMS retrieves the the VM's process ID (pid), via adb, and opens a
connection to the VM's debugger, through the adb daemon (adbd) on the device.
DDMS can now talk to the VM using a custom wire protocol.
Left Pane
The left side of the Debug Monitor shows each emulator/device currently found, with a list of all the
VMs currently running within each. VMs are identified by the package name of the application it hosts.
Right pane
On the right side, the Debug Monitor provides tabs that display useful information and some pretty
cool tools.
Info
This view shows some general information about the selected VM, including the process ID, package name,
and VM version.
The threads view has a list of threads running in the process of the target VM. To reduce the amount
of data sent over the wire, the thread updates are only sent when explicitly enabled by toggling the "threads"
button in the toolbar. This toggle is maintained per VM. This tab includes the following information:
ID - a VM-assigned unique thread ID. In Dalvik, these are odd numbers starting from 3.
Tid - the Linux thread ID. For the main thread in a process, this will match the process ID.
Status - the VM thread status. Daemon threads are shown with an asterisk (*). This will be one of the
following:
running - executing application code
sleeping - called Thread.sleep()
monitor - waiting to acquire a monitor lock
wait - in Object.wait()
native - executing native code
vmwait - waiting on a VM resource
zombie - thread is in the process of dying
init - thread is initializing (you shouldn't see this)
starting - thread is about to start (you shouldn't see this either)
utime - cumulative time spent executing user code, in "jiffies" (usually 10ms). Only available under
Linux.
stime - cumulative time spent executing system code, in "jiffies" (usually 10ms).
Name - the name of the thread
Emulator Control
With these controls, you can simulate special device states and activities. Features include:
Telephony Status - change the state of the phone's Voice and Data plans (home, roaming, searching,
etc.), and simulate different kinds of network Speed and Latency (GPRS, EDGE, UTMS, etc.).
Telephony Actions - perform simulated phone calls and SMS messages to the emulator.
Location Controls - send mock location data to the emulator so that you can perform location-aware
operations like GPS mapping.
To use the Location Controls, launch your application in the Android emulator and open DDMS.
Click the Emulator Controls tab and scroll down to Location Controls. From here, you can:
src — Contains the .java source files for your project. In this example, there is one fi le,
HelloWorldActivity.java. The HelloWorldActivity.java file is the source fi le for your activity. You
write the code for your application in this file.
gen — Contains the R.java fi le, a compiler-generated file that references all the resources found in
your project. You should not modify this file. All the resources in your project are automatically
compiled into this class so that you can refer to them using the class.
Android library — This item contains one file, android.jar, which contains all the class libraries
needed for an Android application.
assets — This folder contains all the assets used by your application, such as HTML, text files,
databases, etc.
bin — This folder contains the files built by the ADT during the build process. In particular, it
generates the .apk file (Android Package). An .apk file is the application binary of an Android
application. It contains everything needed to run an Android application.
res — This folder contains all the resources used in your application. It also contains a few other
subfolders: drawable-<resolution>, layout, and values.
AndroidManifest.xml — This is the manifest file for your Android application. Here you specify
the permissions needed by your application, as well as other features.
Android Emulator:
The Android emulator is an application that provides a virtual mobile device on which you can run
your Android applications. It runs a full Android system stack, down to the kernel level, that includes a set
of preinstalled applications that you can access from your applications. You can choose what version of the
Android system you want to run in the emulator by configuring AVDs, and you can also customize the
mobile device skin and key mappings.
When launching the emulator and at runtime, you can use a variety of commands and options to
control its behavior. The Android system images available through the Android SDK Manager contain code
for the Android Linux kernel, the native libraries, the Dalvik VM, and the various Android packages. The
emulator provides dynamic binary translation of device machine code to the OS and processor architecture
of your development machine.
To use the emulator, you first must create one or more AVD configurations. In each
configuration, you specify an Android platform to run in the emulator and the set of hardware
options and emulator skin you want to use. Then, when you launch the emulator, you specify the
AVD configuration that you want to load.
Each AVD functions as an independent device, with its own private storage for user data, SD
card, and so on. When you launch the emulator with an AVD configuration, it automatically loads
the user data and SD card data from the AVD directory. By default, the emulator stores the user
data, SD card data, and cache in the AVD directory.
During development and testing of your application, you install and run your application in the
Android emulator. You can launch the emulator as a standalone application from a command line, or you
can run it from within your Eclipse development environment. In either case, you specify the AVD
configuration to load and any start up options you want to use.
Activities
An application can have zero or more activities. Typically, applications have one or more activities;
and the main purpose of an activity is to interact with the user. From the moment an activity appears on the
screen to the moment it is hidden, it goes through a number of stages, known as an activity‘s life cycle.
Think of fragments as ―miniature‖ activities that can be grouped to form an activity. Apart from
activities, another unique concept in Android is that of an intent. An intent is basically the ―glue‖ that
enables different activities from different applications to work together seamlessly, ensuring that tasks can
be performed as though they all belong to one single application.
Lifecycle:
The Activity base class defi nes a series of events that govern the life cycle of an activity. The
Activity class defines the following events:
An activity is destroyed when you click the Back button. This is crucial to know, as whatever state
the activity is currently in will be lost; hence, you need to write additional code in your activity to preserve
its state when it is destroyed. At this point, note that the onPause() method is called in both scenarios when
an activity is sent to the background, as well as when it is killed when the user presses the Back button.
When an activity is started, the onStart() and onResume()methods are always called, regardless of
whether the activity is restored from the background or newly created. When an activity is created for the
first time, the onCreate() method is called.
From the preceding example, you can derive the following guidelines:
Use the onCreate() method to create and instantiate the objects that you will be using in your
application.
Use the onResume() method to start any services or code that needs to run while your activity is in
the foreground.
Creating Activities:
1. Using Android Studio, create a new Android project and name it Activity101.
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class Activity101Activity extends Activity {
String tag = “Lifecycle”;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.d(tag, “In the onCreate() event”);
}
public void onStart()
{
super.onStart();
Log.d(tag, “In the onStart() event”);
}
public void onRestart()
{
super.onRestart();
Log.d(tag, “In the onRestart() event”);
}
public void onResume()
{
super.onResume();
Log.d(tag, “In the onResume() event”);
}
public void onPause()
{
super.onPause();
Log.d(tag, “In the onPause() event”);
}
public void onStop()
{
super.onStop();
5. If you click the Back button on the Android emulator, the following is printed:
6. Click the Home button and hold it there. Click the Activities icon and observe the following:
7. Click the Phone button on the Android emulator so that the activity is pushed to the background.
Observe the output in the LogCat window:
8. Notice that the onDestroy() event is not called, indicating that the activity is still in memory. Exit the
phone dialer by clicking the Back button. The activity is now visible again. Observe the output in the LogCat
window:
11-16 06:32:50.515: D/Lifecycle(559): In the onRestart() event
11-16 06:32:50.515: D/Lifecycle(559): In the onStart() event
11-16 06:32:50.515: D/Lifecycle(559): In the onResume() event
The onRestart() event is now fi red, followed by the onStart() and onResume() methods.
One of the most common uses for Intents is to start new Activities, either explicitly (by specifying the
class to load) or implicitly (by requesting that an action be performed on a piece of data). In the latter case
the action does not need to be performed by an Activity within the calling application.
To select a specific Activity class to start, create a new Intent, specifying the current Activity‘s
Context and the class of the Activity to launch. Pass this Intent into startActivity,
startActivity(intent);
After startActivity is called, the new Activity will be created, started, and resumed moving to the top
of the Activity stack. Calling finish on the new Activity, or pressing the hardware back button, closes it and
removes it from the stack. Alternatively, you can continue to navigate to other Activities by calling
startActivity. Note that each time you call startActivity, a new Activity will be added to the stack; pressing
back (or calling finish) will remove each of these Activities, in turn.
An implicit Intent is a mechanism that lets anonymous application components service action
requests. That means you can ask the system to start an Activity to perform an action without knowing
which application, or Activity, will be started.
For example, to let users make calls from your application, you could implement a new dialer, or you
could use an implicit Intent that requests the action (dialing) be performed on a phone
INTENT FILTER:
Generally, the Intent Filters (<intent-filter>) whatever we define in manifest file can be nested in the
corresponding app components and we can specify the type of intents to accept using these three elements.
<action> - It defines the name of an intent action to be accepted and it must be a literal string value
of an action, not the class constant.
<category> - It defines the name of an intent category to be accepted and it must be the literal string
value of an action, not the class constant.
<data> - It defines the type of data to be accepted and by using one or more attributes we can specify
various aspects of the data URI (scheme, host, port, path) and MIME type.
Following is the code snippet of defining an activity with Intent Filter (<intent-filter>) in Android
Manifest file (AndroidManifest.xml) like as shown below.
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<data android:mimeType="text/plain"/>
</intent-filter>
</activity>
Mainactivity.java
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
Androidmanifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tutlane.intentfilters">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
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" />
<action android:name="android.intent.action.SEND"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="message/rfc822"/>
</intent-filter>
Output:
A Task holds the Activities, arranged in a Stack called Android Stack. The Stack has LIFO structure
and stores the activities in the order of their opening. The Activities in the Stack are never rearranged. The
navigation of the back stack is done with the help of the Back button.
2. When the current Activity starts another Activity, then the new Activity is pushed on top of the stack
and takes focus.
3. The previous Activity moves below this new Activity in the back stack and is stopped. The system
retains the current state of this Activity‘s user interfaces like text in the form, scroll position etc.
5. When the Back button is pressed then the current Activity is popped from the top of the back stack.
This destroys the Activity and the previous Activity resumes with its state restored.
6. The Back button then keeps on popping the current Activities and restoring the previous activities.
When the last Activity is removed from the back stack, then the Task terminates to the screen that
was last running before the creation of the Task (in our case the launcher screen).
7. When the back stack goes empty then the Task ceased to exist.
1. It goes into the background when a new task is created or when the Home button is pressed.
2. It is then brought to the foreground by clicking the launcher icon (this is the another role of the
launcher icon that we mentioned earlier) or by selecting the task from the recent screens.
3. When multiple tasks are in the background or when the user leaves the Task for a long time, the
system in order to recover memory clears the Task of all the Activities except the root Activity.
When the user returns to the Task again, only the root Activity is restored (this behavior can be
overridden as we will see later).
Launch Mode:
The launchModes and its equivalent startActivity Flags allow us to define, how a new instance of an
Activity is associated with the current Task and specifies the instruction for its launch in the given Task. The
types of launchModes and its equivalent startActivity Flags are presented and investigated in the following
points
launchMode — standard: This is the default mode of the Activity. In this mode, a new instance of the
Activity is created and put in the Task which started it by routing the intent to it.
launchMode — singleInstance: This launchMode is similar to the singleTask except that the System
doesn‘t launch any other Activity into the Task holding the instance. The Activity is always the single and
the only member of its Task. Any Activity started by this one opens in a separate Task.
ANDROID SERVICE:
A Service is an application component that can perform long-running operations in the background,
and it doesn't provide a user interface. Another application component can start a service, and it continues to
run in the background even if the user switches to another application. These are the three different types of
services:
Foreground: A foreground service performs some operation that is noticeable to the user.
Background: A background service performs an operation that isn't directly noticed by the user.
Bound: A service is bound when an application component binds to it by calling bindService(). A
bound service offers a client-server interface that allows components to interact with the service,
send requests, receive results, and even do so across processes with interprocess communication
(IPC).
To create a service, you must create a subclass of Service or use one of its existing subclasses. In your
implementation, you must override some callback methods. These are the most important callback methods
that you should override:
onStartCommand(): The system invokes this method by calling startService() when another
component (such as an activity) requests that the service be started.
onBind(): The system invokes this method by calling bindService() when another component wants
to bind with the service (such as to perform RPC).
onCreate(): The system invokes this method to perform one-time setup procedures when the service
is initially created.
onDestroy(): The system invokes this method when the service is no longer used and is being
destroyed.
You must declare all services in your application's manifest file, just as you do for activities and
other components. To declare your service, add a <service> element as a child of the <application> element.
Here is an example:
CREATING A SERVICE
A started service is one that another component starts by calling startService(), which results in a call
to the service's onStartCommand() method.
You can start a service from an activity or other application component by passing
an Intent to startService() or startForegroundService(). The Android system calls the
service's onStartCommand() method and passes it the Intent, which specifies which service to start.
Apps can register to receive specific broadcasts. When a broadcast is sent, the system automatically
routes broadcasts to apps that have subscribed to receive that particular type of broadcast. However, you
must be careful not to abuse the opportunity to respond to broadcasts and run jobs in the background that can
contribute to a slow system performance, as described in the following video.
RECEIVING BROADCASTS
Apps can receive broadcasts in two ways: through manifest-declared receivers and context-registered
receivers.
1. If you declare a broadcast receiver in your manifest, the system launches your app (if the app is not
already running) when the broadcast is sent.
2. Subclass BroadcastReceiver and implement onReceive(Context, Intent). The broadcast receiver in the
following example logs and displays the contents of the broadcast:
SENDING BROADCASTS
Android provides three ways for apps to send broadcast:
The sendBroadcast(Intent) method sends broadcasts to all receivers in an undefined order. This is
called a Normal Broadcast.
Example:
activity_main.xml
<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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.journaldev.broadcastreceiver.MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button"
S. Parsuvanathan M.Sc., M.Phil Page 47
android:text="Send Broadcast"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
ConnectionReceiver receiver;
IntentFilter intentFilter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
receiver = new ConnectionReceiver();
intentFilter = new IntentFilter("com.journaldev.broadcastreceiver.SOME_ACTION");
}
@Override
protected void onResume() {
super.onResume();
registerReceiver(receiver, intentFilter);
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(receiver);
}
@OnClick(R.id.button)
void someMethod() {
Intent intent = new Intent("com.journaldev.broadcastreceiver.SOME_ACTION");
sendBroadcast(intent);
}
}
AndroidManifest.xml:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.journaldev.broadcastreceiver">
CONTENT PROVIDER:
A content provider manages access to a central repository of data. A provider is part of an Android
application, which often provides its own UI for working with the data. However, content providers are
primarily intended to be used by other applications, which access the provider using a provider client object.
Typically you work with content providers in one of two scenarios; you may want to implement code
to access an existing content provider in another application, or you may want to create a new content
provider in your application to share data with other applications.
A content provider coordinates access to the data storage layer in your application for a number of
different APIs and components as illustrated in figure 1, these include:
CONTENTRESOLVER.
Each android application can be a content provider. For example, android phone contacts, short
message system and android media library. To get data from a content provider, you need to use
a ContentResolver instance in your app. Generally the ContentResolver instance can be obtained
by Activity‗s getContentResolver() method.
ContentResolver contentResolver = getContentResolver();
Then you can invoke ContentResolver‗s method to insert, delete, update and query data that another
content provider shared. This is something like SQLite database operation.
1 Insert Data To Content Provider:
insert(Uri providerUri, ContentValues values)
2 Update Content Provider Data.
update(Uri providerUri, ContentValues values, String whereClause, String conditionValueArr[])
3 Delete Content Provider Data.
delete(Uri providerUri, String whereClause, String conditionValueArr[])
2.4 Query Content Provider Data.
query(Uri uri, String columnArray[], String whereClause, String wherePlaceHolderValue[], String
orderByClause)
Example:
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
SQLite DATABASE
SQLite is a opensource SQL database that stores data to a text file on a device. Android comes in
with built in SQLite database implementation. SQLite supports all the relational database features. In order
to access this database, you don't need to establish any kind of connections for it like JDBC,ODBC e.t.c
The main package is android.database.sqlite that contains the classes to manage your own databases
1. Database - Insertion
we can create table or insert data into table using execSQL method defined in SQLiteDatabase class.
Its syntax is given below
mydatabase.execSQL("CREATE TABLE IF NOT EXISTS sample (Username VARCHAR,Password
VARCHAR);");
mydatabase.execSQL("INSERT INTO sample VALUES('admin','admin');");
2. Database - Fetching
We can retrieve anything from database using an object of the Cursor class. We will call a method of
this class called rawQuery and it will return a resultset with the cursor pointing to the table. We can move
the cursor forward and retrieve the data.
LAYOUT ATTRIBUTES
Each layout has a set of attributes which define the visual properties of that layout. There are few
common attributes among all the layouts and their are other attributes which are specific to that layout.
Following are common attributes and will be applied to all the layouts:
S. Parsuvanathan M.Sc., M.Phil Page 61
android:id - This is the ID which uniquely identifies the view.
android:layout_width - This is the width of the layout.
android:layout_height - This is the height of the layout
android:layout_marginTop - This is the extra space on the top side of the layout.
android:layout_marginBottom - This is the extra space on the bottom side of the layout.
android:layout_marginLeft - This is the extra space on the left side of the layout.
android:layout_marginRight - This is the extra space on the right side of the layout.
android:layout_gravity - This specifies how child Views are positioned.
android:layout_weight - This specifies how much of the extra space in the layout should be
allocated to the View.
android:paddingLeft - This is the left padding filled for the layout.
android:paddingRight - This is the right padding filled for the layout.
android:paddingTop - This is the top padding filled for the layout.
android:paddingBottom - This is the bottom padding filled for the layout.
1. LinearLayout
The LinearLayout arranges views in a single column or a single row. Child views can be arranged
either vertically or horizontally. To see how LinearLayout works, consider the following elements typically
contained in the main.xml file:
<?xml version=”1.0” encoding=”utf-8”?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
android:orientation=”vertical” >
<TextView
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”@string/hello” />
</LinearLayout>
2. RelativeLayout
The RelativeLayout enables you to specify how child views are positioned relative to each other.
android:id=”@+id/RLayout”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
xmlns:android=”http://schemas.android.com/apk/res/android” >
The TableLayout groups views into rows and columns. You use the <TableRow> element to
designate a row in the table. Each row can contain one or more views. Each view you place within a row
forms a cell. The width of each column is determined by the largest width of each cell in that column.
Consider the content of main.xml shown here:
<TableLayout
xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_height=”fill_parent”
android:layout_width=”fill_parent” >
<TableRow>
<TextView
android:text=”User Name:”
android:width =”120dp”
/>
<EditText
android:id=”@+id/txtUserName”
android:width=”200dp” />
</TableRow>
<TableRow>
<TextView
android:text=”Password:”
/>
<EditText
android:id=”@+id/txtPassword”
android:password=”true”
/>
</TableRow>
<TableRow>
<TextView />
<CheckBox android:id=”@+id/chkRememberPassword”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”Remember Password”
/>
</TableRow>
<TableRow>
<Button
android:id=”@+id/buttonSignIn”
android:text=”Log In” />
</TableRow>
</TableLayout>
4. FrameLayout
The FrameLayout is a placeholder on screen that you can use to display a single view. Views that
you add to a FrameLayout are always anchored to the top left of the layout. Consider the following content
in main.xml:
<?xml version=”1.0” encoding=”utf-8”?>
<RelativeLayout
5. GridView Layout:
Android GridView shows items in two-dimensional scrolling grid (rows & columns) and the grid
items are not necessarily predetermined but they automatically inserted to the layout using a ListAdapter.
The ListView and GridView are subclasses of AdapterView and they can be populated by binding them to
an Adapter, which retrieves data from an external source and creates a View that represents each data entry.
GridView Attributes
android:id - This is the ID which uniquely identifies the layout.
android:columnWidth - This specifies the fixed width for each column. This could be in px, dp, sp,
in,
android:gravity - Specifies the gravity within each cell. Possible values are top, bottom, left, right,
center, center_vertical, center_horizontal etc.
android:horizontalSpacing - Defines the default horizontal spacing between columns. This could
be in px, dp, sp, in, or mm.
android:numColumns - Defines how many columns to show. May be an integer value, such as
"100" or auto_fit which means display as many columns as possible to fill the available space.
2. CONTEXTUAL MENUS
A contextual menu offers actions that affect a specific item or
context frame in the UI. You can provide a context menu for any view,
but they are most often used for items in a ListView, GridView, or other
view collections in which the user can perform direct actions on each
item.
There are two ways to provide contextual actions:
In a floating context menu. A menu appears as a floating list of
menu items (similar to a dialog) when the user performs a long-
click (press and hold) on a view that declares support for a context
menu. Users can perform a contextual action on one item at a time.
3. Implement onContextItemSelected(). When the user selects a menu item, the system calls this method so
you can perform the appropriate action.
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) {
case R.id.edit:
editNote(info.id);
return true;
case R.id.delete:
deleteNote(info.id);
return true;
default:
return super.onContextItemSelected(item);
}
}
POPUP MENU
A PopupMenu is a modal menu anchored to a View. It appears below
the anchor view if there is room, or above the view otherwise. It's useful
for:
Providing an overflow-style menu for actions that relate
to specific content (such as Gmail's email headers, shown in
figure 4).
Providing a second part of a command sentence (such as a button
marked "Add" that produces a popup menu with different "Add"
options).
Providing a drop-down similar to Spinner that does not retain a
persistent selection.
MainActivity.java
public void showPopup(View v) {
PopupMenu popup = new PopupMenu(this, v);
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.actions, popup.getMenu());
popup.show();
}
LIST
Android ListView is a view which groups several items and display them in vertical scrollable list.
The list items are automatically inserted to the list using an Adapter that pulls content from a source such as
an array or database.
An adapter actually bridges between UI components and the data source that fill data into UI
Component. Adapter holds the data and send the data to adapter view, the view can takes the data from
adapter view and shows the data on different views like as spinner, list view, grid view etc.
The ListView and GridView are subclasses of AdapterView and they can be populated by binding
them to an Adapter, which retrieves data from an external source and creates a View that represents each
data entry.
Android provides several subclasses of Adapter that are useful for retrieving different kinds of data
and building views for an AdapterView ( i.e. ListView or GridView). The common adapters
are ArrayAdapter,Base
Adapter, CursorAdapter, SimpleCursorAdapter,SpinnerAdapter and WrapperListAdapter. We will
see separate examples for both the adapters.
android:entries - Specifies the reference to an array resource that will populate the ListView.
android:footerDividersEnabled - When set to false, the ListView will not draw the divider before
each footer view. The default value is true.
Example:
activity_main.xml:
<LinearLayout 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"
android:orientation="vertical"
tools:context=".ListActivity" >
<ListView
android:id="@+id/mobile_list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
MainActivity.java
public class ListDisplay extends Activity {
// Array of strings...
String[] mobileArray = {"Android","IPhone","WindowsMobile","Blackberry",
"WebOS","Ubuntu","Windows7","Max OS X"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayAdapter adapter = new ArrayAdapter<String>(this,
R.layout.activity_listview, mobileArray);
ListView listView = (ListView) findViewById(R.id.mobile_list);
listView.setAdapter(adapter);
}
}
INPUT CONTROLS:
1. TEXTVIEW CONTROL
In android, TextView is a user interface control which is used to set and display the text to the user
based on our requirements. The TextView control will act as like label control and it won‘t allow users to
edit the text. In android, we can create a TextView control in two ways either in XML layout file or create it
in Activity file programmatically.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:text="Welcome to Tutlane"
android:textColor="#86AD33"
android:textSize="20dp"
android:textStyle="bold" />
</LinearLayout>
TextView Attributes
Following are the some of commonly used attributes related to TextView control in android applications.
2. BUTTON CONTROL:
In android, Button is a user interface control which is used to perform an action whenever the user
click or tap on it. Generally, Buttons in android will contains a text or an icon or both and perform an action
when user touches it.
In android, we have a different type of buttons available to use based on our requirements, those
are ImageButton, ToggleButton, RadioButton. In android, we can create a Button control in two ways
either in XML layout file or create it in Activity file programmatically.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/addBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add" />
</LinearLayout>
3. CHECKBOX CONTROLS:
In android, CheckBox is a two states button that can be either checked (ON) or unchecked (OFF)
and it will allow users to toggle between the two states (ON / OFF) based on the requirements. Generally, we
can use multiple CheckBox controls in android application to allow users to select one or more options from
the set of values.
By default, the android CheckBox will be in OFF (Unchecked) state. We can change the default
state of CheckBox by using android:checked attribute.
In case, if we want to change the state of CheckBox to ON (Checked), then we need to
set android:checked = ―true‖ in our XML layout file.
In android, we can create CheckBox control in two ways either in XML layout file or create it
in Activity file programmatically.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
If you observe above code snippet, we defined a progress bar (<ProgressBar>) with different
attributes, those are
android:id - It is used to uniquely identify the control
android:minHeight - It is used to set the height of progress bar.
android:minWidth - It is used to set the width of progress bar.
android:max - It is used to set the maximum value of progress bar.
android:progress - It is used to set the default progress value between 0 and max. It must be an
integer value.
Dialog Description
AlertDialog This dialog is used to display prompt to the user with title, upto three buttons, list of
selectable items or a custom layout.
DatePickerDialog This dialog is a predefined UI control and it allow user to select Date.
Android AlertDialog
In android, AlertDialog is used to
prompt a dialog to the user with message
and buttons to perform an action to
proceed further.
The AlertDialog in android
application will contain a three regions
like as shown below.
In android Alert Dialogs, we can
show a title, up to three buttons, a list of
selectable items or a custom layout based on our requirements.
Region Description
Title It‘s an optional and it can be used to show the detailed messages based on our requirements.
Content It is used to display a message, list or other custom layouts based on our requirements.
Area
Action It is used to display an action buttons to interact with the users. We can use upto 3 different
Buttons action buttons in alert dialog, such as positive, negative and neutral.
Generally, in android we can build AlertDialog in our activity file using different dialog methods.
Android AlertDialog Methods
Method Description
setTitle() It is used to set the title of alertdialog and its an optional component.
setCancelable() It is used to allow users to cancel alertdialog by clicking on outside of dialog area by
setting true / false.
setPositiveButton() It is used to set the positive button for alertdialog and we can implement click event
of positive button.
setNegativeButton() It is used to set the negative button for alertdialog and we can implement click event
of negative button.
setNeutralButton() It is used to set the neutral button for alertdialog and we can implement click event
of neutral button.