Download - Basic of Android
BASIC OF ANDROID
1. Introduction to Mobile Technologies
2. Introduction of Android
3. Android Building Blocks
4. Introduction of the Development tool “Eclipse”
5. Testing and Debugging Android Application
6. Android Activities
7. UI Design
8. Using Android system services
9. Database - SQLite
10.Broadcast
1. INTRODUCTION TO MOBILE TECHNOLOGY
INTRODUCTION TO MOBILE TECHNOLOGIES
1.1 Background about mobile technologies
1.2 Why to use Android for mobile development?
1.1 BACKGROUND ABOUT MOBILE TECHNOLOGIES
• Mobile technology is the technology used for
cellular communication.
• Since the start of this millennium, a standard mobile
device has gone from being no more than a simple
two-way pager to being a mobile phone, GPS
navigation device, an embedded web
browser and instant messaging client, and
a handheld game console.
• Many types of mobile operating systems (OS) are
available for smartphones,
including: Android, BlackBerry
OS, IOS, Symbian, Windows Mobile and Bada. Among
the most popular are the Apple iPhone, and Android.
1.1 MOBILE TECHNOLOGY (CONTD.)
ANDROID
• Android is an operating system based on Linux with
a Java programming interface.
• Android is a mobile operating system (OS)
developed by Google. Android is the first
completely open source mobile OS, meaning that it
is free to any cell phone carrier.
• Building on the contributions of the open-source
Linux community and more than 300 hardware,
software, and carrier partners, Android has rapidly
become the fastest-growing mobile OS.
ANDROID VERSIONS
Version Codename API
1.6 Donut 4
2.1 Eclair 7
2.2 Froyo 8
2.3 - 2.3.2Gingerbread
9
2.3.3 - 2.3.7 10
3.1Honeycomb
12
3.2 13
4.0.3 - 4.0.4Ice Cream
Sandwich15
4.1Jelly Bean
16
4.2 17
ANDROID MARKET SHARE
• Android Dominates Worldwide Smartphone Market,
Powers 80 Percent Of All Smartphones Shipped In
Q2
• A mobile application (or mobile app) is a software
application designed to run on smartphones, tablet
computers and other mobile devices.
• Mobile apps were originally offered for general
productivity and information retrieval, including
email, calendar, contacts, and stock market and
weather information.
Mobile Application
1.2 WHY TO USE ANDROID FOR MOBILE DEVELOPMENT?
Objective-C vs. Android (Java)
• First and foremost, using Java is much better than
Objective-C. Private methods, inner classes,
anonymous classes, generics, better function
syntax, and a much wider plethora of 3rd-party
code are just a small smattering of the advantages
of Java.
• Objective-C doesn't provide a garbage collector
for iPhone while Java has lazy garbage collector
WHY TO USE ANDROID FOR MOBILE DEVELOPMENT? (CONTD.)
• You have more control and the power of Java
allows you to write stricter code that accomplishes
these tasks with better software methodologies.
2. INTRODUCTION OF ANDROID
2. INTRODUCTION OF ANDROID
2.1 What does Android run On – Android
Internals?
2.2 Introduction of DVM (Dalvic Virtual
Machine)
2.3 Architecture of Android
2. INTRODUCTION OF ANDROID
2 .1 WHAT DOES ANDROID RUN ON – ANDROID
INTERNALS?
2.1 WHAT DOES ANDROID RUN ON –ANDROID INTERNALS?
LINUX KERNEL
• Android runs on Linux
• Linux provides as well as:• Hardware abstraction layer
• Application Framework
• Memory management
• Users never see Linux sub system
• The adb shell command opens Linux shell
LIBRARIES
• Bionic, a super fast and small license-friendly libc
library optimized for embedded use.
• Surface Manager for composing window manager
with off-screen buffering.
• WebKit: library for fast HTML rendering
•
DALVIK VM
Dalvik VM is Google’s implementation of Java
• Optimized for mobile devices.
• Key Dalvik differences:
• Register-based versus stack-based VM
• Dalvik runs .dex files
• More efficient and compact implementation
• Different set of Java libraries than SDK
APPLICATION FRAMEWORK
• Activation manager controls the life Applications
cycle of the app
• Content providers encapsulate data Application
Framework that is shared (e.g. contacts)
• Resource manager manages everything that is not
the code.
• Notification manager for events such as arriving
messages, appointments, etc.
APPLICATION
• Each Android application runs inside its own Linux
process.
• Additionally, each application has its own sandbox
file system with its own set of preferences and its
own database.
• Other applications cannot access any of its
data,unless it is explicitly shared.
•
APPLICATION(CONTD)
• There are three main scenarios for your app to talk
to native library:
• - Directly
• - Via native service
• - Via native daemon
• It will depend on the type of app and type of native
library which method works best.
APPLICATION FLOW
INTRODUCTION OF ANDROID
2 .2 INTRODUCTION OF DVM (DALVIC VIRTUAL
MACHINE)
2.2 INTRODUCTION OF DVM (DALVIC VIRTUAL MACHINE)
• Google developed Android and chose DVM for several reasons. First, there were licensing issues with most JVMs.
• DVM should be more efficient in terms of memory usage and performance on a register-based machine.
• DVM is also supposed to be more efficient when running multiple instances of the DVM. Applications are given their own instance. Hence, multiple active applications require multiple DVM instances. Like most Java implementations, the DVM has an automatic garbage collector.
INTRODUCTION OF ANDROID
2 .3 ARCHITECTURE OF ANDROID
2.3 ARCHITECTURE OF ANDROID
Android Java
=
Java SE – AWT/Swing + Android API
2.3 ARCHITECTURE OF ANDROID
• Many APIs are similars but you don't have all J2SE APIs.
• Many APIs are limited to Android (Contacts, Power Management, Graphics...);
• No Swing, no JavaFX ... You must use XML to declare you GUI;
• you can use java jars (if they use only compatible APIs) but they are converted into dalvik.
• Code is compiled into Dalvik opcodes (not java byte code);
3. ANDROID BUILDING BLOCKS
3. ANDROID BUILDING BLOCKS
3.1 Activity
3.2 Broadcast Receiver
3.3 Content Provider
3.4 Service
3.5 Introduction of Intent
3. ANDROID BUILDING BLOCKS
Each building block is a different point through which the system
can enter your application. Not all components are actual
entry points for the user and some depend on each other, but
each one exists as its own entity and plays a specific role—
each one is a unique building block that helps define your
application's overall behavior.
Activities
Services
Content providers
Broadcast receivers
3.1 ACTIVITY
• An Activity represents a single screen with a user
interface.
• An activity represents the visual representation of
an Android application.
• Activities use Views , i.e. user interface widgets as
for example buttons and fragments to create the
user interface and to interact with the user.
3.1 ACTIVITY
3.2 SERVICES
• Services perform tasks without providing a user
interface. They can communicate with other
Android components and notify the user via the
notification framework in Android.
• Service is a component that runs in the background
to perform long-running operations or to perform
work for remote processes.
• A service does not provide a user interface.
3.2 SERVICES (CONTD.)
• Note that services, like other application objects,
run in the main thread of their hosting process. This
means that, if your service is going to do any CPU
intensive (such as MP3 playback) or blocking (such
as networking) operations, it should spawn its own
thread in which to do that work
3.3 CONTENT PROVIDER
• A content provider manages a shared set of application
data. You can store the data in the file system, an SQLite
database, on the web, or any other persistent storage
location your application can access.
• A content provider provides a structured interface to
application data. Via a content provider your
application can share data with other applications.
• Android contains an SQLite database which is frequently
used in conjunction with a content provider . The SQLite
database would store the data, which would be
accessed via the content provider
3.4 BROADCAST RECEIVER
• Broadcast receivers can be registered to receive messages and intents which could be system generated or application level .
• A broadcast receiver gets notified by the Android system, if the specified event occurs.
• For example you can register a broadcast receivers for the event that the Android system completed the boot processor or for the event that the state of the phone changes, e.g. someone is calling.
3.5 INTRODUCTION TO INTENT
• Intents are asynchronous messages which allow the application to request functionality from other Android components, e.g. from services or activities
• An application can call a component directly ( explicit Intent ) or ask the Android system to evaluate registered components based on the intent data ( implicit intents ). For example the application could implement sharing of data via an Intent and all components which allow sharing of data would be available for the user to select. Applications register themselves to an intent via an intent Filter
• Intents allow an Android application to start and to interact with components from other Android applications.
4. INTRODUCTION DEVELOPMENT TOOL “ECLIPSE”
4. INTRODUCTION OF THE DEVELOPMENT TOOL “ECLIPSE”
4.1 Download the latest or working version of
“Eclipse”
4.2 Introduction to Android Simulator
4.3 How to create project?
4.4 First Project “Hello World”
4.5 Introduction to solution components
4.1 DOWNLOAD THE LATEST OR WORKING VERSION OF “ECLIPSE”
• The Android SDK provides you the API libraries and
developer tools necessary to build, test, and debug
apps for Android.
• http://developer.android.com/sdk/index.html
ANDROID DEVELOPMENT TOOLS
• Google provides the Android Development Tools (ADT) to develop Android applications with Eclipse.
• ADT is a set of components (plug-ins) which extend the Eclipse IDE with Android development capabilities.
• ADT contains all required functionalities to create, compile, debug and deploy Android applications from the Eclipse IDE. ADT also allows to create and start AVDs.
• The Android Development Tools (ADT) provides specialized editors for resources files, e.g. layout files.
• These editors allow to switch between the XML representation of the file and a richer user interface via tabs on the bottom of the editor.
4.2 INTRODUCTION TO ANDROID SIMULATOR
• To define an Android Virtual Device (ADV) open the
• AVD Manager dialog via Window Android Virtual
Device Manager and press the New button
AVD CONTINUE
RUN AVD
RUN AVD (CONTINUE)
4.3 HOW TO CREATE PROJECT?
• Create a very simple project
• Run it on a real device
• Run it on the emulator
• Examine its structure
PACKAGE CONTENT
52
Java code for our activityAll source code here
Generated Java codeHelps link resources to Java code
Layout of the activity
Strings used in the program
All non-code resources
Android Manifest
Images
4.4 FIRST PROJECT “HELLO WORLD”
package com.example.helloandroid;
import android.app.Activity;import android.os.Bundle;import android.widget.TextView;
public class HelloAndroid extends Activity {/** Called when the activity is first created. */@Overridepublic void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);TextView tv = new TextView(this);tv.setText("Hello, Android – by hand");setContentView(tv);
}}
53
Set the view “by hand” – from the program
Inherit from the Activity Class
RUN IT!
54
/RES/LAYOUT/MAIN.XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
</LinearLayout>
55
Further redirection to /res/values/strings.xml
/RES/VALUES/STRINGS.XML
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, HelloAndroid – by resources!</string>
<string name="app_name">Hello, Android</string>
</resources>
56
HELLOANDROID.JAVA
57
package com.example.helloandroid;
import android.app.Activity;
import android.os.Bundle;
public class HelloAndroid extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
Set the layout of the view as described in the main.xml layout
/GEN/R.JAVA
package com.example.helloandroid;
public final class R {public static final class attr {}public static final class drawable {
public static final int icon=0x7f020000;}public static final class id {
public static final int textview=0x7f050000;}public static final class layout {
public static final int main=0x7f030000;}public static final class string {
public static final int app_name=0x7f040001;public static final int hello=0x7f040000;
}}
58
RUN IT!
59
5. TESTING AND DEBUGGING ANDROID APPLICATION
5. TESTING AND DEBUGGING ANDROID APPLICATION
5.1 Role and Use of Dalvik Debug Monitor
Server (DDMS)
5.2 How to debug android application
5.3 Use of Step Filters, Breakpoints, Suspend
and Resume
5.4 How to use LogCat (Verbose, Debug, Info,
Warn, Error, Assert)
5.5 Use of Perspectives
5.1 ROLE OF DDMS
• Android ships with a debugging tool called the
Dalvik Debug Monitor Server (DDMS), which
provides port-forwarding services, screen capture
on the device, thread and heap information on the
device, logcat, process, and radio state
information, incoming call and SMS spoofing,
location data spoofing, and more.
5.2 HOW TO DEBUG ANDROID APPLICATION
• On Android, every application runs in its own process,
each of which runs in its own virtual machine (VM). Each
VM exposes a unique port that a debugger can attach
to.
• When DDMS starts, it connects to adb. When a device is
connected, a VM monitoring service is created
between adb and DDMS, which notifies DDMS when a
VM on the device is started or terminated. Once a VM is
running, DDMS retrieves the VM's process ID (pid),
via adb, and opens a connection to the VM's debugger,
through the adb daemon (adbd) on the device. DDMS
can now talk to the VM using a custom wire protocol.
5.3 USE OF STEP FILTERS, BREAKPOINTS, SUSPEND AND RESUME
5.4 HOW TO USE LOGCAT (VERBOSE, DEBUG, INFO, WARN, ERROR, ASSERT)
LOGCAT VIEW
5.5 USE OF PERSPECTIVES
6. ANDROID ACTIVITIES
6. ANDROID ACTIVITIES
6.1 Android Activity Lifecycle
6.2 Using Intents to Launch the Activities
ACTIVITY
• An Android activity is focused on a single
thing a user can do.
• Most applications have multiple activities
71
6.1 ANDROID ACTIVITY LIFECYCLE
AN ACTIVITY : THREE STATES
• Resumed The activity is in the foreground of the screen
and has user focus. (This state is also sometimes referred
to as "running".)
• Paused Another activity is in the foreground and has
focus, but this one is still visible. That is, another activity is
visible on top of this one and that activity is partially
transparent or doesn't cover the entire screen. A paused
activity is completely alive (the Activity object is retained
in memory, it maintains all state and member
information, and remains attached to the window
manager), but can be killed by the system in extremely
low memory situations.
73
• Stopped The activity is completely obscured by
another activity (the activity is now in the
"background"). A stopped activity is also still alive
(the Activity object is retained in memory, it maintains
all state and member information, but
is not attached to the window manager). However, it
is no longer visible to the user and it can be killed by
the system when memory is needed elsewhere.
• If an activity is paused or stopped, the system can
drop it from memory either by asking it to finish
(calling its finish() method), or simply killing its process.
When the activity is opened again (after being
finished or killed), it must be created all over.
74
AN ACTIVITY : THREE STATES (CONTD.)
TASKS AND BACK STACK
• Each activity should be designed around a
specific kind of action the user can perform and
can start other activities.
• For example, an email application might have
one activity to show a list of new email. When
the user selects an email, a new activity opens
to view that email.
75
6.2 USING INTENT TO LAUNCH THE ACTIVITIES
• Intent are asynchronous messages which allow the application to request functionality from other Android components, e.g. from services or activities
• An application can call a component directly (explicit Intent ) or ask the Android system to evaluate registered components based on the intent data ( implicit intents). For example the application could implement sharing of data via an intent and all components which allow sharing of data would be available for the user to select. Applications register themselves to an intent via an intentFilter .
• Intents allow an Android application to start and to interact with components from other Android applications.
• There are separate methods for activating each type of component:
• You can start an activity (or give it something new to do) by passing Intent to startActivity() or startActivityForResult() .
• You can start a service (or give new instructions to an ongoing service) by passing an Intent tostartService(). Or you can bind to the service by passing an Intent to bindService().
• You can initiate a broadcast by passing an Intent to methods like sendBroadcast(),sendOrderedBroadcast(), or sendStickyBroadcast().
• You can perform a query to a content provider by calling query() on a ContentResolver.
77
INTENT (CONTD.)
7. UI DESIGN
7. UI DESIGN
7.1 Fundamental Android UI Design
7.2 Introducing Layouts
7.3 Different UI widgets available in Android
7.4 Event driven Programming in Android
7.1 FUNDAMENTAL ANDROID UI DESIGN
• Layouts is important for good Android application
design.
• We provide an overview of how layouts fit into the
Android application architecture.
• We also explore some of the specific layout controls
available for organizing application screen content
in a variety of interesting ways
WHAT IS A LAYOUT?
• Android developers use the term layout to mean one of two things. Both definitions apply to this tutorial, and are, unfortunately used interchangeably in the Android development community.
The two definitions of layout are:• A type of resource that defines what is drawn on the screen.
Layout resources are stored as XML files in the /res/layout resource directory for the application. A layout resource is simply a template for a user interface screen, or portion of a screen, and contain.
• A type of View class whose primary purpose is to organize other controls. These layout classes (LinearLayout, RelativeLayout, TableLayout, etc. ) are used to display child controls, such as text controls or buttons or images on the screen.
7.2 INTRODUCING LAYOUTS
• Frame Layout
• Liner Layout
• Relative Layout
• Table Layout
FRAMELAYOUT
• Frame layouts are one of the simplest layout types
used to organize controls within the user interface of
an Android application.
• They are used less often than some other layouts,
simply because they are generally used to display
only one view, or views which overlap.
FRAMELAYOUT (CONTD.)
When to Use Frame Layouts
• The efficiency of a frame layout makes it a good
choice for screens containing few view controls
(home screens, game screens with a single canvas,
and the like).
• Sometimes other inefficient layout designs can be
reduced to a frame layout design that is more
efficient, while other times a more specialized
layout type is appropriate. Frame layouts are the
normal layout of choice when you want to overlap
views.
LINER LAYOUT
• Linear layouts are one of the simplest and most common types of layouts used by Android developers to organize controls within their user interfaces.
• The linear layout works much as its name implies: it organizes controls linearly in either a vertical or horizontal fashion.
• When the layout’s orientation is set to vertical, all child controls within it are organized in a single column; when the layout’s orientation is set to horizontal, all child controls within it are organized in a single row.
LINER LAYOUT(CONTD.)
Some specific attributes apply to linear layouts. Some
of the most important attributes you’ll use with linear
layouts include:
• The orientation attribute (required), which can be
set to vertical or horizontal
• The gravity attribute (optional), which controls how
all child controls are aligned and displayed within
the linear layout (class: LinearLayout)
• The layout_weight attribute (optional, applied to
each child control) specifies each child control’s
relative importance within the parent linear layout
(class: LinearLayout.LayoutParams)
LINER LAYOUT(CONTD.)
Also, general ViewGroup-style attributes apply to
linear layouts. These include:
• Generic Layout Parameters such as layout_height
(required) and layout_width (required)
• Margin Layout Parameters such as margin_top,
margin_left, margin_right and margin_bottom
• Layout Parameters such as layout_height and
layout_width (
RELATIVE LAYOUT
• The relative layout works much as its name implies: it
organizes controls relative to one another, or to the
parent control itself.
• What does this mean?
It means that child controls, such as ImageView, TextView
,and Button controls, can be placed above, below, to the left
or right, of one another. Child controls can also be placed in
relation to the parent (the relative layout container), including
placement of controls aligned to the top, bottom, left or right
edges of the layout
RELATIVE LAYOUT(CONTD.)
• Attributes that help configure a relative layout and its child controls. Some specific attributes apply to relative layouts-namely the child rules, including:
• Rules for child control centering within the parent layout, including: center horizontally, center vertically, or both.
• Rules for child control alignment within the parent layout, including: align with top, bottom, left or right edge of another control.
• Rules for child control alignment in relation to other child controls, including: align with top, bottom, left or right edge.
• Rules for child control placement in relation to other child controls, including: placement to the left or right of a specific control, or above or below another control.
RELATIVE LAYOUT(CONTD.)
Also, general ViewGroup-style attributes apply to relative layouts. These include:
• Generic Layout Parameters such as layout_height(required) and layout_width (required)
• Margin Layout Parameters such as margin_top, margin_left, margin_right and margin_bottom
• Layout Parameters such as layout_height and layout_width
TABLE LAYOUT
• A table layout is exactly what you might expect: a
grid of made up of rows and columns, where a cell
can display a view control. From a user interface
design perspective, a TableLayout is comprised of
TableRow controls—one for each row in your table.
• The contents of a TableRow are simply the view
controls that will go in each “cell” of the table grid.
TABLELAYOUT CONCERNS
• Although table layouts can be used to design entire
user interfaces, they usually aren’t the best tool for
doing so, as they are derived from LinearLayout
and not the most efficient of layout controls.
• If you think about it, a TableLayout is little more than
an organized set of nested LinearLayouts, and
nesting layouts too deeply is generally discouraged
for performance concerns.
• However, for data that is already in a format
suitable for a table, such as spreadsheet data,
table layout may be a reasonable choice.
7.3 DIFFERENT UI WIDGETS AVAILABLE IN ANDROID
• Text View
• Edit Text
• List View
• Spinner
• Button
• Check Box
• Radio Button
• Scroll View
TEXT VIEW
• Displays text to the user and optionally allows them
to edit it. A TextView is a complete text editor,
however the basic class is configured to not allow
editing.
EDIT TEXT
• EditText is a thin veneer over TextView that
configures itself to be editable.
LISTVIEW
• The display of elements in a lists is a very common
pattern in mobile applications. The user sees a list of
items and can scroll through them.
• ListView is a view group that displays a list of
scrollable items. The list items are automatically
inserted to the list using an Adapter that pulls
content from a source such as an array or
database query and converts each item result into
a view that's placed into the list.
LISTVIEW
SPINNERS
• Spinners provide a quick way to select one value
from a set. In the default state, a spinner shows its
currently selected value. Touching the spinner
displays a dropdown menu with all other available
values, from which the user can select a new one.
99
CHECK BOX
• Checkboxes allow the user to select one or more
options from a set. Typically, you should present
each checkbox option in a vertical list.
100
RADIO BUTTONS
• Radio buttons allow the user to select one option
from a set. You should use radio buttons for
optional sets that are mutually exclusive if you
think that the user needs to see all available
options side-by-side.
101
SCROLLVIEW
• The ScrollView class can be used to contain one
View that might be to big too fit on one screen.
ScrollView will is this case display a scroll bar to scroll
the context.
• A ScrollView is a FrameLayout, meaning you should
place one child in it containing the entire contents
to scroll; this child may itself be a layout manager
with a complex hierarchy of objects. A child that is
often used is a LinearLayout in a vertical orientation,
presenting a vertical array of top-level items that
the user can scroll through.
TOGGLE BUTTONS
• A toggle button allows the user to change a setting
between two states.
• You can add a basic toggle button to your layout
with theToggleButton object
103
EVENT DRIVEN PROGRAMMING IN ANDROID
There is a simple truth:
• Android (and other smartphone) programming isn’t
like desktop programming.
• Android applications aren’t really applications at
all, they are more like plugins into an existing
application. They don’t own execution and they
really shouldn’t do anything in the UI thread if they
can help it.
7.4 EVENT DRIVEN PROGRAMMING IN ANDROID
• At OS boot, a process called the Zygote is created.
This process waits for incoming requests for app
startups. Once it receives a request, it forks a VM
instance based on the Zygote VM itself. Thus every
app is its own process with it's own sandboxed VM.
• It is this VM process that starts the onCreate() (and
other relevant methods) which subsequently start
the app.
8.1 MENUS
Menus are a common user interface component in
many types of applications. To provide a familiar
and consistent user experience, you should use
the Menu APIs to present user actions and other
options in your activities.
• Options menu and action bar
• Context menu and contextual action mode
• Popup menu
106
OPTIONS MENU AND ACTION BAR
The options menu is the primary collection of menu items
for an activity. It's where you should place actions that
have a global impact on the app, such as "Search,"
"Compose email," and "Settings.“
• On Android 3.0 and higher, items from the options menu
are presented by the action bar as a combination of on-
screen action items and overflow options. Beginning with
Android 3.0, theMenu button is deprecated (some
devices don't have one), so you should migrate toward
using the action bar to provide access to actions and
other options.
107
CONTEXT MENU AND CONTEXTUAL ACTION MODE
A context menu is a floating menu that appears
when the user performs a long-click on an element.
It provides actions that affect the selected content
or context frame.
@2013 Training 108
POPUP MENU
A popup menu displays a list of items in a vertical list
that's anchored to the view that invoked the menu.
It's good for providing an overflow of actions that
relate to specific content or to provide options for a
second part of a command.
109
CREATING CONTEXTUAL MENUS
• A contextual menu offers actions that affect a specific
item or context frame in the UI. You can provide a
context menu for any view, but they are most often
used for items in a ListView, GridView, or other view
collections in which the user can perform direct actions
on each item.
There are two ways to provide contextual actions:
• floating context menu. A menu appears as a floating
list of menu items (similar to a dialog) when the user
performs a long-click (press and hold) on a view that
declares support for a context menu.
• In the contextual action mode. This mode is a system
implementation ofActionMode that displays
acontextual action bar at the top of the screen 110
CREATING A POPUP MENU
• A PopupMenu is a modal menu anchored to a View.
It appears below the anchor view if there is room, or
above the view otherwise.
It's useful for:
• Providing an overflow-style menu for actions
that relate to specific content Note: This is not the
same as a context menu, which is generally for
actions that affect selected content. For actions that
affect selected content.
• Providing a second part of a command sentence
(such as a button marked "Add" that produces a
popup menu with different "Add" options).
• Providing a drop-down similar to Spinner that does
not retain a persistent selection. 111
8.2 WHAT IS DIALOG?HOW TO CREATE AN ALERT 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.
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.
• AlertDialogA dialog that can show a title, up to
three buttons, a list of selectable items, or a
custom layout.
• DatePickerDialog or TimePickerDialogA dialog
with a pre-defined UI that allows the user to
select a date or time.
113
• These classes define the style and structure for
your dialog, but you should use
a DialogFragment as a container for your dialog.
TheDialogFragment class provides all the
controls you need to create your dialog and
manage its appearance, instead of calling
methods on the Dialog object.
114
DIALOG
CREATE AN ALERT DIALOG?
Creating alert dialog is very easy :
AlertDialog alertDialog = new AlertDialog.Builder(
AlertDialogActivity.this).create();
// Setting Dialog Title
alertDialog.setTitle("Alert Dialog");
// Setting Dialog Message
alertDialog.setMessage("Welcome to AndroidHive.info");
// Setting Icon to Dialog
alertDialog.setIcon(R.drawable.tick);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog closed
Toast.makeText(getApplicationContext(), "You clicked on OK", Toast.LENGTH_SHORT).show();
}
});
// Showing Alert Message
alertDialog.show();
8.3 WHAT IS TOAST IN ANDROID?
• A toast provides simple feedback about an
operation in a small popup.
• It only fills the amount of space required for the
message and the current activity remains visible
and interactive.
TOAST(CONTD.)
Sample Code :
Context context = getApplicationContext();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
8.4 LIST VIEW
• ListView is a view group that displays a list of
scrollable items.
• The list items are automatically inserted to the list
using an Adapter that pulls content from a source
such as an array or database query and converts
each item result into a view that's placed into the
list
ADAPTERS
• An Adapter acts as a bridge between an ListViewand the underlying data for that view.
• The Adapter provides access to the data items.
• The Adapter is also responsible for making a View for each item in the data set
System/Native Adapter available in Android
• ArrayAdapter
• CursorAdapter
• SimpleCursorAdapter
ARRAYADAPTER
• A concrete BaseAdapter that is backed by an array
of arbitrary objects.
• By default this class expects that the provided
resource id references a single TextView.
• If you want to use a more complex layout, use the
constructors that also takes a field id. That field id
should reference a TextView in the larger layout
resource
CURSORADAPTER
• Adapter that exposes data from a Cursor to a
ListView widget. The Cursor must include a column
named "_id" or this class will not work
SIMPLECURSOR ADAPTER
• An easy adapter to map columns from a cursor to
TextViews or ImageViews defined in an XML file.
• You can specify which columns you want, which
views you want to display the columns, and the XML
file that defines the appearance of these views.
8.5 NOTIFICATION MANAGER
• Class to notify the user of events that happen. This is
how you tell the user that something has happened
in the background.
Notifications can take different forms:
• A persistent icon that goes in the status bar and is
accessible through the launcher, (when the user
selects it, a designated Intent can be launched),
• Turning on or flashing LEDs on the device, or
• Alerting the user by flashing the backlight, playing a
sound, or vibrating.
NOTIFICATION MANAGER
• Each of the notify methods takes an int id parameter and optionally a String tag parameter, which may be null.
• These parameters are used to form a pair (tag, id), or (null, id) if tag is unspecified. This pair identifies this notification from your app to the system, so that pair should be unique within your app.
• If you call one of the notify methods with a (tag, id) pair that is currently active and a new set of notification parameters, it will be updated
8.6 PENDING INTENT
• A PendingIntent is a token that you give to a foreign application (e.g. NotificationManager, AlarmManager, Home Screen AppWidgetManager, or other 3rd party applications), which allows the foreign application to use your application's permissions to execute a predefined piece of code.
• If you give the foreign application an Intent, and that application sends/broadcasts the Intent you gave, they will execute the Intent with their own permissions. But if you instead give the foreign application a PendingIntentyou created using your own permission, that application will execute the contained Intent using your application's permission.
8.7 NOTIFICATION
• A notification is a message you can display to
the user outside of your application's normal UI.
When you tell the system to issue a notification, it
first appears as an icon in the notification area.
To see the details of the notification, the user
opens the notification drawer.
126
• A notification in normal view appears in an area that's up to 64 dp tall. Even if you create a notification with a big view style, it will appear in normal view until it's expanded. This is an example of a normal view:
The callouts in the illustration refer to the following:
1. Content title
2. Large icon
3. Content text
4. Content info
5. Small icon
6. Time that the notification was issued. You can set an explicit value with setWhen(); if you don't it defaults to the time that the system received the notification.
127
9. USING ANDROID SYSTEM SERVICES
9. SERVICE INTRO
• A Service is a component which runs in the
background, without interacting with the user.
• Services support true multitasking for Android, as
they can run in their own process.
• If you use threads in Activities their are still
connected to the life-cycle of Activities and the
Android system may decide to terminate them at
any point in point.
• You can declare your own Service to perform long
running operations without user interaction or to
supply functionality to other applications.
129
• A Service needs to be declared in
the AndroidManifest.xml via a <service
android:name="yourclasss"> </service> and the
implementing class must extend theService class
or one of its subclasses.
• A Service will not automatically run in its own
thread. Without the process attribute, they run the
main thread of their hosting process. Therefore
you should run performance intensive tasks in the
background.
130
SERVICE INTRO(CONTD.)
RUNNING A SERVICES IN ITS OWN PROCESS
• You can also specify that your Service runs in a
separate process via the
android:process =":process_description" attribute.
• This way the service gets its own process and has its
own memory. Any long running operation in
theService, e.g. a garbage collection, will not affect
the user interface of your Activity.
• The colon prefix before the name tells Android that
the Service is private to its declaring application. If
the colon is not used the Service would be a global
process and can be used by other components.
131
• <service
android:name="WordService"
android:process=":my_process"
android:icon="@drawable/icon"
android:label="@string/service_name" >
</service>
• The colon prefix before the name tells Android that
the Service is private to its declaring application. If
the colon is not used the Service would be a global
process and can be used by other components.
• Additionally, you can ensure that your service is
private to your application only if you include
theandroid:exported attribute and set it to "false".
132
FORMS OF SERVICE
• Started: A service is "started" when an application
component (such as an activity) starts it by
calling startService(). Once started, a service can run
in the background indefinitely, even if the
component that started it is destroyed. Usually, a
started service performs a single operation and does
not return a result to the caller.
• Bound :A service is "bound" when an application
component binds to it by calling bindService(). A
bound service offers a client-server interface that
allows components to interact with the service, send
requests, get results, and even do so across processes
with interprocess communication (IPC). A bound
service runs only as long as another application
component is bound to it. 133
INTENTSERVICE
• The IntentService is used to perform a certain task in
the background. Once done, the instance of
IntentService terminate itself automatically.
Examples for its usage would be to download a
certain resources from the Internet.
• The IntentService class offers
the onHandleIntent() method which will be
asynchronously called by the Android system.
134
SERVICE LIFECYCLE
135
To stop the service when its work is done, by calling stopSelf() orstopService().
• onCreate()The system calls this method when the service is first created, to perform one-time setup procedures (before it calls eitheronStartCommand() or onBind())
• onStartCommand()The system calls this method when another component, such as an activity, requests that the service be started, by calling startService().
• onBind()The system calls this method when another component wants to bind with the service (such as to perform RPC), by callingbindService().
• onDestroy()The system calls this method when the service is no longer used and is being destroyed. Your service should implement this to clean up any resources such as threads, registered listeners, receivers, etc
SERVICE LIFECYCLE
• Just like an activity, a service can define intent filters that allow other components to invoke the service using implicit intents. By declaring intent filters, components from any application installed on the user's device can potentially start your service if your service declares an intent filter that matches the intent another application passes to startService().
• An application component such as an activity can start the service by calling startService() and passing an Intent that specifies the service and includes any data for the service to use. The service receives this Intent in the onStartCommand() method. 137
SERVICE (CONTD.)
10. DATABASE - SQLITE
10. DATABASE - SQLITE
10.1 Introducing SQLite
10.2 SQLiteOpenHelper and creating a
database
10.3 Opening and closing a database
10.4 Working with cursors Inserts, updates, and
deletes
10.1 DATABASE - SQLITE
• SQLite is an Open Source database.
• SQLite supports standard relational database
features like SQL syntax, transactions and prepared
statements. The database requires limited memory
at runtime (approx. 250 KByte) which makes it a
good candidate from being embedded into other
runtimes.
SQLITE IN ANDROID
• SQLite is embedded into every Android device. Using an SQLite database in Android does not require a setup procedure or administration of the database.
• You only have to define the SQL statements for creating and updating the database. Afterwards the database is automatically managed for you by the Android platform.
• Access to an SQLite database involves accessing the file system. This can be slow. Therefore it is recommended to perform database operations asynchronously
• If your application creates a database, this database is by default saved in the directoryDATA/data/APP_NAME/databases/FILENAME.
10.2 SQLITEOPENHELPER AND CREATING A DATABASE
• To create and upgrade a database in your Android
application you create a subclass of the
SQLiteOpenHelper class. In the constructor of your
subclass you call the super() method of
SQLiteOpenHelper, specifying the database name
and the current database version
SQLITEOPENHELPER
In this class you need to override the following methods to create and update your database.
• onCreate() - is called by the framework, if the database is accessed but not yet created.
• onUpgrade() - called, if the database version is increased in your application code. This method allows you to update an existing database schema or to drop the existing database and recreate it via the onCreate() method.
SQLITEDATABASE
SQLiteDatabase is the base class for working with a SQLite database in Android and provides methods to open, query, update and close the database.
• More specifically SQLiteDatabase provides the insert(), update() and delete() methods.
• In addition it provides the execSQL() method, which allows to execute an SQL statement directly.
• The object ContentValues allows to define key/values. The key represents the table column identifier and the value represents the content for the table record in this column. ContentValues can be used for inserts and updates of database entries.
• Queries can be created via the rawQuery() and query()
methods or via the SQLiteQueryBuilder class .
• rawQuery() directly accepts an SQL select statement as
input.
• query() provides a structured interface for specifying the
SQL query.
• SQLiteQueryBuilder is a convenience class that helps to
build SQL queries.
SQLITEDATABASE
RAWQUERY()
rawQuery() Example
The following gives an example of a rawQuery() call.
• Cursor cursor =
getReadableDatabase().rawQuery("select * from
todo where _id = ?", new String[] { id });
QUERY()
query() Example
The following gives an example of a query() call.
• return database.query(DATABASE_TABLE,
new String[] { KEY_ROWID, KEY_CATEGORY,
KEY_SUMMARY, KEY_DESCRIPTION }, null, null, null,
null, null);
10.3 OPENING AND CLOSING A DATABASE
SQLiteDatabase db = this.getWritableDatabase();
//Opening DatabaseConnection
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName()); // Contact Name
values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone Number
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
WORKING WITH CURSORS INSERTS, UPDATES, AND DELETES
Cursor
• A query returns a Cursor object. A Cursor represents the result of a query and basically points to one row of the query result. This way Android can buffer the query results efficiently; as it does not have to load all data into memory.
• To get the number of elements of the resulting query use the getCount() method.
• To move between individual data rows, you can use the moveToFirst() and moveToNext() methods. The isAfterLast() method allows to check if the end of the query result has been reached.
10.4 WORKING WITH CURSORS INSERTS, UPDATES, AND DELETES
• Cursor provides typed get*() methods, e.g. getLong(columnIndex), getString(columnIndex) to access the column data for the current position of the result. The "columnIndex" is the number of the column you are accessing.
• Cursor also provides the getColumnIndexOrThrow(String) method which allows to get the column index for a column name of the table.
• A Cursor needs to be closed with the close() method call.
INSERT
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_COMMENT,
comment);
long insertId =
database.insert(MySQLiteHelper.TABLE_COMMENTS,
null, values);
cursor.close();
return newComment;
DELETE
database.delete(MySQLiteHelper.TABLE_COMMENTS,
MySQLiteHelper.COLUMN_ID + " = " + id, null);
CONTENT PROVIDER AND SHARING DATA
• A SQLite database is private to the application which creates it. If you want to share data with other applications you can use a content provider.
• A content provider allows applications to access data. In most cases this data is stored in an SQlite database.
• While a content provider can be used within an application to access data, its is typically used to share data with other application. As application data is by default private, a content provider is a convenient to share you data with other application based on a structured interface.
• A content provider must be declared in the AndroidManifest.xml file.
ACCESSING A CONTENT PROVIDER
The access to a content provider is done via an URI.
The basis for the URI is defined in the declaration of the
ContentProvider in the AndroidManifest.xml file via the
android:authorities attribute.
• To create your own ContentProvider you have to
define a class which
extendsandroid.content.ContentProvider.
• You also declare your ContentProvider in
the AndroidManifest.xmlfile. This entry must specify
the android:authorities attribute which allows to
identify the ContentProvider. This authority is the basis
for the URI to access data and must be unique.
11. BROADCAST
11 .BROADCAST
11.1 System broadcast
11.2 User defined broadcast
BROADCAST
• A broadcast receiver (receiver) can be registered
to receive system messages and intents. A receiver
gets notified by the Android system, if the specified
event occurs.
• For example you can register a receiver for the
event that the Android system finished the boot
process. Or you can register for the event that the
state of the phone changes, e.g. someone is
calling.
BROADCAST
• A receiver can be registered via the AndroidManifest.xml file.
• Alternatively to this static registration, you can also register a broadcast receiver dynamically via the Context.registerReceiver() method.
• The implementing class for a receiver extends the BroadcastReceiver class.
• If the event for which the broadcast receiver has registered happens the onReceive() method of the receiver is called by the Android system.
LIFECYCLE OF A BROADCAST RECEIVER
• After the onReceive() of the BroadcastReceiver has
finished, the Android system can recycle the
BroadcastReceiver.
• Before API 11 you could not perform any
asynchronous operation in the onReceive() method
because once the onReceive() method is finished
the Android system was allowed to recyled that
component. If you have potentially long running
operations you should trigger a service for that
11.1 SYSTEM BROADCAST
• Several system events are defined as final static fields in the Intent class. Other Android system classes also define events, e.g. the TelephonyManager defines events for the change of the phone state.
The following table lists a few important system events.
• Intent.ACTION_BOOT_COMPLETED : Boot completed. Requires the android.permission.RECEIVE_BOOT_COMPLETEDpermission.
• Intent.ACTION_POWER_CONNECTED : Power got connected to the device.
• Intent.ACTION_POWER_DISCONNECTED : Power got disconnected to the device.
• Intent.ACTION_BATTERY_LOW : Battery gets low, typically used to reduce activities in your app which consume power.
• Intent.ACTION_BATTERY_OKAY : Battery status good again.
11.2 USER DEFINED BROADCAST
• You can register a receiver for your own customer
actions.
The following AndroidManifest.xml file shows a
broadcast receiver which is registered to a custom
action.
<receiver android:name="MyReceiver" > <intent-filter>
<action
android:name="de.vogella.android.mybroadcast" />
</intent-filter> </receiver>
SENDING BROADCAST INTENTS
The sendBroadcast() method from the Context class allows you to send intents to your registered receivers. The following coding show an example.
Intent intent = new Intent();intent.setAction("de.vogella.android.mybroadcast");sendBroadcast(intent);
// handler for received Intents for the "my-event" event privateBroadcastReceiver mMessageReceiver = new BroadcastReceiver() { @Overridepublic void onReceive(Context context, Intent intent){ // Extract data included in the Intent String message =
intent.getStringExtra("message"); Log.d("receiver", "Got message: " + message);}};