SlideShare a Scribd company logo
20IT601PE-
MOBILE APPLICATION DEVELOPMENT
III Year / VI Semester
UNIT I
ANDROID OVERVIEW
Introduction – Android SDK features – OHA
– Development framework – Getting started –
developing for android, mobile devices - ADT –
Creating an applications and activities -
Application manifest – Android Application Life
Cycle – Understanding application priority -
Externalizing resources – Android application
class – Android Activities
Introduction
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.
Why Android ?
Features of Android
S.No. Feature & Description
1
Beautiful UI
Android OS basic screen provides a beautiful and intuitive user interface.
2
Connectivity
GSM/EDGE, IDEN, CDMA, EV-DO, UMTS, Bluetooth, Wi-Fi, LTE, NFC and
WiMAX.
3
Storage
SQLite, a lightweight relational database, is used for data storage purposes.
4
Media support
H.263, H.264, MPEG-4 SP, AMR, AMR-WB, AAC, HE-AAC, AAC 5.1, MP3, MIDI,
Ogg Vorbis, WAV, JPEG, PNG, GIF, and BMP.
5
Messaging
SMS and MMS
6
Web browser
Based on the open-source WebKit layout engine, coupled with Chrome's V8 JavaScript
engine supporting HTML5 and CSS3.
S.No. Feature & Description
7
Multi-touch
Android has native support for multi-touch which was initially made available in handsets such as
the HTC Hero.
8
Multi-tasking
User can jump from one task to another and same time various application can run
simultaneously.
9
GCM
Google Cloud Messaging (GCM) is a service that lets developers send short message data to their
users on Android devices, without needing a proprietary sync solution.
10
Wi-Fi Direct
A technology that lets apps discover and pair directly, over a high-bandwidth peer-to-peer
connection.
11
Android Beam
A popular NFC-based technology that lets users instantly share, just by touching two NFC-
enabled phones together.
Android applications:
 Entertainment
 Tools
 Communication
 Productivity
 Personalization
 Music and Audio
 Social
 Media and Video
 Travel and Local
Android SDK Features
 Android SDK stands for Android Software Development Kit which is
developed by Google for Android Platform. With the help of Android
SDK, we can create android Apps easily.
 Android SDK is a collection of libraries and Software Development
tools that are essential for Developing Android Applications.
 Android SDK consists of some tools which are very essential for the
development of Android Application.
 These tools provide a smooth flow of the development process from
developing and debugging. Android SDK is compatible with all
operating systems such as Windows, Linux, macOS, etc.
Android SDK Features
 To download and install latest android APIs and development
tools from the internet, android provide us with android SDK
manager.
 Android SDK Manager separates the APIs, tools and different
platforms into different packages which you can download.
 Android SDK manager comes with the Android SDK bundle.
You can't download it separately.
Android SDK Features
Running Android SDK Manager
 Once downloaded, you can launch Android SDK Manager in
one of the following ways −
 Click tools->Android-> SDK Manager option in Eclipse.
 Double Click on the SDK Manager.exe file in the Android
SDK folder.
When it runs you will see the following screen:
Components of Android SDK
1. Android SDK Tools
 Android SDK tool is an important component of Android
SDK. It consists of a complete set of development and
debugging tools. Below are the SDK developer tools:
 Android SDK Build tool.
 Android Emulator.
 Android SDK Platform-tools.
 Android SDK Tools.
Components of Android SDK
2. Android SDK Build-Tools
Android SDK build tools are used for building actual binaries of Android
App. The main functions of Android SDK Build tools are built, debug,
run and test Android applications.
3. Android Emulator
• An Android Emulator is a device that simulates an Android device
on your system. Suppose we want to run our android application that we
code.
• In Android Emulator the virtual android device is shown on our
system on which we run the Android application that we code.
Components of Android SDK
4. Android SDK Platform-tools
 Android SDK Platform-tools is helpful when we are working on Project
and they will show the error messages at the same time. It is specifically
used for testing. It includes:
 Android Debug Bridge (ADB), is a command-line tool that helps to
communicate with the device. It allows us to perform an action such as
Installing App and Debugging App etc.
 Fastboot allows you to flash a device with a new system image.
 Systrace tools help to collect and inspect timing information. It is
very crucial for App Debugging.
Open Handset Alliance (OHA)
 The Open Handset Alliance (OHA) is a consortium of 84 firms to
develop open standards for mobile devices.
 Established on 5th November 2007, as a consortium of 84
companies, the Open Handset Alliance (OHA) includes Google,
Samsung, AKM, Synaptics, KDDI, Garmin, Teleca, eBay, Intel, etc.
 The Open Handset Alliance (OHA) is led by Google. The main
objective of Android is to advance open standards, provide services,
and deploy handsets.
Open Handset Alliance (OHA)
 The Open Handset Alliance (OHA) It's a consortium of 84
companies such as google, samsung, AKM, synaptics, KDDI,
Garmin, Teleca, Ebay, Intel etc.
 Established on 5th November 2007, as a consortium of 84
companies, the Open Handset Alliance (OHA) includes Google,
Samsung, AKM, Synaptics, KDDI, Garmin, Teleca, eBay, Intel, etc.
 The Open Handset Alliance (OHA) is led by Google. The main
objective of Android is to advance open standards, provide services,
and deploy handsets.
Development framework
 In general, a framework is a real or conceptual structure
intended to serve as a support or guide for the building of
something that expands the structure into something useful.
 An Android application framework is a software toolkit that
enables app developers to piece together a finished product
that meets the requirements of its proprietor.
Development framework
 A framework provides the bones of an application, to be
fleshed out with graphics, animation, special features and
functionality.
 The Application Framework layer provides many higher-
level services to applications in the form of Java classes.
Android architecture or Android software stack is
categorized into five parts:
Linux kernel
Native libraries (middleware)
Android Runtime
Application Framework
Application Layer
20IT601PE - Mobile Application Development PPT.pdf
1) Linux kernel
• It is the heart of android architecture that exists
at the root of android architecture.
• Linux kernel is responsible for device drivers,
power management, memory management,
device management and resource access.
2) Native Libraries
• Running on the top of linux kernel, Native libraries such as
WebKit, OpenGL, FreeType, SQLite, Media, C runtime
library (libc) etc.
• The WebKit library is responsible for browser support and
Internet security;
• SQLite is for database,
• FreeType for font support,
• Media for playing and recording audio and video formats.
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.
3) Android Runtime
 In android runtime, there are core libraries and DVM
(Dalvik Virtual Machine) which is responsible to run
android application.
 One of the key elements of Android is the Dalvik VM,
Android uses its own custom VM designed to ensure that
multiple instances run efficiently on a single device.
 DVM is like JVM but it is optimized for mobile devices.
 The Dalvik VM makes use of Linux core features like
memory management and multi-threading, which is
intrinsic in the Java language.
 It consumes less memory and provides fast performance.
4) Android Framework
 On the top of Native libraries and android runtime, there
is android framework.
 Android framework includes Android API's such as UI
(User Interface), telephony, resources, locations, Content
Providers (data) and package managers.
 It provides a lot of classes and interfaces for android
application development.
5) Application Layer
 On the top of android framework, there are applications.
 All applications such as home, contact, settings, games,
browsers are using android framework that uses android
runtime and libraries.
 Android runtime and native libraries are using linux
kernal.
Android Core Building Blocks
 An android component is simply a piece of code that has
a well defined life cycle e.g. Activity, Receiver, and
Service etc.
 The core building blocks or fundamental components of
android are activities, views, intents, services, content
providers, fragments and AndroidManifest.xml.
 Activity
An activity is a class that represents a single screen.
It is like a Frame in AWT.
 View
A view is the UI element such as button, label, text field etc.
Anything that you see is a view.
 Intent
Intent is used to invoke components. It is mainly used to:
• Start the service
• Launch an activity
• Display a web page
• Display a list of contacts
• Broadcast a message
• Dial a phone call etc.
• For example, write the following code to view the
webpage.
Intent intent=new Intent (Intent.ACTION_VIEW);
intent.setData(Uri.parse("http://www.javatpoint.com"));
startActivity(intent);
Service
• Service is a background process that can run for a long time.
• There are two types of services local and remote.
• Local service is accessed from within the application
whereas remote service is accessed remotely from other
applications running on the same device.
Content Provider
• Content Providers are used to share data between the
applications.
• Fragment
• Fragments are like parts of activity.
• An activity can display one or more fragments on the screen
at the same time.
AndroidManifest.xml
• It contains information about activities, content providers,
permissions etc.
• It is like the web.xml file in Java EE.
Android Virtual Device (AVD)
• It is used to test the android application without the need
for mobile or tablet etc.
• It can be created in different configurations to emulate
different types of real devices.
Android Activity Lifecycle
• Activity is one of the building blocks of Android OS.
• Activity is a screen that user interact with.
• Every Activity in android has lifecycle like created,
started, resumed, paused, stopped or destroyed.
• Activity is a class pre-written in Java Programming. An
activity is the single screen in android. It is like
window or frame of Java.
Android Activity Lifecycle methods
The 7 lifecycle methods of Activity describes how activity will
behave at different states.
•onCreate()
•onStart()
•onResume()
•onPause()
•onStop()
•onRestart()
•onDestroy
Android Activity Lifecycle methods
•onCreate() – Called when the activity is first created
•onStart() – Called just after it’s creation or by restart
method after onStop(). Here Activity start becoming visible
to user
•onResume() – Called when Activity is visible to user and
user can interact with it
•onPause() – Called when Activity content is not visible
because user resume previous activity
Android Activity Lifecycle methods
•onStop() – Called when activity is not visible to user
because some other activity takes place of it
•onRestart() – Called when user comes on screen or resume
the activity which was stopped
•onDestroy – Called when Activity is not in background
20IT601PE - Mobile Application Development PPT.pdf
20IT601PE - Mobile Application Development PPT.pdf
20IT601PE - Mobile Application Development PPT.pdf
20IT601PE - Mobile Application Development PPT.pdf
20IT601PE - Mobile Application Development PPT.pdf
20IT601PE - Mobile Application Development PPT.pdf
EXAMPLE
Following is the content of the modified main activity
file src/com.example.helloworld/MainActivity.java.
This file includes each of the fundamental life cycle
methods.
The Log.d() method has been used to generate log
messages −
package com.example.helloworld;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
public class MainActivity extends Activity {
String msg = "Android : ";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(msg, "The onCreate() event"); }
/** Called when the activity is about to become visible. */ @Override
protected void onStart() {
super.onStart();
Log.d(msg, "The onStart() event"); }
/** Called when the activity has become visible. */
@Override
protected void onResume() {
super.onResume();
Log.d(msg, "The onResume() event"); }
/** Called when another activity is taking focus. */
@Override
protected void onPause() {
super.onPause();
Log.d(msg, "The onPause() event"); }
/** Called when the activity is no longer visible. */
@Override
protected void onStop() {
super.onStop();
Log.d(msg, "The onStop() event"); }
/** Called just before the activity is destroyed. */
@Override
public void onDestroy() {
super.onDestroy();
Log.d(msg, "The onDestroy() event");
} }
ANDROID DEVELOPMENT TOOLS
• Android Development Tools (ADT) is a plug-in for the
Eclipse IDE that is designed to give you a powerful,
integrated environment in which to build Android
applications.
• ADT is the Android Developer Tools plug-in for Eclipse.
• ADT is about the useful code stuff: for example the libraries,
packages.
• The ADT plug-in for Eclipse uses the SDK tools as part of
its work.
ADT vs Android SDK
• The Android SDK contains the tools and
related files necessary to build an Android
application.
• SDK is actually about the tools: for example
Debugging.
Android Development Tools (ADT)
ADT plug-in incorporates many of the tools into the
Eclipse IDE, where you can access them from the DDMS
perspective, including the following:
Android Virtual Device and SDK Managers
Android Emulator
Dalvik Debug Monitoring Service (DDMS)
Android Debug Bridge (ADB)
Android Asset Packaging Tool (AAPT)
SQLite3
MkSDCard
Android Virtual Device and SDK Managers
• Used to create and manage AVDs and to download
SDK packages, respectively.
• The AVD hosts an Emulator running on a particular
build of Android,
• It specify the supported SDK version, screen
resolution, amount of SD card storage available, and
available hardware capabilities (such as touchscreens
and GPS).
Android Emulator
• Use the Emulator to test and debug your Android
applications
Dalvik Debug Monitoring Service (DDMS)
• Use the DDMS to monitor and control the Emulators on
which you’re debugging your applications.
Android Debug Bridge (ADB)
• A client-server application that provides a link to virtual and
physical devices. It lets you copy files, install compiled
application packages (.apk), and run shell commands.
Android Asset Packaging Tool (AAPT)
• Constructs the distributable Android package fi les (.apk).
SQLite3
• A database tool that you can use to access the SQLite
database fi les created and used by Android.
MkSDCard
• Creates an SD card disk image that can be used by the
Emulator to simulate an external storage card.
Creating an Applications and Activities
• Used to create and manage AVDs and to download
SDK packages, respectively.
• The AVD hosts an Emulator running on a particular
build of Android,
• It specify the supported SDK version, screen
resolution, amount of SD card storage available, and
available hardware capabilities (such as touchscreens
and GPS).
AndroidManifest.xml file in android
• The AndroidManifest.xml file contains
information of your package, including
components of the application such as
activities, services, broadcast receivers,
content providers etc.
• It is responsible to protect the application to
access any protected parts by providing the
permissions.
Elements of the AndroidManifest.xml file
• <manifest>
• manifest is the root element of the
AndroidManifest.xml file. It has package attribute
that describes the package name of the activity
class.
• <application>
• application is the subelement of the manifest. It
includes the namespace declaration. This
element contains several subelements that
declares the application component such as
activity etc.
• The commonly used attributes are of this
element are icon, label, theme etc.
• android:icon represents the icon for all the
android application components.
• android:label works as the default label for all the
application components.
• android:theme represents a common theme for
all the android activities.
20IT601PE - Mobile Application Development PPT.pdf
20IT601PE - Mobile Application Development PPT.pdf
20IT601PE - Mobile Application Development PPT.pdf
20IT601PE - Mobile Application Development PPT.pdf
20IT601PE - Mobile Application Development PPT.pdf
20IT601PE - Mobile Application Development PPT.pdf
20IT601PE - Mobile Application Development PPT.pdf
20IT601PE - Mobile Application Development PPT.pdf
20IT601PE - Mobile Application Development PPT.pdf
20IT601PE - Mobile Application Development PPT.pdf
20IT601PE - Mobile Application Development PPT.pdf
20IT601PE - Mobile Application Development PPT.pdf
20IT601PE - Mobile Application Development PPT.pdf
20IT601PE - Mobile Application Development PPT.pdf
20IT601PE - Mobile Application Development PPT.pdf
20IT601PE - Mobile Application Development PPT.pdf
20IT601PE - Mobile Application Development PPT.pdf
20IT601PE - Mobile Application Development PPT.pdf
20IT601PE - Mobile Application Development PPT.pdf
20IT601PE - Mobile Application Development PPT.pdf
20IT601PE - Mobile Application Development PPT.pdf
20IT601PE - Mobile Application Development PPT.pdf
20IT601PE - Mobile Application Development PPT.pdf
20IT601PE - Mobile Application Development PPT.pdf
20IT601PE - Mobile Application Development PPT.pdf
20IT601PE - Mobile Application Development PPT.pdf
20IT601PE - Mobile Application Development PPT.pdf
Intent
Intent is used to invoke components. It is mainly used to:
 Start the service
 Launch an activity
 Display a web page
 Display a list of contacts
 Broadcast a message
 Dial a phone call etc.
Exploring Intent objects
Object
Intent
LabeledIntent
Intent
• Android Intent is the message that is passed between
components such as activities, content providers,
broadcast receivers, services etc.
• It is generally used with startActivity() method to invoke
activity, broadcast receivers etc.
• The dictionary meaning of intent is intention or purpose.
So, it can be described as the intention to do action.
• The LabeledIntent is the subclass of android.content.Intent
class.
• Intent Types
• There are two types of intents in android: implicit and
explicit.
1) Implicit Intent
• Implicit Intent doesn't specify the component. In
such case, intent provides information of available
components provided by the system that is to be
invoked.
• For example, you may write the following code to view
the webpage.
• Intent intent=new Intent(Intent.ACTION_VIEW);
• intent.setData(Uri.parse("http://www.javatpoint.com"));
• startActivity(intent);
2) Explicit Intent
• Explicit Intent specifies the component. In such case,
intent provides the external class to be invoked.
Intent i = new Intent(getApplicationContext(),
ActivityTwo.class);
startActivity(i);
• Android Implicit Intent Example
• Let's see the simple example of implicit intent that displays a web page.
• activity_main.xml
• File: activity_main.xml
• <RelativeLayout
xmlns:androclass="http://schemas.android.com/apk/res/android"
• xmlns:tools="http://schemas.android.com/tools"
• android:layout_width="match_parent"
• android:layout_height="match_parent"
• tools:context=".MainActivity" >
• <EditText
• android:id="@+id/editText1"
• android:layout_width="wrap_content"
• android:layout_height="wrap_content"
• android:layout_alignParentTop="true"
• android:layout_centerHorizontal="true"
• android:layout_marginTop="44dp"
• Android Implicit Intent Example
• android:ems="10" />
• <Button
• android:id="@+id/button1"
• android:layout_width="wrap_content"
• android:layout_height="wrap_content"
• android:layout_below="@+id/editText1"
• android:layout_centerHorizontal="true"
• android:layout_marginTop="54dp"
• android:text="Visit" />
• </RelativeLayout>
Activity class
File: MainActivity.java
package org.sssit.implicitintent;
import android.net.Uri;
import android.widget.EditText;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditTexteditText1=(EditText)findViewById(R.id.editText1);
Button button1=(Button)findViewById(R.id.button1);
• button1.setOnClickListener(new OnClickListener() {
• @Override
• public void onClick(View arg0) {
• String url=editText1.getText().toString();
• Intent intent=new Intent(Intent.ACTION_VIEW,Uri.parse(url));
• startActivity(intent);
• } }); } }
20IT601PE - Mobile Application Development PPT.pdf
Activity class
File: MainActivity.java
package org.sssit.implicitintent;
import android.net.Uri;
import android.widget.EditText;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText
editText1=(EditText)findViewById(R.id.editText1);
Button button1=(Button)findViewById(R.id.button1);
Drawable Resources:
• drawable/
• For bitmap files (PNG, JPEG, or GIF), 9-Patch image files,
and
• XML files that describe Drawable shapes or Drawable
objects that
• contain multiple states (normal, pressed, or focused).
• res — This folder contains all the resources used in your
application. It also contains a few other subfolders:
drawable-<resolution>, layout, and values.
Android multiple screen: Screen Density
• We considered only the screen size but as we said earlier
there are different densities too.
• Density affects primary the images so an image could be
the right size one a screen device and looks too small in
another device with more density.
• So we have to consider this problem.
Android multiple screen: Screen Density
Density Android name
Small around 120dpi (ldpi)
Normal around 160dpi (mdpi)
High around 240dpi (hdpi)
x-High around 320dpi (xhdpi)
20IT601PE - Mobile Application Development PPT.pdf
Resource
Type
Directory Filename XML Tag
SimpleDrawables /res/values/ drawables.xml <drawable>
Graphics
Frame-by-Frame
Animations
/res/drawable/
/res/drawable/
Examples include
icon.png logo.jpg
Examples include
sequence1.xml
sequence2.xml
Supported
graphics files
or drawable
definition XML
files such as
shapes.
<animation-list>,
<item>
Option Menu with Icon
You need to have icon images inside the res/drawable
directory. The android:icon element is used to display
the icon on the option menu. You can write the string
information in the strings.xml file. But we have written
it inside the menu_main.xml file.
Option Menu with Icon
File: menu_main.xml
<menu
xmlns:androclass="http://schemas.android.com/apk/res/android"
>
<item android:id="@+id/item1"
android:icon="@drawable/add"
android:title="Item 1"/>
<item android:id="@+id/item2"
android:icon="@drawable/minus"
android:title="Item 2"/>
<item android:id="@+id/item3"
android:icon="@drawable/delete"
android:title="Item 3"/>
</menu>
20IT601PE-
MOBILE APPLICATION DEVELOPMENT
III Year / VI Semester
UNIT II
USE INTERFACE TOOLS
Creating user interface – Views - Creating
views – Layouts – Drawable resources –
Resolution and density independence – Menus –
Intents – Adapters – Using Internet resources –
Dialogs
Creating User Interface
The role of the UI is to display the application data on the
screen and also to serve as the primary point of user interaction.
User Interface (UI) design in Android is a graphical
representation of views displayed on a smartphone or tablet. It
allows users to interact with the features, functions, and contents
of the application.
To design UI, you need no prior programming knowledge,
although it is nice to have web developing skills or
programming skills.
Components used for Android application
Main Action Bar (MAR)
Split Action Bar (SAB)
Content Area
Steps to follow in UI Design
• Download Android studio from your browser.
• Install Android studio.
• Open Android studio.
• Create a new project and select project type.
• Give it a name of your choice.
• Click on the resources folder.
• Click on the layout folder and begin to design your UI.
Views components
Views are used to customize User Interface (UI) design. A
view is considered a building block for a proper User Interface
created from the view class.
A view can also be defined as a small rectangular box in
Android development that responds to the user inputs, for
example, buttons, checkboxes, etc.
Views components
View group is an invisible container of other views, such as
child view and other view groups.
This view class is a super class of all the GUI components in
Android.
Views play a key role in the development of an application
because you need settings present in the application, e.g.,color,
style, themes, etc.
A simple UI Design
Layout as a subclass of View group
The Layout defines the visual structures of the UI of user
application.
All elements in the layout are built using a hierarchy of
views and view group object.
The layout can be declared through a programming
language, or through a simple XML layout file located in the
resource layout folder of any project you work on.
Layout
Layouts are kept in the folder called resources. Android studio
creates a default XML layout file in the resources layout folder
that is extremely useful if you know the basic at the time of
compiling.
20IT601PE - Mobile Application Development PPT.pdf
Advantages of XML Layout
It is an immensely popular and widely used format.
It helps provide the UI component from the logic, which in
turn provides the flexibility to change one component without
affecting the other.
It is much easier to generate than writing direct code. It allows
an easier drag and drop to generate interfaces for the Android
application.
Types of layout
Linear layout: It is used to arrange views in a single column or
row. It is further divided into a vertical or horizontal linear layout.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a Button" />
</LinearLayout>
Types of layout
Frame layout: It is a placeholder on the screen used to display a
single screen.
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a Button" />
</FrameLayout>
Types of layout
Relative layout: It enables you to specify how child views are
positioned to each other.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a Button" />
</RelativeLayout>
Types of layout
Constraint layout: It provides you with adaptable and flexible
ways to create views for your applications.
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas
.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent“
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a TextView" />
</androidx.constraintlayout.widget.ConstraintLayout>
Intent
Intent is used to invoke components. It is mainly used to:
 Start the service
 Launch an activity
 Display a web page
 Display a list of contacts
 Broadcast a message
 Dial a phone call etc.
Exploring Intent objects
Object
Intent
LabeledIntent
Intent
• Android Intent is the message that is passed between
components such as activities, content providers,
broadcast receivers, services etc.
• It is generally used with startActivity() method to invoke
activity, broadcast receivers etc.
• The dictionary meaning of intent is intention or purpose.
So, it can be described as the intention to do action.
• The LabeledIntent is the subclass of android.content.Intent
class.
• Intent Types
• There are two types of intents in android: implicit and
explicit.
1) Implicit Intent
• Implicit Intent doesn't specify the component. In
such case, intent provides information of available
components provided by the system that is to be
invoked.
• For example, you may write the following code to view
the webpage.
• Intent intent=new Intent(Intent.ACTION_VIEW);
• intent.setData(Uri.parse("http://www.javatpoint.com"));
• startActivity(intent);
2) Explicit Intent
• Explicit Intent specifies the component. In such case,
intent provides the external class to be invoked.
Intent i = new Intent(getApplicationContext(),
ActivityTwo.class);
startActivity(i);
• Android Implicit Intent Example
• Let's see the simple example of implicit intent that displays a web page.
• activity_main.xml
• File: activity_main.xml
• <RelativeLayout
xmlns:androclass="http://schemas.android.com/apk/res/android"
• xmlns:tools="http://schemas.android.com/tools"
• android:layout_width="match_parent"
• android:layout_height="match_parent"
• tools:context=".MainActivity" >
• <EditText
• android:id="@+id/editText1"
• android:layout_width="wrap_content"
• android:layout_height="wrap_content"
• android:layout_alignParentTop="true"
• android:layout_centerHorizontal="true"
• android:layout_marginTop="44dp"
• Android Implicit Intent Example
• android:ems="10" />
• <Button
• android:id="@+id/button1"
• android:layout_width="wrap_content"
• android:layout_height="wrap_content"
• android:layout_below="@+id/editText1"
• android:layout_centerHorizontal="true"
• android:layout_marginTop="54dp"
• android:text="Visit" />
• </RelativeLayout>
Activity class
File: MainActivity.java
package org.sssit.implicitintent;
import android.net.Uri;
import android.widget.EditText;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditTexteditText1=(EditText)findViewById(R.id.editText1);
Button button1=(Button)findViewById(R.id.button1);
• button1.setOnClickListener(new OnClickListener() {
• @Override
• public void onClick(View arg0) {
• String url=editText1.getText().toString();
• Intent intent=new Intent(Intent.ACTION_VIEW,Uri.parse(url));
• startActivity(intent);
• } }); } }
20IT601PE - Mobile Application Development PPT.pdf
Activity class
File: MainActivity.java
package org.sssit.implicitintent;
import android.net.Uri;
import android.widget.EditText;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText
editText1=(EditText)findViewById(R.id.editText1);
Button button1=(Button)findViewById(R.id.button1);
Drawable Resources:
• drawable/
• For bitmap files (PNG, JPEG, or GIF), 9-Patch image files,
and
• XML files that describe Drawable shapes or Drawable
objects that
• contain multiple states (normal, pressed, or focused).
• res — This folder contains all the resources used in your
application. It also contains a few other subfolders:
drawable-<resolution>, layout, and values.
Android multiple screen: Screen Density
• We considered only the screen size but as we said earlier
there are different densities too.
• Density affects primary the images so an image could be
the right size one a screen device and looks too small in
another device with more density.
• So we have to consider this problem.
Android multiple screen: Screen Density
Density Android name
Small around 120dpi (ldpi)
Normal around 160dpi (mdpi)
High around 240dpi (hdpi)
x-High around 320dpi (xhdpi)
20IT601PE - Mobile Application Development PPT.pdf
Resource
Type
Directory Filename XML Tag
SimpleDrawables /res/values/ drawables.xml <drawable>
Graphics
Frame-by-Frame
Animations
/res/drawable/
/res/drawable/
Examples include
icon.png logo.jpg
Examples include
sequence1.xml
sequence2.xml
Supported
graphics files
or drawable
definition XML
files such as
shapes.
<animation-list>,
<item>
Option Menu with Icon
You need to have icon images inside the res/drawable
directory. The android:icon element is used to display
the icon on the option menu. You can write the string
information in the strings.xml file. But we have written
it inside the menu_main.xml file.
Option Menu with Icon
File: menu_main.xml
<menu
xmlns:androclass="http://schemas.android.com/apk/res/android"
>
<item android:id="@+id/item1"
android:icon="@drawable/add"
android:title="Item 1"/>
<item android:id="@+id/item2"
android:icon="@drawable/minus"
android:title="Item 2"/>
<item android:id="@+id/item3"
android:icon="@drawable/delete"
android:title="Item 3"/>
</menu>
 Activity
An activity is a class that represents a single screen.
It is like a Frame in AWT.
 View
A view is the UI element such as button, label, text field etc.
Anything that you see is a view.
 Intent
Intent is used to invoke components. It is mainly used to:
• Start the service
• Launch an activity
• Display a web page
• Display a list of contacts
• Broadcast a message
• Dial a phone call etc.
• For example, write the following code to view the
webpage.
Intent intent=new Intent (Intent.ACTION_VIEW);
intent.setData(Uri.parse("http://www.javatpoint.com"));
startActivity(intent);
Service
• Service is a background process that can run for a long time.
• There are two types of services local and remote.
• Local service is accessed from within the application
whereas remote service is accessed remotely from other
applications running on the same device.
Content Provider
• Content Providers are used to share data between the
applications.
• Fragment
• Fragments are like parts of activity.
• An activity can display one or more fragments on the screen
at the same time.
AndroidManifest.xml
• It contains information about activities, content providers,
permissions etc.
• It is like the web.xml file in Java EE.
Android Virtual Device (AVD)
• It is used to test the android application without the need
for mobile or tablet etc.
• It can be created in different configurations to emulate
different types of real devices.
• IMAGES
• public abstract class Image extends Object implements
AutoCloseable
• java.lang.Object
• ↳ android.media.Image
• A single complete image buffer to use with a media
source such as a MediaCodec or a CameraDevice.
• This class allows for efficient direct application access to
the pixel data of the Image through one or more
ByteBuffers.
• Each buffer is encapsulated in a Plane that describes the
layout of the pixel data in that plane.
• Due to this direct access, and unlike the Bitmap class,
Images are not directly usable as UI resources.
• MENU
• In android, Options Menu is a primary
collection of menu items for an activity and it
is useful to implement
• actions that have a global impact on the app,
such as Settings, Search, etc.
• In case, if we define items for the options
menu in both activity or fragment, then those
items will be combine and display in UI.
20IT601PE - Mobile Application Development PPT.pdf
20IT601PE - Mobile Application Development PPT.pdf
20IT601PE - Mobile Application Development PPT.pdf
20IT601PE - Mobile Application Development PPT.pdf
Adapter
In Android, Adapter is a bridge between UI component
and data source that helps us to fill data in UI component.
It holds the data and send the data to an Adapter view
then view can takes the data from the adapter view and
shows the data on different views like as ListView,
GridView, Spinner etc.
For more customization in Views we uses the base
adapter or custom adapters.
Conceptual Diagram of Adapter:
Adapters In Android:
There are the some commonly used Adapter in Android used to fill the
data in the UI components.
BaseAdapter – It is parent adapter for all other adapters
ArrayAdapter – It is used whenever we have a list of single items
which is backed by an array
Custom ArrayAdapter – It is used whenever we need to display a
custom list
SimpleAdapter – It is an easy adapter to map static data to views
defined in your XML file
Custom SimpleAdapter – It is used whenever we need to display a
customized list and needed to access the child items of the list or
grid
1. BaseAdapter In Android:
BaseAdapter is a common base class of a general
implementation of an Adapter that can be used in ListView,
GridView, Spinner etc.
Whenever we need a customized list in a ListView or
customized grids in a GridView we create our own adapter and
extend base adapter in that.
Base Adapter can be extended to create a custom Adapter for
displaying a custom list item. ArrayAdapter is also an
implementation of BaseAdapter.
Custom Adapter code which extends the BaseAdapter in that:
public class CustomAdapter extends BaseAdapter {
@Override
public int getCount() {
return 0; }
@Override
public Object getItem(int i) {
return null; }
@Override
public long getItemId(int i) {
return 0; }
@Override
public View getView(int i, View view, ViewGroup
viewGroup) { return null; }
2. ArrayAdapter In Android:
Whenever we have a list of single items which is backed by an
Array, we can use ArrayAdapter. For instance, list of phone
contacts, countries or names.
ArrayAdapter(Context context, int resource, int
textViewResourceId, T[] objects)
3. Custom ArrayAdapter In Android:
ArrayAdapter is also an implementation of BaseAdapter, so if
we want more customization then we can create a custom
adapter and extend ArrayAdapter in that.
Below Custom adapter class MyAdapter extends
ArrayAdapter in that:
Below Custom adapter class MyAdapter extends ArrayAdapter in that:
public class MyAdapter extends ArrayAdapter
{
public MyAdapter(Context context, int resource, int
textViewResourceId, List objects)
{ super(context, resource, textViewResourceId, objects);
}
@Override
public int getCount()
{
return super.getCount(); }
@Override
public View getView(int position, View convertView, ViewGroup
parent)
{
return super.getView(position, convertView, parent);
} }
4. SimpleAdapter In Android:
In Android SimpleAdapter is an easy Adapter to map static
data to views defined in an XML file(layout).
In Android we can specify the data backing to a list as an
ArrayList of Maps(i.e. hashmap or other). Each entry in a
ArrayList is corresponding to one row of a list.
The Map contains the data for each row. Here we also specify
an XML file(custom list items file) that defines the views which
is used to display the row, and a mapping from keys in the Map
to specific views.
SimpleAdapter code in Android:
SimpleAdapter (Context context, List<? extends Map<S
tring, ?>> data, int resource, String[] from, int[] to)
Adapter Example In Android Studio:
Below is the Android Studio example which show the use of the
Adapter in Android.
In this example we display a list of fruits names with images by
using SimpleAdapter and whenever user click on a list item the
fruit’s name displayed in a Toast.
20IT601PE - Mobile Application Development PPT.pdf
Android Listview in Java with Example
A ListView is a type of AdapterView that displays a vertical list
of scroll-able views and each view is placed one below the
other.
For displaying the items in the list method setAdaptor() is
used. setAdaptor() method conjoins an adapter with the list.
XML Attributes of ListView
Attribute Description
android:divider A color or drawable to separate list items.
android:dividerHeight Divider’s height.
android:entries
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.
android:headerDividersEnabled
When set to false, the ListView will not
draw the divider before each header view.
Create an android application that will display a list of
tutorials available in GeeksforGeeks portal
Step 1: Create a new project
1.Click on File, then New => New Project.
2.Choose “Empty Activity” for the project template.
3.Select language as Java.
4.Select the minimum SDK as per your need.
Step 2: Modify activity_main.xml file
Add a ListView in the activity_main.xml file.
How to add a ListView in an Android App
How to add a ListView in an Android App
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/and
roid"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
Step 3: Modify MainActivity.java file
public ArrayAdapter (Context context, int Resource, T[ ] objects)
20IT601PE - Mobile Application Development PPT.pdf
20IT601PE - Mobile Application Development PPT.pdf
• DIALOG
• A dialog is a small window that prompts the user to make
a decision or enter additional information.
• A dialog does not fill the screen and is normally used for
modal events that require users to take an action before
they can proceed.
• The Dialog class is the base class for dialogs, but you
should avoid instantiating Dialog directly. Instead, use
one of the following subclasses:
• AlertDialog : A dialog that can show a title, up to three
buttons, a list of selectable items, or a custom layout.
• DatePickerDialog or TimePickerDialog : A dialog with a
pre-defined UI that allows the user to select a date or
time.
20IT601PE - Mobile Application Development PPT.pdf
Saving Simple Application Data – Creating and
saving preferences – Preferences activity – Saving activity
state - Loading files – File management tools - Introducing
Android databases –SQLite – Cursors and content Values –
Working with SQlite Databases – Creating and Using
Content providers – Native Android content Providers
• SQLite Database in Android.
• Database - Package
• The main package is android.database.sqlite
that contains the classes to manage your own
databases
• 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.
SQLite is lightweight process.
No connectivity is needed.
For example: In order to access this database,
you don't need to establish any kind of
connections for it like JDBC,ODBC e.t.c.
20IT601PE - Mobile Application Development PPT.pdf
 In order to create a database you just need to call this method
openOrCreateDatabase with your database name and mode as a
parameter.
 It returns an instance of SQLite database which you have to
receive in your own object.
 Its syntax is given below
 SQLiteDatabase mydatabase = OpenOrCreateDatabase("your
database name",MODE_PRIVATE,null);
 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
TutorialsPoint(Username VARCHAR, Password VARCHAR);");
 mydatabase.execSQL("INSERT INTO TutorialsPoint
VALUES('admin','admin');");
 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.
 Cursor resultSet = mydatbase.rawQuery("Select * from
MRCET",null);
 resultSet.moveToFirst();
 String username = resultSet.getString(0);
 String password = resultSet.getString(1);
 For managing all the operations related to the database , an
helper class has been given and is called SQLiteOpenHelper.
 It automatically manages the creation and update of the
database.
 To experiment with this example, you need to run this on
an actual device on which camera is supported.
 public class DBHelper extends SQLiteOpenHelper {
 public DBHelper(){
 super(context,DATABASE_NAME,null,1);
 }
 public void onCreate(SQLiteDatabase db) {}
 public void onUpgrade(SQLiteDatabase database, int
oldVersion, int newVersion) {}
 }
 For managing all the operations related to the database , an
helper class has been given and is called SQLiteOpenHelper.
 It automatically manages the creation and update of the
database.
 To experiment with this example, you need to run this on
an actual device on which camera is supported.
Steps Description
You will use Android studio to create an Android application under a
package com.example.dinesh.myapplication.
Modify src/MainActivity.java file to get references of all the XML
components and populate
the contacts on listView.
Create new src/DBHelper.java that will manage the database work
Create a new Activity as DisplayContact.java that will display the
contact on the screen
 Demonstrating the use of SQLite Database.
 It creates a basic contacts applications that allows
insertion, deletion and modification of contacts.
20IT601PE - Mobile Application Development PPT.pdf
20IT601PE - Mobile Application Development PPT.pdf
20IT601PE - Mobile Application Development PPT.pdf
20IT601PE - Mobile Application Development PPT.pdf
20IT601PE - Mobile Application Development PPT.pdf
20IT601PE - Mobile Application Development PPT.pdf
20IT601PE - Mobile Application Development PPT.pdf
20IT601PE - Mobile Application Development PPT.pdf
20IT601PE - Mobile Application Development PPT.pdf
HARDWARE SENSORS AND LOCATION-
BASED SERVICES
Using Sensors and the Sensor Manager–
Monitoring a Device’s Movement and Orientation
–Introducing the Environmental Sensors– Using
Location-Based Services– Selecting a Location
Provider –Finding Your Current Location
In Android devices, there are various built-in
sensors that can be used to measure the
orientation, motions, and various other kinds of
environmental conditions.
 Hardware sensors are physical components that are
present in Android devices.
 They can directly measure various properties like field
strength, acceleration, etc according to the types of the
sensors and after measuring the environment
properties they can send the data to Software Sensors.
 To express data values or to collect data, the sensors in Android
devices uses a 3-axis coordinate system i.e. you will be having
X, Y, and Z-axis.
 The following figure depicts the position of various axis used in
sensors.
 Motion Sensors: The sensors that are responsible for measuring
or identifying the shakes and tilts of your Android devices are
called Motion sensors.
 Position Sensors: As the name suggests, the Position sensors are
used to determine the position of an Android device.
Magnetometers sensors is the example of Position sensors.
 Environmental Sensors: Environmental properties like
temperature, pressure, humidity, etc are identified with the help of
Environmental sensors. Some of the examples of Environmental
sensors are thermometer, photometer, barometer, etc.
 The Sensor Manager is used to manage the sensor hardware
available on Android devices.
 Use getSystemService to return a reference to the Sensor
Manager Service, as shown in the following snippet:
String service_name = Context.SENSOR_SERVICE;
SensorManager sensorManager =
(SensorManager)getSystemService(service_name);
 Sensor.TYPE_TEMPERATURE. This is a thermometer that returns the
temperature in degrees Celsius; the temperature returned will be the ambient
room temperature.
 Sensor.TYPE_ACCELEROMETER— A three-axis accelerometer that returns
the current acceleration along three axes in m/s2 (meters per second)
 Sensor.TYPE_GRAVITY — A three-axis gravity sensor that returns the current
direction and magnitude of gravity along three axes in m/s2.
 Sensor.TYPE_LINEAR_ACCELERATION: A three-axis linear acceleration
Sensor that returns the acceleration, not including gravity, along three axes in
m/s2.
 Sensor.TYPE_GYROSCOPE — A three-axis gyroscope that returns the rate of
device rotation along three axes in radians/second.
 Sensor.TYPE_TEMPERATURE. This is a thermometer that returns the
temperature in degrees Celsius; the temperature returned will be the ambient
room temperature.
 Sensor.TYPE_ACCELEROMETER— A three-axis accelerometer that returns
the current acceleration along three axes in m/s2 (meters per second)
 Sensor.TYPE_GRAVITY — A three-axis gravity sensor that returns the current
direction and magnitude of gravity along three axes in m/s2.
 Sensor.TYPE_LINEAR_ACCELERATION: A three-axis linear acceleration
Sensor that returns the acceleration, not including gravity, along three axes in
m/s2.
 Sensor.TYPE_GYROSCOPE — A three-axis gyroscope that returns the rate of
device rotation along three axes in radians/second.
 To find every Sensor available on the host platform, use
getSensorList on the Sensor Manager, passing in
Sensor.TYPE_ALL:
 List<Sensor>allSensors =
sensorManager.getSensorList(Sensor.TYPE_ALL);
 To find a list of all the available Sensors of a particular type, use
getSensorList, specifying the type of Sensor you require, as shown
in the following code that returns all the available gyroscopes:
 List<Sensor> gyroscopes =
sensorManager.getSensorList(Sensor.TYPE_GYROSCOPE);
 The following snippet returns the default pressure sensor:
 Sensor defaultBarometer =
sensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE);
 To monitor a Sensor, implement a SensorEventListener, using the
onSensorChanged method to monitor Sensor values, and
onAccuracyChanged to react to changes in a Sensor’s accuracy.
Example: Sensor Event Listener skeleton code
finalSensorEventListenermySensorEventListener = new
SensorEventListener() {
public void onSensorChanged(SensorEventsensorEvent) {
// TODO Monitor Sensor changes.
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO React to a change in Sensor accuracy.
}
};
The SensorEvent parameter in the onSensorChanged method includes
the following four properties to describe each Sensor Event:
sensor — The Sensor object that triggered the event.
accuracy — The accuracy of the Sensor when the event occurred (low,
medium, high, or unreliable, as described in the next list).
values — A float array that contains the new value(s) observed. The
next section explains the values returned for each sensor type.
timestamp — The time (in nanoseconds) at which the Sensor Event
occurred.
20IT601PE - Mobile Application Development PPT.pdf
SMALL COMPUTING TECNOLOGY
Audio, Video Using the Camera – Using
Bluetooth – Managing Network and Internet
Connectivity - Managing Wi-Fi – Transferring
Data Using Wi-Fi Direct – Near Field
Communication.
 PLAYING AUDIO AND VIDEO
 Android 4.0.3 (API level 15) supports the following multimedia
formats for playback.
Audio
Image
Video
Network protocols for streaming media
Audio Image Video
 AAC LC/LTP (Advanced
Audio Coding)
 HE-AACv1 (AAC+)
 HE-AACv2 (Enhanced
AAC+)
 AMR-NB (Adaptive Multi
Rate)
 AMR-WB
 MP3
 MIDI
 JPEG
 PNG
 WEBP (on
devices running
Android 4.0 or
above)
 GIF
 BMP
 H.263
 H.264 AVC
 MPEG-4 SP
 VP8 (on devices
running Android
2.3.3 or above)
 Network protocols are supported for streaming
media:
RTSP (RTP, SDP)
HTTP/HTTPS progressive streaming
HTTP/HTTPS live streaming (on devices
running Android 3.0 or above)
 Playback of audio and video within Android applications is
handled primarily through the MediaPlayer class.
1. Initialize the Media Player with media to play.
2. Prepare the Media Player for playback.
3. Start the playback.
4. Pause or stop the playback prior to its completing.
5. The playback is complete.
 To stream Internet media using the Media Player, your
application must include the INTERNETpermission:
<uses-permission android:name=”android.permission.INTERNET”/>
 When you finish playback, call release on your Media Player
object to free the associated resources:
mediaPlayer.release();
 It can used as an application resource, play it from local files or
Content Providers, or stream it from a remote URL.
Initializing Audio Content for Playback
 Using the static create method, passing in the Activity Context and any
one of the following audio sources:
 A resource identifier (typically for an audio file stored in the res/raw
resource folder)
 A URI to a local file (using the file:// schema)
 A URI to an online audio resource (as a URL)
 A URI to a row within a Content Provider that returns an audio file
// Load an audio resource from a package resource.
MediaPlayer resourcePlayer = MediaPlayer.create(this, R.raw.my_audio);
// Load an audio resource from a local file.
MediaPlayer filePlayer = MediaPlayer.create(this,
Uri.parse(“file:///sdcard/localfile.mp3”));
// Load an audio resource from an online resource.
MediaPlayer urlPlayer = MediaPlayer.create(this,
Uri.parse(“http://site.com/audio/audio.mp3”));
// Load an audio resource from a Content Provider.
MediaPlayer contentPlayer = MediaPlayer.create(this,
Settings.System.DEFAULT_RINGTONE_URI);
 There are two alternatives for the playback of video content.
1. Using the VideoViewclass, encapsulates the creation of a Surface
and allocation and preparation of video content using a Media
Player.
2. Allows you to specify your own Surface and manipulate the
underlyingMedia Player instance directly.
 A video to play by calling its setVideoPath or setVideoURI
methods to specify the path to a local file, or the URI of either a
Content Provider or remote video stream:
final VideoView videoView =
(VideoView)findViewById(R.id.videoView);
// Assign a local file to play
videoView.setVideoPath(“/sdcard/mycatvideo.3gp”);
// Assign a URL of a remote video stream
videoView.setVideoUri(myAwesomeStreamingSource);
 Call start to begin playback of the associated media using:
mediaPlayer.start();
 Use the stop and pause methods to stop or pause playback,
respectively.
 It provides:
 getDuration method- to find the length of the media being
played.
 getCurrentPosition method- to find the playback position.
 seekTo method- to jump to a specific position in the media.
 import java.io.IOException;
 import android.app.Activity;
 import android.media.MediaPlayer;
 import android.os.Bundle;
 import android.util.Log;
 import android.view.SurfaceHolder;
 import android.view.SurfaceView;
 import android.view.View;
 import android.view.View.OnClickListener;
 import android.widget.Button;
public class SurfaceViewVideoViewActivity extends Activity
implements SurfaceHolder.Callback {
static final String TAG = “SurfaceViewVideoViewActivity”;
private MediaPlayer mediaPlayer;
public void surfaceCreated(SurfaceHolder holder) {
try {
mediaPlayer.setDisplay(holder);
public class SurfaceViewVideoViewActivity extends Activity
implements SurfaceHolder.Callback {
static final String TAG = “SurfaceViewVideoViewActivity”;
private MediaPlayer mediaPlayer;
public void surfaceCreated(SurfaceHolder holder) {
try {
mediaPlayer.setDisplay(holder);
mediaPlayer.setDataSource(“/sdcard/test2.3gp”);
mediaPlayer.prepare();
}
catch (IllegalArgumentException e) {
Log.e(TAG, “Illegal Argument Exception”, e);
} catch (IllegalStateException e) {
Log.e(TAG, “Illegal State Exception“, e);
} catch (SecurityException e) {
Log.e(TAG, “Security Exception“, e);
} catch (IOException e) {
Log.e(TAG, “IO Exception“, e);
}
}
// Create a new Media Player.
mediaPlayer = new MediaPlayer();
// Get a reference to the Surface View.
final SurfaceView surfaceView = (SurfaceView)findViewById(R.id.surfaceView);
// Configure the Surface View.
surfaceView.setKeepScreenOn(true);
// Connect a play button.
Button playButton = (Button)findViewById(R.id.buttonPlay);
playButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) { mediaPlayer.start(); } });
// Connect a pause button.
Button pauseButton = (Button)findViewById(R.id.buttonPause);
pauseButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) { mediaPlayer.pause(); } }
// Add a skip button.
Button skipButton = (Button)findViewById(R.id.buttonSkip);
skipButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mediaPlayer.seekTo(mediaPlayer.getDuration()/2);
} }
To ensure a consistent media control experience, Android
includes the MediaController — a standard control that provides the
common media control buttons.
MediaController mediaController = new MediaController(this);
mediaController.setMediaPlayer(new MediaPlayerControl() {
public boolean canPause() {
return true; }
public boolean canSeekBackward() {
return true; }
public boolean canSeekForward() {
return true;
}
public int getCurrentPosition() {
return mediaPlayer.getCurrentPosition(); }
public int getDuration() {
return mediaPlayer.getDuration(); }
public boolean isPlaying() {
return mediaPlayer.isPlaying(); }
public void pause() {
mediaPlayer.pause(); }
public void start() {
mediaPlayer.start(); }
Creating a Sound Pool preloads the audio tracks used by your application,
such as each level within a game, and optimizes their resource
management.
Specify the maximum number of concurrent streams to play.
It supports loading audio resources from an Asset File Descriptor,
package resource, file path, using a series of overloaded load methods.
int maxStreams = 10;
SoundPool sp = new SoundPool(maxStreams,
AudioManager.STREAM_MUSIC, 0);
int track1 = sp.load(this, R.raw.track1, 0);
int track2 = sp.load(this, R.raw.track2, 0);
int track3 = sp.load(this, R.raw.track3, 0);
Bluetooth is a communications protocol designed for short-range,
low-bandwidth peer-to-peer communications.
Using the Bluetooth APIs, you can search for, and connect to, other
Bluetooth devices within range.
By initiating a communications link using Bluetooth Sockets, you
can transmit and receive streams of data between devices from
within your applications.
The local Bluetooth device is controlled via the BluetoothAdapter class,
which represents the host Android device on which your application is
running.
For accessing the default Bluetooth Adapter:
BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
To read any of the local Bluetooth Adapter properties includes the BLUETOOTH
permission in your application manifest.
To modify any of the local device properties, the BLUETOOTH_ADMIN
permission is also required:
<uses-permission android:name=”android.permission.BLUETOOTH”/>
<uses-permission android:name=”android.permission.BLUETOOTH_ADMIN”/>
Use the isEnabled method to confirm the device is enabled, after which you can
access the Bluetooth Adapter’s friendly name and hardware address, using the
getName and getAddress methods, respectively:
if (bluetooth.isEnabled()) {
String address = bluetooth.getAddress();
String name = bluetooth.getName();
}
To find a more detailed description of the current Bluetooth Adapter state, use the
getStatemethod, which will return one of the following BluetoothAdapter constants:
 STATE_TURNING_ON
 STATE_ON
 STATE_TURNING_OFF
 STATE_OFF
Android Bluetooth communications APIs are wrappers around RFCOMM,
the Bluetooth radio frequency communications protocol.
RFCOMM supports RS232 serial communication over the Logical Link
Control and Adaptation Protocol (L2CAP) layer.
RFCOMM communication channel for bidirectional communications using
the following classes:
BluetoothServerSocket — Used to establish a listening socket for initiating
a link between devices. To establish a handshake, one device acts as a server
to listen for, and accept, incoming connection requests.
BluetoothSocket — Used to create a new client to connect to a listening
Bluetooth Server Socket.
Example: Listening for Bluetooth Socket connection requests
private BluetoothSocket transferSocket;
private UUID startServerSocket(BluetoothAdapter bluetooth) {
UUID uuid = UUID.fromString(“a60f35f0-b93a-11de-8a39-08002009c666”);
String name = “bluetoothserver”;
try {
final BluetoothServerSocket btserver = bluetooth.listenUsingRfcommWithServiceRecord(name,
uuid);
public void run() {
try {
// Block until client connection established.
BluetoothSocket serverSocket = btserver.accept();
// Start listening for messages.
listenForMessages(serverSocket);
}
catch (IOException e) {
Log.e(“BLUETOOTH”, “Server connection IO Exception”, e); } } }
BluetoothSocket class can be used on the client device to initiate a
communications channel from within your application to a listening
Bluetooth Server Socket.
It is also returned by the Bluetooth Server Socket Listener after a connection
to a client device has been established.
Create a client-side Bluetooth Socket by calling
createRfcommSocketToServiceRecord on a BluetoothDevice object that
represents the target remote server device.
To establish a Bluetooth Socket connection to a remote Bluetooth Device, the
following conditions must be true:
The remote device must be discoverable.
The remote device must be accepting connections through a Bluetooth
Server Socket.
The local and remote devices must be paired (bonded).
 private void connectToServerSocket(BluetoothDevice device,
UUID uuid) {
 try{
 BluetoothSocket clientSocket =
device.createRfcommSocketToServiceRecord(uuid);
 // Block until server connection accepted.
 clientSocket.connect();
 // Start listening for messages.
 listenForMessages(clientSocket);
 // Add a reference to the socket used to send messages.
 transferSocket = clientSocket;
 }
 catch (IOException e) {
 Log.e(“BLUETOOTH”, “Bluetooth client I/O Exception”, e);
 }}
 With the speed, reliability, and cost of Internet connectivity being
dependent on the network technology used (Wi-Fi, GPRS, 3G, LTE,
and so on).
 Android broadcasts Intents that allows to monitor changes in network
connectivity and offers APIs that provide control over network
settings and connections.
 Android networking is principally handled via the
ConnectivityManager, a Service that monitor the connectivity state,
set your preferred network connection, and manage connectivity
failover.
 It represents the Network Connectivity Service.
 It’s used to monitor the state of network connections, configure failover
settings, and control the network radios.
 To use the Connectivity Manager, application needs read and write
network state access permissions:
<uses-permission android:name=”android.permission.ACCESS_NETWORK_STATE”/>
<uses-permission android:name=”android.permission.CHANGE_NETWORK_STATE”/>
 To access the Connectivity Manager, use getSystemService, passing in
Context.CONNECTIVITY_SERVICE as the service name, as shown
below:
String service = Context.CONNECTIVITY_SERVICE;
ConnectivityManager connectivity = (ConnectivityManager)getSystemService(service);
Supporting User Preferences for Background Data Transfers
 To monitor changes in the background data setting, create and register a
new Broadcast Receiver that listens for this Broadcast Intent, as listed
below.
registerReceiver(
new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
boolean backgroundEnabled =
connectivity.getBackgroundDataSetting();
setBackgroundData(backgroundEnabled);
} },
new IntentFilter(
ConnectivityManager.ACTION_BACKGROUND_DATA_SETTIN
G_CHANGED)
);
Finding and Monitoring Network Connectivity
 The Connectivity Manager provides a high-level view of the available
network connections.
 The getActiveNetworkInfo method returns a NetworkInfo object that
includes details on the currently active network:
// Get the active network information.
NetworkInfo activeNetwork = connectivity.getActiveNetworkInfo();
Finding and Monitoring Network Connectivity
NetworkInfo activeNetwork = connectivity.getActiveNetworkInfo();
boolean isConnected =
((activeNetwork != null) &&(activeNetwork.isConnectedOrConnecting()));
boolean isWiFi = activeNetwork.getType() == ConnectivityManager.TYPE_WIFI;
 To monitor network connectivity, create a Broadcast Receiver that listens for
ConnectivityManager.CONNECTIVITY_ACTION Broadcast Intents as,
<receiver android:name=”.ConnectivityChangedReceiver” >
<intent-filter>
<action android:name=”android.net.conn.CONNECTIVITY_CHANGE”/>
</intent-filter>
</receiver>
 It represents the Android Wi-Fi Connectivity Service,
 It used to configure Wi-Fi network connections, manage the current
Wi-Fi connection and monitor changes in Wi-Fi connectivity.
 It describes how to use the WifiManager to monitor and control the
device’s Wi-Fi connectivity specifically.
 Access the Wi-Fi Manager using the getSystemService method,
passing in the Context.WIFI_SERVICE constant, as shown below:
String service = Context.WIFI_SERVICE;
WifiManager wifi = (WifiManager)getSystemService(service);
To Monitoring and changing Wi-Fi state
if (!wifi.isWifiEnabled())
if (wifi.getWifiState() != WifiManager.WIFI_STATE_ENABLING)
wifi.setWifiEnabled(true);
 Wifi Manager to manage the configured network settings and control
which networks to connect.
 Get a list of the current network configurations using
getConfiguredNetworks.
// Get a list of available configurations
List<WifiConfiguration> configurations = wifi.getConfiguredNetworks();
 To connect to a Wi-Fi network, need to create and register a configuration.
 Network configurations are stored as WifiConfiguration objects.
 The following is a non exhaustive list of some of the public fields
available for each Wi-Fi configuration:
 BSSID — The BSSID for an access point
 SSID — The SSID for a particular network
 networkId — A unique identifier used to identify this network
configuration on the current device
 priority — To use when ordering the list of potential access points to
connect to.
 status — The current status of this network connection, which will be one
of the following:
 WifiConfiguration.Status.ENABLED, WifiConfiguration.Status.DISABLED,
or
 WifiConfiguration.Status.CURRENT
 Wi-Fi Direct is a communications protocol designed for medium-
range, high-bandwidth peer-to-peer communications.
 By initiating a communications link using sockets, you can then
transmit and receive streams of data between supported devices
(including some printers, scanners, cameras, and televisions) and
between instances of your application running on different devices.
 To use Wi-Fi Direct, your application requires the
ACCESS_WIFI_STATE, CHANGE_WIFI_STATE, and
INTERNET permissions:
<uses-permission android:name=”android.permission.ACCESS_WIFI_STATE”/>
<uses-permission android:name=”android.permission.CHANGE_WIFI_STATE”/>
<uses-permission android:name=”android.permission.INTERNET”/>
 Wi-Fi Direct connections are initiated and managed using the
WifiP2pManager system service, which you canaccess using the
getSystemService method, passing in the
Context.WIFI_P2P_SERVICE constant:
wifiP2pManager=(WifiP2pManager)getSystemService(Context.
WIFI_P2P_SERVICE);
 private WifiP2pManager wifiP2pManager;
 private Channel wifiDirectChannel;
 private void initializeWiFiDirect() {
 wifiP2pManager =
(WifiP2pManager)getSystemService(Context.WIFI_P2P_SE
RVICE);
 wifiDirectChannel = wifiP2pManager.initialize(this,
getMainLooper(),
 new ChannelListener() {
 public void onChannelDisconnected() {
 initializeWiFiDirect();
 } }
 );
 }
 NFC is a contactless technology used to transmit small amounts of data
across short distances.
 NFC transfers can occur between two NFC-enabled devices, or between a
device and an NFC “tag.
 NFC messages are handled using the NFC Data Exchange Format
(NDEF).
 To read, write, or broadcast NFC messages, application requires the NFC
manifest permission:
<uses-permission android:name=”android.permission.NFC” />
 When an Android device is used to scan an NFC tag,
 System will decode the incoming payload using its own tag
dispatch system
 Analyzes the tag, categorizes the data
 Uses an Intent to launch an application to receive the data.
 NfcAdapter.ACTION_NDEF_DISCOVERED
 NfcAdapter.ACTION_TECH_DISCOVERED- This action is
broadcast when the NFC technology is known.
 NfcAdapter.ACTION_TAG_DISCOVERED- If a tag is received
from an unknown technology, it will be broadcast using this action.
 <activity android:name=”.BlogViewer”>
 <intent-filter>
 <action
android:name=”android.nfc.action.NDEF_DISCOVERED”/>
 <category
android:name=”android.intent.category.DEFAULT”/>
 <data android:scheme=”http”
 android:host=”blog.radioactiveyak.com”/>
 </intent-filter>
 </activity>

More Related Content

PPTX
Outstanding Improvement Award Outstanding Improvement Award
PPT
Android - Workshop By Secure-Net Technologies
PPTX
MAD unit 1.pptxi 8hv8yv8cy8c8ycy8c8yv8uvyv
PDF
android app development training report
PPTX
Getting started with android
PPTX
Android architecture
PDF
Ch1 hello, android
PPT
Introduction to android sessions new
Outstanding Improvement Award Outstanding Improvement Award
Android - Workshop By Secure-Net Technologies
MAD unit 1.pptxi 8hv8yv8cy8c8ycy8c8yv8uvyv
android app development training report
Getting started with android
Android architecture
Ch1 hello, android
Introduction to android sessions new

Similar to 20IT601PE - Mobile Application Development PPT.pdf (20)

PPTX
Android 1-intro n architecture
PPT
My androidpresentation
PPTX
UNIT-1 INTRODUCTION TO ANDROID [Autosaved].pptx
PDF
Android fundamentals and tutorial for beginners
DOCX
Unit 1-android-and-its-tools-ass
PDF
Android Workshop Part 1
PPT
UPDATED Application fundamentals lec 1 &2.ppt
PDF
Android : Architecture & Components
PPT
Chapter 1 Introduction to android.ppt pl
PPTX
18ITT61 - Introduction.pptx
PPT
Android Basics
PDF
Android and its feature
PDF
01 02 - introduction - adroid stack
PPTX
Android introduction
PPT
Mobile appliaction w android week 1 by osama
PPTX
architecture of android.pptx
DOC
document
PPTX
mobile-application_develop_android_MOD1.pptx
PDF
Consumer Electronics
PDF
Software training report
Android 1-intro n architecture
My androidpresentation
UNIT-1 INTRODUCTION TO ANDROID [Autosaved].pptx
Android fundamentals and tutorial for beginners
Unit 1-android-and-its-tools-ass
Android Workshop Part 1
UPDATED Application fundamentals lec 1 &2.ppt
Android : Architecture & Components
Chapter 1 Introduction to android.ppt pl
18ITT61 - Introduction.pptx
Android Basics
Android and its feature
01 02 - introduction - adroid stack
Android introduction
Mobile appliaction w android week 1 by osama
architecture of android.pptx
document
mobile-application_develop_android_MOD1.pptx
Consumer Electronics
Software training report
Ad

Recently uploaded (20)

PDF
The Final Stretch: How to Release a Game and Not Die in the Process.
PPTX
Cell Structure & Organelles in detailed.
PDF
01-Introduction-to-Information-Management.pdf
PDF
O7-L3 Supply Chain Operations - ICLT Program
PPTX
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
PDF
Pre independence Education in Inndia.pdf
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
PDF
Introduction-to-Social-Work-by-Leonora-Serafeca-De-Guzman-Group-2.pdf
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
Insiders guide to clinical Medicine.pdf
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
TR - Agricultural Crops Production NC III.pdf
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PDF
BÀI TẬP TEST BỔ TRỢ THEO TỪNG CHỦ ĐỀ CỦA TỪNG UNIT KÈM BÀI TẬP NGHE - TIẾNG A...
The Final Stretch: How to Release a Game and Not Die in the Process.
Cell Structure & Organelles in detailed.
01-Introduction-to-Information-Management.pdf
O7-L3 Supply Chain Operations - ICLT Program
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
Pre independence Education in Inndia.pdf
Abdominal Access Techniques with Prof. Dr. R K Mishra
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
Introduction-to-Social-Work-by-Leonora-Serafeca-De-Guzman-Group-2.pdf
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
human mycosis Human fungal infections are called human mycosis..pptx
Insiders guide to clinical Medicine.pdf
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Microbial disease of the cardiovascular and lymphatic systems
TR - Agricultural Crops Production NC III.pdf
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
BÀI TẬP TEST BỔ TRỢ THEO TỪNG CHỦ ĐỀ CỦA TỪNG UNIT KÈM BÀI TẬP NGHE - TIẾNG A...
Ad

20IT601PE - Mobile Application Development PPT.pdf

  • 2. UNIT I ANDROID OVERVIEW Introduction – Android SDK features – OHA – Development framework – Getting started – developing for android, mobile devices - ADT – Creating an applications and activities - Application manifest – Android Application Life Cycle – Understanding application priority - Externalizing resources – Android application class – Android Activities
  • 3. Introduction 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.
  • 5. Features of Android S.No. Feature & Description 1 Beautiful UI Android OS basic screen provides a beautiful and intuitive user interface. 2 Connectivity GSM/EDGE, IDEN, CDMA, EV-DO, UMTS, Bluetooth, Wi-Fi, LTE, NFC and WiMAX. 3 Storage SQLite, a lightweight relational database, is used for data storage purposes. 4 Media support H.263, H.264, MPEG-4 SP, AMR, AMR-WB, AAC, HE-AAC, AAC 5.1, MP3, MIDI, Ogg Vorbis, WAV, JPEG, PNG, GIF, and BMP. 5 Messaging SMS and MMS 6 Web browser Based on the open-source WebKit layout engine, coupled with Chrome's V8 JavaScript engine supporting HTML5 and CSS3.
  • 6. S.No. Feature & Description 7 Multi-touch Android has native support for multi-touch which was initially made available in handsets such as the HTC Hero. 8 Multi-tasking User can jump from one task to another and same time various application can run simultaneously. 9 GCM Google Cloud Messaging (GCM) is a service that lets developers send short message data to their users on Android devices, without needing a proprietary sync solution. 10 Wi-Fi Direct A technology that lets apps discover and pair directly, over a high-bandwidth peer-to-peer connection. 11 Android Beam A popular NFC-based technology that lets users instantly share, just by touching two NFC- enabled phones together.
  • 7. Android applications:  Entertainment  Tools  Communication  Productivity  Personalization  Music and Audio  Social  Media and Video  Travel and Local
  • 8. Android SDK Features  Android SDK stands for Android Software Development Kit which is developed by Google for Android Platform. With the help of Android SDK, we can create android Apps easily.  Android SDK is a collection of libraries and Software Development tools that are essential for Developing Android Applications.  Android SDK consists of some tools which are very essential for the development of Android Application.  These tools provide a smooth flow of the development process from developing and debugging. Android SDK is compatible with all operating systems such as Windows, Linux, macOS, etc.
  • 9. Android SDK Features  To download and install latest android APIs and development tools from the internet, android provide us with android SDK manager.  Android SDK Manager separates the APIs, tools and different platforms into different packages which you can download.  Android SDK manager comes with the Android SDK bundle. You can't download it separately.
  • 10. Android SDK Features Running Android SDK Manager  Once downloaded, you can launch Android SDK Manager in one of the following ways −  Click tools->Android-> SDK Manager option in Eclipse.  Double Click on the SDK Manager.exe file in the Android SDK folder.
  • 11. When it runs you will see the following screen:
  • 12. Components of Android SDK 1. Android SDK Tools  Android SDK tool is an important component of Android SDK. It consists of a complete set of development and debugging tools. Below are the SDK developer tools:  Android SDK Build tool.  Android Emulator.  Android SDK Platform-tools.  Android SDK Tools.
  • 13. Components of Android SDK 2. Android SDK Build-Tools Android SDK build tools are used for building actual binaries of Android App. The main functions of Android SDK Build tools are built, debug, run and test Android applications. 3. Android Emulator • An Android Emulator is a device that simulates an Android device on your system. Suppose we want to run our android application that we code. • In Android Emulator the virtual android device is shown on our system on which we run the Android application that we code.
  • 14. Components of Android SDK 4. Android SDK Platform-tools  Android SDK Platform-tools is helpful when we are working on Project and they will show the error messages at the same time. It is specifically used for testing. It includes:  Android Debug Bridge (ADB), is a command-line tool that helps to communicate with the device. It allows us to perform an action such as Installing App and Debugging App etc.  Fastboot allows you to flash a device with a new system image.  Systrace tools help to collect and inspect timing information. It is very crucial for App Debugging.
  • 15. Open Handset Alliance (OHA)  The Open Handset Alliance (OHA) is a consortium of 84 firms to develop open standards for mobile devices.  Established on 5th November 2007, as a consortium of 84 companies, the Open Handset Alliance (OHA) includes Google, Samsung, AKM, Synaptics, KDDI, Garmin, Teleca, eBay, Intel, etc.  The Open Handset Alliance (OHA) is led by Google. The main objective of Android is to advance open standards, provide services, and deploy handsets.
  • 16. Open Handset Alliance (OHA)  The Open Handset Alliance (OHA) It's a consortium of 84 companies such as google, samsung, AKM, synaptics, KDDI, Garmin, Teleca, Ebay, Intel etc.  Established on 5th November 2007, as a consortium of 84 companies, the Open Handset Alliance (OHA) includes Google, Samsung, AKM, Synaptics, KDDI, Garmin, Teleca, eBay, Intel, etc.  The Open Handset Alliance (OHA) is led by Google. The main objective of Android is to advance open standards, provide services, and deploy handsets.
  • 17. Development framework  In general, a framework is a real or conceptual structure intended to serve as a support or guide for the building of something that expands the structure into something useful.  An Android application framework is a software toolkit that enables app developers to piece together a finished product that meets the requirements of its proprietor.
  • 18. Development framework  A framework provides the bones of an application, to be fleshed out with graphics, animation, special features and functionality.  The Application Framework layer provides many higher- level services to applications in the form of Java classes.
  • 19. Android architecture or Android software stack is categorized into five parts: Linux kernel Native libraries (middleware) Android Runtime Application Framework Application Layer
  • 21. 1) Linux kernel • It is the heart of android architecture that exists at the root of android architecture. • Linux kernel is responsible for device drivers, power management, memory management, device management and resource access.
  • 22. 2) Native Libraries • Running on the top of linux kernel, Native libraries such as WebKit, OpenGL, FreeType, SQLite, Media, C runtime library (libc) etc. • The WebKit library is responsible for browser support and Internet security; • SQLite is for database, • FreeType for font support, • Media for playing and recording audio and video formats.
  • 23. 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.
  • 24. • 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.
  • 25. 3) Android Runtime  In android runtime, there are core libraries and DVM (Dalvik Virtual Machine) which is responsible to run android application.  One of the key elements of Android is the Dalvik VM, Android uses its own custom VM designed to ensure that multiple instances run efficiently on a single device.  DVM is like JVM but it is optimized for mobile devices.  The Dalvik VM makes use of Linux core features like memory management and multi-threading, which is intrinsic in the Java language.  It consumes less memory and provides fast performance.
  • 26. 4) Android Framework  On the top of Native libraries and android runtime, there is android framework.  Android framework includes Android API's such as UI (User Interface), telephony, resources, locations, Content Providers (data) and package managers.  It provides a lot of classes and interfaces for android application development.
  • 27. 5) Application Layer  On the top of android framework, there are applications.  All applications such as home, contact, settings, games, browsers are using android framework that uses android runtime and libraries.  Android runtime and native libraries are using linux kernal.
  • 28. Android Core Building Blocks  An android component is simply a piece of code that has a well defined life cycle e.g. Activity, Receiver, and Service etc.  The core building blocks or fundamental components of android are activities, views, intents, services, content providers, fragments and AndroidManifest.xml.
  • 29.  Activity An activity is a class that represents a single screen. It is like a Frame in AWT.  View A view is the UI element such as button, label, text field etc. Anything that you see is a view.  Intent Intent is used to invoke components. It is mainly used to: • Start the service • Launch an activity • Display a web page • Display a list of contacts • Broadcast a message • Dial a phone call etc.
  • 30. • For example, write the following code to view the webpage. Intent intent=new Intent (Intent.ACTION_VIEW); intent.setData(Uri.parse("http://www.javatpoint.com")); startActivity(intent);
  • 31. Service • Service is a background process that can run for a long time. • There are two types of services local and remote. • Local service is accessed from within the application whereas remote service is accessed remotely from other applications running on the same device. Content Provider • Content Providers are used to share data between the applications. • Fragment • Fragments are like parts of activity. • An activity can display one or more fragments on the screen at the same time.
  • 32. AndroidManifest.xml • It contains information about activities, content providers, permissions etc. • It is like the web.xml file in Java EE. Android Virtual Device (AVD) • It is used to test the android application without the need for mobile or tablet etc. • It can be created in different configurations to emulate different types of real devices.
  • 33. Android Activity Lifecycle • Activity is one of the building blocks of Android OS. • Activity is a screen that user interact with. • Every Activity in android has lifecycle like created, started, resumed, paused, stopped or destroyed. • Activity is a class pre-written in Java Programming. An activity is the single screen in android. It is like window or frame of Java.
  • 34. Android Activity Lifecycle methods The 7 lifecycle methods of Activity describes how activity will behave at different states. •onCreate() •onStart() •onResume() •onPause() •onStop() •onRestart() •onDestroy
  • 35. Android Activity Lifecycle methods •onCreate() – Called when the activity is first created •onStart() – Called just after it’s creation or by restart method after onStop(). Here Activity start becoming visible to user •onResume() – Called when Activity is visible to user and user can interact with it •onPause() – Called when Activity content is not visible because user resume previous activity
  • 36. Android Activity Lifecycle methods •onStop() – Called when activity is not visible to user because some other activity takes place of it •onRestart() – Called when user comes on screen or resume the activity which was stopped •onDestroy – Called when Activity is not in background
  • 43. EXAMPLE Following is the content of the modified main activity file src/com.example.helloworld/MainActivity.java. This file includes each of the fundamental life cycle methods. The Log.d() method has been used to generate log messages −
  • 44. package com.example.helloworld; import android.os.Bundle; import android.app.Activity; import android.util.Log; public class MainActivity extends Activity { String msg = "Android : "; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.d(msg, "The onCreate() event"); } /** Called when the activity is about to become visible. */ @Override protected void onStart() { super.onStart(); Log.d(msg, "The onStart() event"); }
  • 45. /** Called when the activity has become visible. */ @Override protected void onResume() { super.onResume(); Log.d(msg, "The onResume() event"); } /** Called when another activity is taking focus. */ @Override protected void onPause() { super.onPause(); Log.d(msg, "The onPause() event"); }
  • 46. /** Called when the activity is no longer visible. */ @Override protected void onStop() { super.onStop(); Log.d(msg, "The onStop() event"); } /** Called just before the activity is destroyed. */ @Override public void onDestroy() { super.onDestroy(); Log.d(msg, "The onDestroy() event"); } }
  • 47. ANDROID DEVELOPMENT TOOLS • Android Development Tools (ADT) is a plug-in for the Eclipse IDE that is designed to give you a powerful, integrated environment in which to build Android applications. • ADT is the Android Developer Tools plug-in for Eclipse. • ADT is about the useful code stuff: for example the libraries, packages. • The ADT plug-in for Eclipse uses the SDK tools as part of its work.
  • 48. ADT vs Android SDK • The Android SDK contains the tools and related files necessary to build an Android application. • SDK is actually about the tools: for example Debugging.
  • 49. Android Development Tools (ADT) ADT plug-in incorporates many of the tools into the Eclipse IDE, where you can access them from the DDMS perspective, including the following: Android Virtual Device and SDK Managers Android Emulator Dalvik Debug Monitoring Service (DDMS) Android Debug Bridge (ADB) Android Asset Packaging Tool (AAPT) SQLite3 MkSDCard
  • 50. Android Virtual Device and SDK Managers • Used to create and manage AVDs and to download SDK packages, respectively. • The AVD hosts an Emulator running on a particular build of Android, • It specify the supported SDK version, screen resolution, amount of SD card storage available, and available hardware capabilities (such as touchscreens and GPS).
  • 51. Android Emulator • Use the Emulator to test and debug your Android applications Dalvik Debug Monitoring Service (DDMS) • Use the DDMS to monitor and control the Emulators on which you’re debugging your applications. Android Debug Bridge (ADB) • A client-server application that provides a link to virtual and physical devices. It lets you copy files, install compiled application packages (.apk), and run shell commands.
  • 52. Android Asset Packaging Tool (AAPT) • Constructs the distributable Android package fi les (.apk). SQLite3 • A database tool that you can use to access the SQLite database fi les created and used by Android. MkSDCard • Creates an SD card disk image that can be used by the Emulator to simulate an external storage card.
  • 53. Creating an Applications and Activities • Used to create and manage AVDs and to download SDK packages, respectively. • The AVD hosts an Emulator running on a particular build of Android, • It specify the supported SDK version, screen resolution, amount of SD card storage available, and available hardware capabilities (such as touchscreens and GPS).
  • 54. AndroidManifest.xml file in android • The AndroidManifest.xml file contains information of your package, including components of the application such as activities, services, broadcast receivers, content providers etc. • It is responsible to protect the application to access any protected parts by providing the permissions.
  • 55. Elements of the AndroidManifest.xml file • <manifest> • manifest is the root element of the AndroidManifest.xml file. It has package attribute that describes the package name of the activity class. • <application> • application is the subelement of the manifest. It includes the namespace declaration. This element contains several subelements that declares the application component such as activity etc.
  • 56. • The commonly used attributes are of this element are icon, label, theme etc. • android:icon represents the icon for all the android application components. • android:label works as the default label for all the application components. • android:theme represents a common theme for all the android activities.
  • 84. Intent Intent is used to invoke components. It is mainly used to:  Start the service  Launch an activity  Display a web page  Display a list of contacts  Broadcast a message  Dial a phone call etc.
  • 86. Intent • Android Intent is the message that is passed between components such as activities, content providers, broadcast receivers, services etc. • It is generally used with startActivity() method to invoke activity, broadcast receivers etc. • The dictionary meaning of intent is intention or purpose. So, it can be described as the intention to do action. • The LabeledIntent is the subclass of android.content.Intent class.
  • 87. • Intent Types • There are two types of intents in android: implicit and explicit. 1) Implicit Intent • Implicit Intent doesn't specify the component. In such case, intent provides information of available components provided by the system that is to be invoked. • For example, you may write the following code to view the webpage. • Intent intent=new Intent(Intent.ACTION_VIEW); • intent.setData(Uri.parse("http://www.javatpoint.com")); • startActivity(intent);
  • 88. 2) Explicit Intent • Explicit Intent specifies the component. In such case, intent provides the external class to be invoked. Intent i = new Intent(getApplicationContext(), ActivityTwo.class); startActivity(i);
  • 89. • Android Implicit Intent Example • Let's see the simple example of implicit intent that displays a web page. • activity_main.xml • File: activity_main.xml • <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android" • xmlns:tools="http://schemas.android.com/tools" • android:layout_width="match_parent" • android:layout_height="match_parent" • tools:context=".MainActivity" > • <EditText • android:id="@+id/editText1" • android:layout_width="wrap_content" • android:layout_height="wrap_content" • android:layout_alignParentTop="true" • android:layout_centerHorizontal="true" • android:layout_marginTop="44dp"
  • 90. • Android Implicit Intent Example • android:ems="10" /> • <Button • android:id="@+id/button1" • android:layout_width="wrap_content" • android:layout_height="wrap_content" • android:layout_below="@+id/editText1" • android:layout_centerHorizontal="true" • android:layout_marginTop="54dp" • android:text="Visit" /> • </RelativeLayout>
  • 91. Activity class File: MainActivity.java package org.sssit.implicitintent; import android.net.Uri; import android.widget.EditText; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final EditTexteditText1=(EditText)findViewById(R.id.editText1); Button button1=(Button)findViewById(R.id.button1); • button1.setOnClickListener(new OnClickListener() { • @Override • public void onClick(View arg0) { • String url=editText1.getText().toString(); • Intent intent=new Intent(Intent.ACTION_VIEW,Uri.parse(url)); • startActivity(intent); • } }); } }
  • 93. Activity class File: MainActivity.java package org.sssit.implicitintent; import android.net.Uri; import android.widget.EditText; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final EditText editText1=(EditText)findViewById(R.id.editText1); Button button1=(Button)findViewById(R.id.button1);
  • 94. Drawable Resources: • drawable/ • For bitmap files (PNG, JPEG, or GIF), 9-Patch image files, and • XML files that describe Drawable shapes or Drawable objects that • contain multiple states (normal, pressed, or focused). • res — This folder contains all the resources used in your application. It also contains a few other subfolders: drawable-<resolution>, layout, and values.
  • 95. Android multiple screen: Screen Density • We considered only the screen size but as we said earlier there are different densities too. • Density affects primary the images so an image could be the right size one a screen device and looks too small in another device with more density. • So we have to consider this problem.
  • 96. Android multiple screen: Screen Density Density Android name Small around 120dpi (ldpi) Normal around 160dpi (mdpi) High around 240dpi (hdpi) x-High around 320dpi (xhdpi)
  • 98. Resource Type Directory Filename XML Tag SimpleDrawables /res/values/ drawables.xml <drawable> Graphics Frame-by-Frame Animations /res/drawable/ /res/drawable/ Examples include icon.png logo.jpg Examples include sequence1.xml sequence2.xml Supported graphics files or drawable definition XML files such as shapes. <animation-list>, <item>
  • 99. Option Menu with Icon You need to have icon images inside the res/drawable directory. The android:icon element is used to display the icon on the option menu. You can write the string information in the strings.xml file. But we have written it inside the menu_main.xml file.
  • 100. Option Menu with Icon File: menu_main.xml <menu xmlns:androclass="http://schemas.android.com/apk/res/android" > <item android:id="@+id/item1" android:icon="@drawable/add" android:title="Item 1"/> <item android:id="@+id/item2" android:icon="@drawable/minus" android:title="Item 2"/> <item android:id="@+id/item3" android:icon="@drawable/delete" android:title="Item 3"/> </menu>
  • 102. UNIT II USE INTERFACE TOOLS Creating user interface – Views - Creating views – Layouts – Drawable resources – Resolution and density independence – Menus – Intents – Adapters – Using Internet resources – Dialogs
  • 103. Creating User Interface The role of the UI is to display the application data on the screen and also to serve as the primary point of user interaction. User Interface (UI) design in Android is a graphical representation of views displayed on a smartphone or tablet. It allows users to interact with the features, functions, and contents of the application. To design UI, you need no prior programming knowledge, although it is nice to have web developing skills or programming skills.
  • 104. Components used for Android application Main Action Bar (MAR) Split Action Bar (SAB) Content Area
  • 105. Steps to follow in UI Design • Download Android studio from your browser. • Install Android studio. • Open Android studio. • Create a new project and select project type. • Give it a name of your choice. • Click on the resources folder. • Click on the layout folder and begin to design your UI.
  • 106. Views components Views are used to customize User Interface (UI) design. A view is considered a building block for a proper User Interface created from the view class. A view can also be defined as a small rectangular box in Android development that responds to the user inputs, for example, buttons, checkboxes, etc.
  • 107. Views components View group is an invisible container of other views, such as child view and other view groups. This view class is a super class of all the GUI components in Android. Views play a key role in the development of an application because you need settings present in the application, e.g.,color, style, themes, etc.
  • 108. A simple UI Design
  • 109. Layout as a subclass of View group The Layout defines the visual structures of the UI of user application. All elements in the layout are built using a hierarchy of views and view group object. The layout can be declared through a programming language, or through a simple XML layout file located in the resource layout folder of any project you work on.
  • 110. Layout Layouts are kept in the folder called resources. Android studio creates a default XML layout file in the resources layout folder that is extremely useful if you know the basic at the time of compiling.
  • 112. Advantages of XML Layout It is an immensely popular and widely used format. It helps provide the UI component from the logic, which in turn provides the flexibility to change one component without affecting the other. It is much easier to generate than writing direct code. It allows an easier drag and drop to generate interfaces for the Android application.
  • 113. Types of layout Linear layout: It is used to arrange views in a single column or row. It is further divided into a vertical or horizontal linear layout. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello, I am a Button" /> </LinearLayout>
  • 114. Types of layout Frame layout: It is a placeholder on the screen used to display a single screen. <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello, I am a Button" /> </FrameLayout>
  • 115. Types of layout Relative layout: It enables you to specify how child views are positioned to each other. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello, I am a Button" /> </RelativeLayout>
  • 116. Types of layout Constraint layout: It provides you with adaptable and flexible ways to create views for your applications. <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas .android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent“ <TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello, I am a TextView" /> </androidx.constraintlayout.widget.ConstraintLayout>
  • 117. Intent Intent is used to invoke components. It is mainly used to:  Start the service  Launch an activity  Display a web page  Display a list of contacts  Broadcast a message  Dial a phone call etc.
  • 119. Intent • Android Intent is the message that is passed between components such as activities, content providers, broadcast receivers, services etc. • It is generally used with startActivity() method to invoke activity, broadcast receivers etc. • The dictionary meaning of intent is intention or purpose. So, it can be described as the intention to do action. • The LabeledIntent is the subclass of android.content.Intent class.
  • 120. • Intent Types • There are two types of intents in android: implicit and explicit. 1) Implicit Intent • Implicit Intent doesn't specify the component. In such case, intent provides information of available components provided by the system that is to be invoked. • For example, you may write the following code to view the webpage. • Intent intent=new Intent(Intent.ACTION_VIEW); • intent.setData(Uri.parse("http://www.javatpoint.com")); • startActivity(intent);
  • 121. 2) Explicit Intent • Explicit Intent specifies the component. In such case, intent provides the external class to be invoked. Intent i = new Intent(getApplicationContext(), ActivityTwo.class); startActivity(i);
  • 122. • Android Implicit Intent Example • Let's see the simple example of implicit intent that displays a web page. • activity_main.xml • File: activity_main.xml • <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android" • xmlns:tools="http://schemas.android.com/tools" • android:layout_width="match_parent" • android:layout_height="match_parent" • tools:context=".MainActivity" > • <EditText • android:id="@+id/editText1" • android:layout_width="wrap_content" • android:layout_height="wrap_content" • android:layout_alignParentTop="true" • android:layout_centerHorizontal="true" • android:layout_marginTop="44dp"
  • 123. • Android Implicit Intent Example • android:ems="10" /> • <Button • android:id="@+id/button1" • android:layout_width="wrap_content" • android:layout_height="wrap_content" • android:layout_below="@+id/editText1" • android:layout_centerHorizontal="true" • android:layout_marginTop="54dp" • android:text="Visit" /> • </RelativeLayout>
  • 124. Activity class File: MainActivity.java package org.sssit.implicitintent; import android.net.Uri; import android.widget.EditText; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final EditTexteditText1=(EditText)findViewById(R.id.editText1); Button button1=(Button)findViewById(R.id.button1); • button1.setOnClickListener(new OnClickListener() { • @Override • public void onClick(View arg0) { • String url=editText1.getText().toString(); • Intent intent=new Intent(Intent.ACTION_VIEW,Uri.parse(url)); • startActivity(intent); • } }); } }
  • 126. Activity class File: MainActivity.java package org.sssit.implicitintent; import android.net.Uri; import android.widget.EditText; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final EditText editText1=(EditText)findViewById(R.id.editText1); Button button1=(Button)findViewById(R.id.button1);
  • 127. Drawable Resources: • drawable/ • For bitmap files (PNG, JPEG, or GIF), 9-Patch image files, and • XML files that describe Drawable shapes or Drawable objects that • contain multiple states (normal, pressed, or focused). • res — This folder contains all the resources used in your application. It also contains a few other subfolders: drawable-<resolution>, layout, and values.
  • 128. Android multiple screen: Screen Density • We considered only the screen size but as we said earlier there are different densities too. • Density affects primary the images so an image could be the right size one a screen device and looks too small in another device with more density. • So we have to consider this problem.
  • 129. Android multiple screen: Screen Density Density Android name Small around 120dpi (ldpi) Normal around 160dpi (mdpi) High around 240dpi (hdpi) x-High around 320dpi (xhdpi)
  • 131. Resource Type Directory Filename XML Tag SimpleDrawables /res/values/ drawables.xml <drawable> Graphics Frame-by-Frame Animations /res/drawable/ /res/drawable/ Examples include icon.png logo.jpg Examples include sequence1.xml sequence2.xml Supported graphics files or drawable definition XML files such as shapes. <animation-list>, <item>
  • 132. Option Menu with Icon You need to have icon images inside the res/drawable directory. The android:icon element is used to display the icon on the option menu. You can write the string information in the strings.xml file. But we have written it inside the menu_main.xml file.
  • 133. Option Menu with Icon File: menu_main.xml <menu xmlns:androclass="http://schemas.android.com/apk/res/android" > <item android:id="@+id/item1" android:icon="@drawable/add" android:title="Item 1"/> <item android:id="@+id/item2" android:icon="@drawable/minus" android:title="Item 2"/> <item android:id="@+id/item3" android:icon="@drawable/delete" android:title="Item 3"/> </menu>
  • 134.  Activity An activity is a class that represents a single screen. It is like a Frame in AWT.  View A view is the UI element such as button, label, text field etc. Anything that you see is a view.  Intent Intent is used to invoke components. It is mainly used to: • Start the service • Launch an activity • Display a web page • Display a list of contacts • Broadcast a message • Dial a phone call etc.
  • 135. • For example, write the following code to view the webpage. Intent intent=new Intent (Intent.ACTION_VIEW); intent.setData(Uri.parse("http://www.javatpoint.com")); startActivity(intent);
  • 136. Service • Service is a background process that can run for a long time. • There are two types of services local and remote. • Local service is accessed from within the application whereas remote service is accessed remotely from other applications running on the same device. Content Provider • Content Providers are used to share data between the applications. • Fragment • Fragments are like parts of activity. • An activity can display one or more fragments on the screen at the same time.
  • 137. AndroidManifest.xml • It contains information about activities, content providers, permissions etc. • It is like the web.xml file in Java EE. Android Virtual Device (AVD) • It is used to test the android application without the need for mobile or tablet etc. • It can be created in different configurations to emulate different types of real devices.
  • 138. • IMAGES • public abstract class Image extends Object implements AutoCloseable • java.lang.Object • ↳ android.media.Image • A single complete image buffer to use with a media source such as a MediaCodec or a CameraDevice. • This class allows for efficient direct application access to the pixel data of the Image through one or more ByteBuffers. • Each buffer is encapsulated in a Plane that describes the layout of the pixel data in that plane. • Due to this direct access, and unlike the Bitmap class, Images are not directly usable as UI resources.
  • 139. • MENU • In android, Options Menu is a primary collection of menu items for an activity and it is useful to implement • actions that have a global impact on the app, such as Settings, Search, etc. • In case, if we define items for the options menu in both activity or fragment, then those items will be combine and display in UI.
  • 144. Adapter In Android, Adapter is a bridge between UI component and data source that helps us to fill data in UI component. It holds the data and send the data to an Adapter view then view can takes the data from the adapter view and shows the data on different views like as ListView, GridView, Spinner etc. For more customization in Views we uses the base adapter or custom adapters.
  • 146. Adapters In Android: There are the some commonly used Adapter in Android used to fill the data in the UI components. BaseAdapter – It is parent adapter for all other adapters ArrayAdapter – It is used whenever we have a list of single items which is backed by an array Custom ArrayAdapter – It is used whenever we need to display a custom list SimpleAdapter – It is an easy adapter to map static data to views defined in your XML file Custom SimpleAdapter – It is used whenever we need to display a customized list and needed to access the child items of the list or grid
  • 147. 1. BaseAdapter In Android: BaseAdapter is a common base class of a general implementation of an Adapter that can be used in ListView, GridView, Spinner etc. Whenever we need a customized list in a ListView or customized grids in a GridView we create our own adapter and extend base adapter in that. Base Adapter can be extended to create a custom Adapter for displaying a custom list item. ArrayAdapter is also an implementation of BaseAdapter.
  • 148. Custom Adapter code which extends the BaseAdapter in that: public class CustomAdapter extends BaseAdapter { @Override public int getCount() { return 0; } @Override public Object getItem(int i) { return null; } @Override public long getItemId(int i) { return 0; } @Override public View getView(int i, View view, ViewGroup viewGroup) { return null; }
  • 149. 2. ArrayAdapter In Android: Whenever we have a list of single items which is backed by an Array, we can use ArrayAdapter. For instance, list of phone contacts, countries or names. ArrayAdapter(Context context, int resource, int textViewResourceId, T[] objects)
  • 150. 3. Custom ArrayAdapter In Android: ArrayAdapter is also an implementation of BaseAdapter, so if we want more customization then we can create a custom adapter and extend ArrayAdapter in that. Below Custom adapter class MyAdapter extends ArrayAdapter in that:
  • 151. Below Custom adapter class MyAdapter extends ArrayAdapter in that: public class MyAdapter extends ArrayAdapter { public MyAdapter(Context context, int resource, int textViewResourceId, List objects) { super(context, resource, textViewResourceId, objects); } @Override public int getCount() { return super.getCount(); } @Override public View getView(int position, View convertView, ViewGroup parent) { return super.getView(position, convertView, parent); } }
  • 152. 4. SimpleAdapter In Android: In Android SimpleAdapter is an easy Adapter to map static data to views defined in an XML file(layout). In Android we can specify the data backing to a list as an ArrayList of Maps(i.e. hashmap or other). Each entry in a ArrayList is corresponding to one row of a list. The Map contains the data for each row. Here we also specify an XML file(custom list items file) that defines the views which is used to display the row, and a mapping from keys in the Map to specific views.
  • 153. SimpleAdapter code in Android: SimpleAdapter (Context context, List<? extends Map<S tring, ?>> data, int resource, String[] from, int[] to)
  • 154. Adapter Example In Android Studio: Below is the Android Studio example which show the use of the Adapter in Android. In this example we display a list of fruits names with images by using SimpleAdapter and whenever user click on a list item the fruit’s name displayed in a Toast.
  • 156. Android Listview in Java with Example A ListView is a type of AdapterView that displays a vertical list of scroll-able views and each view is placed one below the other. For displaying the items in the list method setAdaptor() is used. setAdaptor() method conjoins an adapter with the list.
  • 157. XML Attributes of ListView Attribute Description android:divider A color or drawable to separate list items. android:dividerHeight Divider’s height. android:entries 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. android:headerDividersEnabled When set to false, the ListView will not draw the divider before each header view.
  • 158. Create an android application that will display a list of tutorials available in GeeksforGeeks portal Step 1: Create a new project 1.Click on File, then New => New Project. 2.Choose “Empty Activity” for the project template. 3.Select language as Java. 4.Select the minimum SDK as per your need. Step 2: Modify activity_main.xml file Add a ListView in the activity_main.xml file. How to add a ListView in an Android App
  • 159. How to add a ListView in an Android App <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/and roid" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <ListView android:id="@+id/list" android:layout_width="match_parent" android:layout_height="match_parent"/> </LinearLayout>
  • 160. Step 3: Modify MainActivity.java file public ArrayAdapter (Context context, int Resource, T[ ] objects)
  • 163. • DIALOG • A dialog is a small window that prompts the user to make a decision or enter additional information. • A dialog does not fill the screen and is normally used for modal events that require users to take an action before they can proceed. • The Dialog class is the base class for dialogs, but you should avoid instantiating Dialog directly. Instead, use one of the following subclasses: • AlertDialog : A dialog that can show a title, up to three buttons, a list of selectable items, or a custom layout. • DatePickerDialog or TimePickerDialog : A dialog with a pre-defined UI that allows the user to select a date or time.
  • 165. Saving Simple Application Data – Creating and saving preferences – Preferences activity – Saving activity state - Loading files – File management tools - Introducing Android databases –SQLite – Cursors and content Values – Working with SQlite Databases – Creating and Using Content providers – Native Android content Providers
  • 166. • SQLite Database in Android. • Database - Package • The main package is android.database.sqlite that contains the classes to manage your own databases
  • 167. • 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.
  • 168. SQLite is lightweight process. No connectivity is needed. For example: In order to access this database, you don't need to establish any kind of connections for it like JDBC,ODBC e.t.c.
  • 170.  In order to create a database you just need to call this method openOrCreateDatabase with your database name and mode as a parameter.  It returns an instance of SQLite database which you have to receive in your own object.  Its syntax is given below  SQLiteDatabase mydatabase = OpenOrCreateDatabase("your database name",MODE_PRIVATE,null);
  • 171.  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 TutorialsPoint(Username VARCHAR, Password VARCHAR);");  mydatabase.execSQL("INSERT INTO TutorialsPoint VALUES('admin','admin');");
  • 172.  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.  Cursor resultSet = mydatbase.rawQuery("Select * from MRCET",null);  resultSet.moveToFirst();  String username = resultSet.getString(0);  String password = resultSet.getString(1);
  • 173.  For managing all the operations related to the database , an helper class has been given and is called SQLiteOpenHelper.  It automatically manages the creation and update of the database.  To experiment with this example, you need to run this on an actual device on which camera is supported.
  • 174.  public class DBHelper extends SQLiteOpenHelper {  public DBHelper(){  super(context,DATABASE_NAME,null,1);  }  public void onCreate(SQLiteDatabase db) {}  public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {}  }
  • 175.  For managing all the operations related to the database , an helper class has been given and is called SQLiteOpenHelper.  It automatically manages the creation and update of the database.  To experiment with this example, you need to run this on an actual device on which camera is supported.
  • 176. Steps Description You will use Android studio to create an Android application under a package com.example.dinesh.myapplication. Modify src/MainActivity.java file to get references of all the XML components and populate the contacts on listView. Create new src/DBHelper.java that will manage the database work Create a new Activity as DisplayContact.java that will display the contact on the screen
  • 177.  Demonstrating the use of SQLite Database.  It creates a basic contacts applications that allows insertion, deletion and modification of contacts.
  • 187. HARDWARE SENSORS AND LOCATION- BASED SERVICES Using Sensors and the Sensor Manager– Monitoring a Device’s Movement and Orientation –Introducing the Environmental Sensors– Using Location-Based Services– Selecting a Location Provider –Finding Your Current Location
  • 188. In Android devices, there are various built-in sensors that can be used to measure the orientation, motions, and various other kinds of environmental conditions.
  • 189.  Hardware sensors are physical components that are present in Android devices.  They can directly measure various properties like field strength, acceleration, etc according to the types of the sensors and after measuring the environment properties they can send the data to Software Sensors.
  • 190.  To express data values or to collect data, the sensors in Android devices uses a 3-axis coordinate system i.e. you will be having X, Y, and Z-axis.  The following figure depicts the position of various axis used in sensors.
  • 191.  Motion Sensors: The sensors that are responsible for measuring or identifying the shakes and tilts of your Android devices are called Motion sensors.  Position Sensors: As the name suggests, the Position sensors are used to determine the position of an Android device. Magnetometers sensors is the example of Position sensors.  Environmental Sensors: Environmental properties like temperature, pressure, humidity, etc are identified with the help of Environmental sensors. Some of the examples of Environmental sensors are thermometer, photometer, barometer, etc.
  • 192.  The Sensor Manager is used to manage the sensor hardware available on Android devices.  Use getSystemService to return a reference to the Sensor Manager Service, as shown in the following snippet: String service_name = Context.SENSOR_SERVICE; SensorManager sensorManager = (SensorManager)getSystemService(service_name);
  • 193.  Sensor.TYPE_TEMPERATURE. This is a thermometer that returns the temperature in degrees Celsius; the temperature returned will be the ambient room temperature.  Sensor.TYPE_ACCELEROMETER— A three-axis accelerometer that returns the current acceleration along three axes in m/s2 (meters per second)  Sensor.TYPE_GRAVITY — A three-axis gravity sensor that returns the current direction and magnitude of gravity along three axes in m/s2.  Sensor.TYPE_LINEAR_ACCELERATION: A three-axis linear acceleration Sensor that returns the acceleration, not including gravity, along three axes in m/s2.  Sensor.TYPE_GYROSCOPE — A three-axis gyroscope that returns the rate of device rotation along three axes in radians/second.
  • 194.  Sensor.TYPE_TEMPERATURE. This is a thermometer that returns the temperature in degrees Celsius; the temperature returned will be the ambient room temperature.  Sensor.TYPE_ACCELEROMETER— A three-axis accelerometer that returns the current acceleration along three axes in m/s2 (meters per second)  Sensor.TYPE_GRAVITY — A three-axis gravity sensor that returns the current direction and magnitude of gravity along three axes in m/s2.  Sensor.TYPE_LINEAR_ACCELERATION: A three-axis linear acceleration Sensor that returns the acceleration, not including gravity, along three axes in m/s2.  Sensor.TYPE_GYROSCOPE — A three-axis gyroscope that returns the rate of device rotation along three axes in radians/second.
  • 195.  To find every Sensor available on the host platform, use getSensorList on the Sensor Manager, passing in Sensor.TYPE_ALL:  List<Sensor>allSensors = sensorManager.getSensorList(Sensor.TYPE_ALL);  To find a list of all the available Sensors of a particular type, use getSensorList, specifying the type of Sensor you require, as shown in the following code that returns all the available gyroscopes:  List<Sensor> gyroscopes = sensorManager.getSensorList(Sensor.TYPE_GYROSCOPE);
  • 196.  The following snippet returns the default pressure sensor:  Sensor defaultBarometer = sensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE);
  • 197.  To monitor a Sensor, implement a SensorEventListener, using the onSensorChanged method to monitor Sensor values, and onAccuracyChanged to react to changes in a Sensor’s accuracy.
  • 198. Example: Sensor Event Listener skeleton code finalSensorEventListenermySensorEventListener = new SensorEventListener() { public void onSensorChanged(SensorEventsensorEvent) { // TODO Monitor Sensor changes. } public void onAccuracyChanged(Sensor sensor, int accuracy) { // TODO React to a change in Sensor accuracy. } };
  • 199. The SensorEvent parameter in the onSensorChanged method includes the following four properties to describe each Sensor Event: sensor — The Sensor object that triggered the event. accuracy — The accuracy of the Sensor when the event occurred (low, medium, high, or unreliable, as described in the next list). values — A float array that contains the new value(s) observed. The next section explains the values returned for each sensor type. timestamp — The time (in nanoseconds) at which the Sensor Event occurred.
  • 201. SMALL COMPUTING TECNOLOGY Audio, Video Using the Camera – Using Bluetooth – Managing Network and Internet Connectivity - Managing Wi-Fi – Transferring Data Using Wi-Fi Direct – Near Field Communication.
  • 202.  PLAYING AUDIO AND VIDEO  Android 4.0.3 (API level 15) supports the following multimedia formats for playback. Audio Image Video Network protocols for streaming media
  • 203. Audio Image Video  AAC LC/LTP (Advanced Audio Coding)  HE-AACv1 (AAC+)  HE-AACv2 (Enhanced AAC+)  AMR-NB (Adaptive Multi Rate)  AMR-WB  MP3  MIDI  JPEG  PNG  WEBP (on devices running Android 4.0 or above)  GIF  BMP  H.263  H.264 AVC  MPEG-4 SP  VP8 (on devices running Android 2.3.3 or above)
  • 204.  Network protocols are supported for streaming media: RTSP (RTP, SDP) HTTP/HTTPS progressive streaming HTTP/HTTPS live streaming (on devices running Android 3.0 or above)
  • 205.  Playback of audio and video within Android applications is handled primarily through the MediaPlayer class. 1. Initialize the Media Player with media to play. 2. Prepare the Media Player for playback. 3. Start the playback. 4. Pause or stop the playback prior to its completing. 5. The playback is complete.
  • 206.  To stream Internet media using the Media Player, your application must include the INTERNETpermission: <uses-permission android:name=”android.permission.INTERNET”/>  When you finish playback, call release on your Media Player object to free the associated resources: mediaPlayer.release();
  • 207.  It can used as an application resource, play it from local files or Content Providers, or stream it from a remote URL. Initializing Audio Content for Playback  Using the static create method, passing in the Activity Context and any one of the following audio sources:  A resource identifier (typically for an audio file stored in the res/raw resource folder)  A URI to a local file (using the file:// schema)  A URI to an online audio resource (as a URL)  A URI to a row within a Content Provider that returns an audio file
  • 208. // Load an audio resource from a package resource. MediaPlayer resourcePlayer = MediaPlayer.create(this, R.raw.my_audio); // Load an audio resource from a local file. MediaPlayer filePlayer = MediaPlayer.create(this, Uri.parse(“file:///sdcard/localfile.mp3”)); // Load an audio resource from an online resource. MediaPlayer urlPlayer = MediaPlayer.create(this, Uri.parse(“http://site.com/audio/audio.mp3”)); // Load an audio resource from a Content Provider. MediaPlayer contentPlayer = MediaPlayer.create(this, Settings.System.DEFAULT_RINGTONE_URI);
  • 209.  There are two alternatives for the playback of video content. 1. Using the VideoViewclass, encapsulates the creation of a Surface and allocation and preparation of video content using a Media Player. 2. Allows you to specify your own Surface and manipulate the underlyingMedia Player instance directly.
  • 210.  A video to play by calling its setVideoPath or setVideoURI methods to specify the path to a local file, or the URI of either a Content Provider or remote video stream: final VideoView videoView = (VideoView)findViewById(R.id.videoView); // Assign a local file to play videoView.setVideoPath(“/sdcard/mycatvideo.3gp”); // Assign a URL of a remote video stream videoView.setVideoUri(myAwesomeStreamingSource);
  • 211.  Call start to begin playback of the associated media using: mediaPlayer.start();  Use the stop and pause methods to stop or pause playback, respectively.  It provides:  getDuration method- to find the length of the media being played.  getCurrentPosition method- to find the playback position.  seekTo method- to jump to a specific position in the media.
  • 212.  import java.io.IOException;  import android.app.Activity;  import android.media.MediaPlayer;  import android.os.Bundle;  import android.util.Log;  import android.view.SurfaceHolder;  import android.view.SurfaceView;  import android.view.View;  import android.view.View.OnClickListener;  import android.widget.Button;
  • 213. public class SurfaceViewVideoViewActivity extends Activity implements SurfaceHolder.Callback { static final String TAG = “SurfaceViewVideoViewActivity”; private MediaPlayer mediaPlayer; public void surfaceCreated(SurfaceHolder holder) { try { mediaPlayer.setDisplay(holder);
  • 214. public class SurfaceViewVideoViewActivity extends Activity implements SurfaceHolder.Callback { static final String TAG = “SurfaceViewVideoViewActivity”; private MediaPlayer mediaPlayer; public void surfaceCreated(SurfaceHolder holder) { try { mediaPlayer.setDisplay(holder); mediaPlayer.setDataSource(“/sdcard/test2.3gp”); mediaPlayer.prepare(); }
  • 215. catch (IllegalArgumentException e) { Log.e(TAG, “Illegal Argument Exception”, e); } catch (IllegalStateException e) { Log.e(TAG, “Illegal State Exception“, e); } catch (SecurityException e) { Log.e(TAG, “Security Exception“, e); } catch (IOException e) { Log.e(TAG, “IO Exception“, e); } }
  • 216. // Create a new Media Player. mediaPlayer = new MediaPlayer(); // Get a reference to the Surface View. final SurfaceView surfaceView = (SurfaceView)findViewById(R.id.surfaceView); // Configure the Surface View. surfaceView.setKeepScreenOn(true); // Connect a play button. Button playButton = (Button)findViewById(R.id.buttonPlay); playButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { mediaPlayer.start(); } });
  • 217. // Connect a pause button. Button pauseButton = (Button)findViewById(R.id.buttonPause); pauseButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { mediaPlayer.pause(); } } // Add a skip button. Button skipButton = (Button)findViewById(R.id.buttonSkip); skipButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { mediaPlayer.seekTo(mediaPlayer.getDuration()/2); } }
  • 218. To ensure a consistent media control experience, Android includes the MediaController — a standard control that provides the common media control buttons.
  • 219. MediaController mediaController = new MediaController(this); mediaController.setMediaPlayer(new MediaPlayerControl() { public boolean canPause() { return true; } public boolean canSeekBackward() { return true; } public boolean canSeekForward() { return true; }
  • 220. public int getCurrentPosition() { return mediaPlayer.getCurrentPosition(); } public int getDuration() { return mediaPlayer.getDuration(); } public boolean isPlaying() { return mediaPlayer.isPlaying(); } public void pause() { mediaPlayer.pause(); } public void start() { mediaPlayer.start(); }
  • 221. Creating a Sound Pool preloads the audio tracks used by your application, such as each level within a game, and optimizes their resource management. Specify the maximum number of concurrent streams to play. It supports loading audio resources from an Asset File Descriptor, package resource, file path, using a series of overloaded load methods. int maxStreams = 10; SoundPool sp = new SoundPool(maxStreams, AudioManager.STREAM_MUSIC, 0); int track1 = sp.load(this, R.raw.track1, 0); int track2 = sp.load(this, R.raw.track2, 0); int track3 = sp.load(this, R.raw.track3, 0);
  • 222. Bluetooth is a communications protocol designed for short-range, low-bandwidth peer-to-peer communications. Using the Bluetooth APIs, you can search for, and connect to, other Bluetooth devices within range. By initiating a communications link using Bluetooth Sockets, you can transmit and receive streams of data between devices from within your applications.
  • 223. The local Bluetooth device is controlled via the BluetoothAdapter class, which represents the host Android device on which your application is running. For accessing the default Bluetooth Adapter: BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter(); To read any of the local Bluetooth Adapter properties includes the BLUETOOTH permission in your application manifest. To modify any of the local device properties, the BLUETOOTH_ADMIN permission is also required: <uses-permission android:name=”android.permission.BLUETOOTH”/> <uses-permission android:name=”android.permission.BLUETOOTH_ADMIN”/>
  • 224. Use the isEnabled method to confirm the device is enabled, after which you can access the Bluetooth Adapter’s friendly name and hardware address, using the getName and getAddress methods, respectively: if (bluetooth.isEnabled()) { String address = bluetooth.getAddress(); String name = bluetooth.getName(); } To find a more detailed description of the current Bluetooth Adapter state, use the getStatemethod, which will return one of the following BluetoothAdapter constants:  STATE_TURNING_ON  STATE_ON  STATE_TURNING_OFF  STATE_OFF
  • 225. Android Bluetooth communications APIs are wrappers around RFCOMM, the Bluetooth radio frequency communications protocol. RFCOMM supports RS232 serial communication over the Logical Link Control and Adaptation Protocol (L2CAP) layer. RFCOMM communication channel for bidirectional communications using the following classes: BluetoothServerSocket — Used to establish a listening socket for initiating a link between devices. To establish a handshake, one device acts as a server to listen for, and accept, incoming connection requests. BluetoothSocket — Used to create a new client to connect to a listening Bluetooth Server Socket.
  • 226. Example: Listening for Bluetooth Socket connection requests private BluetoothSocket transferSocket; private UUID startServerSocket(BluetoothAdapter bluetooth) { UUID uuid = UUID.fromString(“a60f35f0-b93a-11de-8a39-08002009c666”); String name = “bluetoothserver”; try { final BluetoothServerSocket btserver = bluetooth.listenUsingRfcommWithServiceRecord(name, uuid); public void run() { try { // Block until client connection established. BluetoothSocket serverSocket = btserver.accept(); // Start listening for messages. listenForMessages(serverSocket); } catch (IOException e) { Log.e(“BLUETOOTH”, “Server connection IO Exception”, e); } } }
  • 227. BluetoothSocket class can be used on the client device to initiate a communications channel from within your application to a listening Bluetooth Server Socket. It is also returned by the Bluetooth Server Socket Listener after a connection to a client device has been established. Create a client-side Bluetooth Socket by calling createRfcommSocketToServiceRecord on a BluetoothDevice object that represents the target remote server device.
  • 228. To establish a Bluetooth Socket connection to a remote Bluetooth Device, the following conditions must be true: The remote device must be discoverable. The remote device must be accepting connections through a Bluetooth Server Socket. The local and remote devices must be paired (bonded).
  • 229.  private void connectToServerSocket(BluetoothDevice device, UUID uuid) {  try{  BluetoothSocket clientSocket = device.createRfcommSocketToServiceRecord(uuid);  // Block until server connection accepted.  clientSocket.connect();  // Start listening for messages.  listenForMessages(clientSocket);  // Add a reference to the socket used to send messages.  transferSocket = clientSocket;  }  catch (IOException e) {  Log.e(“BLUETOOTH”, “Bluetooth client I/O Exception”, e);  }}
  • 230.  With the speed, reliability, and cost of Internet connectivity being dependent on the network technology used (Wi-Fi, GPRS, 3G, LTE, and so on).  Android broadcasts Intents that allows to monitor changes in network connectivity and offers APIs that provide control over network settings and connections.  Android networking is principally handled via the ConnectivityManager, a Service that monitor the connectivity state, set your preferred network connection, and manage connectivity failover.
  • 231.  It represents the Network Connectivity Service.  It’s used to monitor the state of network connections, configure failover settings, and control the network radios.  To use the Connectivity Manager, application needs read and write network state access permissions: <uses-permission android:name=”android.permission.ACCESS_NETWORK_STATE”/> <uses-permission android:name=”android.permission.CHANGE_NETWORK_STATE”/>
  • 232.  To access the Connectivity Manager, use getSystemService, passing in Context.CONNECTIVITY_SERVICE as the service name, as shown below: String service = Context.CONNECTIVITY_SERVICE; ConnectivityManager connectivity = (ConnectivityManager)getSystemService(service);
  • 233. Supporting User Preferences for Background Data Transfers  To monitor changes in the background data setting, create and register a new Broadcast Receiver that listens for this Broadcast Intent, as listed below. registerReceiver( new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { boolean backgroundEnabled = connectivity.getBackgroundDataSetting(); setBackgroundData(backgroundEnabled); } }, new IntentFilter( ConnectivityManager.ACTION_BACKGROUND_DATA_SETTIN G_CHANGED) );
  • 234. Finding and Monitoring Network Connectivity  The Connectivity Manager provides a high-level view of the available network connections.  The getActiveNetworkInfo method returns a NetworkInfo object that includes details on the currently active network: // Get the active network information. NetworkInfo activeNetwork = connectivity.getActiveNetworkInfo();
  • 235. Finding and Monitoring Network Connectivity NetworkInfo activeNetwork = connectivity.getActiveNetworkInfo(); boolean isConnected = ((activeNetwork != null) &&(activeNetwork.isConnectedOrConnecting())); boolean isWiFi = activeNetwork.getType() == ConnectivityManager.TYPE_WIFI;  To monitor network connectivity, create a Broadcast Receiver that listens for ConnectivityManager.CONNECTIVITY_ACTION Broadcast Intents as, <receiver android:name=”.ConnectivityChangedReceiver” > <intent-filter> <action android:name=”android.net.conn.CONNECTIVITY_CHANGE”/> </intent-filter> </receiver>
  • 236.  It represents the Android Wi-Fi Connectivity Service,  It used to configure Wi-Fi network connections, manage the current Wi-Fi connection and monitor changes in Wi-Fi connectivity.  It describes how to use the WifiManager to monitor and control the device’s Wi-Fi connectivity specifically.
  • 237.  Access the Wi-Fi Manager using the getSystemService method, passing in the Context.WIFI_SERVICE constant, as shown below: String service = Context.WIFI_SERVICE; WifiManager wifi = (WifiManager)getSystemService(service); To Monitoring and changing Wi-Fi state if (!wifi.isWifiEnabled()) if (wifi.getWifiState() != WifiManager.WIFI_STATE_ENABLING) wifi.setWifiEnabled(true);
  • 238.  Wifi Manager to manage the configured network settings and control which networks to connect.  Get a list of the current network configurations using getConfiguredNetworks. // Get a list of available configurations List<WifiConfiguration> configurations = wifi.getConfiguredNetworks();
  • 239.  To connect to a Wi-Fi network, need to create and register a configuration.  Network configurations are stored as WifiConfiguration objects.  The following is a non exhaustive list of some of the public fields available for each Wi-Fi configuration:  BSSID — The BSSID for an access point  SSID — The SSID for a particular network  networkId — A unique identifier used to identify this network configuration on the current device  priority — To use when ordering the list of potential access points to connect to.
  • 240.  status — The current status of this network connection, which will be one of the following:  WifiConfiguration.Status.ENABLED, WifiConfiguration.Status.DISABLED, or  WifiConfiguration.Status.CURRENT
  • 241.  Wi-Fi Direct is a communications protocol designed for medium- range, high-bandwidth peer-to-peer communications.  By initiating a communications link using sockets, you can then transmit and receive streams of data between supported devices (including some printers, scanners, cameras, and televisions) and between instances of your application running on different devices.
  • 242.  To use Wi-Fi Direct, your application requires the ACCESS_WIFI_STATE, CHANGE_WIFI_STATE, and INTERNET permissions: <uses-permission android:name=”android.permission.ACCESS_WIFI_STATE”/> <uses-permission android:name=”android.permission.CHANGE_WIFI_STATE”/> <uses-permission android:name=”android.permission.INTERNET”/>
  • 243.  Wi-Fi Direct connections are initiated and managed using the WifiP2pManager system service, which you canaccess using the getSystemService method, passing in the Context.WIFI_P2P_SERVICE constant: wifiP2pManager=(WifiP2pManager)getSystemService(Context. WIFI_P2P_SERVICE);
  • 244.  private WifiP2pManager wifiP2pManager;  private Channel wifiDirectChannel;  private void initializeWiFiDirect() {  wifiP2pManager = (WifiP2pManager)getSystemService(Context.WIFI_P2P_SE RVICE);  wifiDirectChannel = wifiP2pManager.initialize(this, getMainLooper(),  new ChannelListener() {  public void onChannelDisconnected() {  initializeWiFiDirect();  } }  );  }
  • 245.  NFC is a contactless technology used to transmit small amounts of data across short distances.  NFC transfers can occur between two NFC-enabled devices, or between a device and an NFC “tag.  NFC messages are handled using the NFC Data Exchange Format (NDEF).  To read, write, or broadcast NFC messages, application requires the NFC manifest permission: <uses-permission android:name=”android.permission.NFC” />
  • 246.  When an Android device is used to scan an NFC tag,  System will decode the incoming payload using its own tag dispatch system  Analyzes the tag, categorizes the data  Uses an Intent to launch an application to receive the data.
  • 247.  NfcAdapter.ACTION_NDEF_DISCOVERED  NfcAdapter.ACTION_TECH_DISCOVERED- This action is broadcast when the NFC technology is known.  NfcAdapter.ACTION_TAG_DISCOVERED- If a tag is received from an unknown technology, it will be broadcast using this action.
  • 248.  <activity android:name=”.BlogViewer”>  <intent-filter>  <action android:name=”android.nfc.action.NDEF_DISCOVERED”/>  <category android:name=”android.intent.category.DEFAULT”/>  <data android:scheme=”http”  android:host=”blog.radioactiveyak.com”/>  </intent-filter>  </activity>