Android Programing Course Material

196
Android Programming Written by: Shady Selim

Transcript of Android Programing Course Material

Page 1: Android Programing Course Material

Android Programming

Written by: Shady Selim

Page 2: Android Programing Course Material

Table of ContentsModule I................................................................................................................7Getting Started....................................................................................................7

Importance of mobile applications development..............................................8

Define difference between desktop and mobile SW development.............................9

Some software and hardware vendors.....................................................................10development..................................................................................................10

Pros and cons of different platform..........................................................................12development..................................................................................................12

Special considerations for mobility...........................................................................15Mobile Platforms............................................................................................16development..................................................................................................16

Difference between various mobile platforms..........................................................18development..................................................................................................18

Market share of various mobile platforms................................................................19Android...........................................................................................................20What is Android and why develop for it?........................................................20

Why people use their mobile phones.......................................................................21

Android Advantage...................................................................................................22

Android Disadvantage..............................................................................................23

The Android Architecture.........................................................................................24Android development tools.............................................................................26

Android Development Requirement.........................................................................26

Android SDK download and setup...........................................................................27Android SDK Manager...................................................................................28

Android Project Main Parts in Eclipse......................................................................29Setting up development environment.............................................................31

Creating your first app..............................................................................................31

Creating Android Virtual Devices (AVDs).................................................................31

Module II.............................................................................................................32Activities, Fragments, and Intents..................................................................32

Understanding activities and application manifest file....................................33

Understanding activities...........................................................................................33

Page 3: Android Programing Course Material

Manifest....................................................................................................................34Activity lifecycle and configuration.................................................................35

Activity lifecycle........................................................................................................35

Activity Reconfiguration............................................................................................37Parse XML format..........................................................................................38

XML creation............................................................................................................38Intent Class....................................................................................................40

Intent Definition........................................................................................................40Linking activities using intents........................................................................41

Linking Activities.......................................................................................................41Permissions...................................................................................................42Fragments......................................................................................................43Displaying notifications...................................................................................44

Module III............................................................................................................45Android User Interface......................................................................................45

Fundamentals and layouts.............................................................................46

Understanding the screen components....................................................................46

A layout defines the visual structure for a user interface, such as the UI for an activity or app widget. You can declare a layout in two ways:.............................46

Layouts.....................................................................................................................47

LinearLayout............................................................................................................48

RelativeLayout.........................................................................................................49

TableLayout.............................................................................................................50

FrameLayout and AbsoluteLayout...........................................................................51Understanding the screen components.........................................................52

Common widgets.....................................................................................................52

Java and XML code.................................................................................................53User navigation (click, touch, drag, etc...)......................................................54

Gesture....................................................................................................................55

Views and Events.....................................................................................................56

Events Listeners.......................................................................................................57Adapting to display orientation.......................................................................58Utilizing the action bar....................................................................................59Creating the user interface programmatically................................................60

Page 4: Android Programing Course Material

Listening for UI notifications...........................................................................61

ActionListeners.........................................................................................................61Using basic views, image views, and menus.................................................64

TextView..................................................................................................................64

Linkify elements.......................................................................................................65

EditText....................................................................................................................66

Button and CompoundButton...................................................................................67

CheckedTextView....................................................................................................68

Menu: outline............................................................................................................69

Menu: creating a menu............................................................................................70

The declarative approach.........................................................................................71

Other elements …....................................................................................................72Displaying pictures and managing drawing areas..........................................73

ImageView...............................................................................................................73

Module IV...........................................................................................................74Sensors..............................................................................................................74

Types.............................................................................................................75Using sensors and the sensor manager........................................................76Types.............................................................................................................76Monitoring a device’s movement and orientation...........................................77Calculating orientation using the accelerometer and magnetic field sensors.78Location and maps.........................................................................................79

Module V............................................................................................................80Bluetooth, NFC, Networks, and Wi-Fi.............................................................80

Bluetooth communications.............................................................................81Transmitting data using Bluetooth sockets....................................................82Managing Wi-Fi and its configurations...........................................................84Transferring data using Wi-Fi direct...............................................................85Near field communication...............................................................................86

Module VI...........................................................................................................87I/O file.................................................................................................................87

Access local files............................................................................................88Read local files...............................................................................................89Write files.......................................................................................................90

Module VII..........................................................................................................91

Page 5: Android Programing Course Material

Database............................................................................................................91SQLite: how?............................................................................................................94

SQLite: better to use constants................................................................................96

SQLite: creation code...............................................................................................97

SQLite: insert code...................................................................................................98

SQLite: delete code..................................................................................................99

SQLite: update code..............................................................................................100

SQLite: search code...............................................................................................101

Cursors: data handlers...........................................................................................102

Cursors: methods...................................................................................................103The Calendar Provider is a repository for a user's calendar events. The Calendar Provider API allows you to perform query, insert, update, and delete operations on calendars, events, attendees, reminders, and so on....................................106

Module VIII.......................................................................................................107Networking.......................................................................................................107

HTTP Classes........................................................................................................109

Parsing JSON........................................................................................................111

Module IX.........................................................................................................113Module X..........................................................................................................117Audio and Video..............................................................................................117

Media API...............................................................................................................118

MediaRecorder.......................................................................................................123

Video......................................................................................................................125

Sounds...................................................................................................................126

Video......................................................................................................................127

Module XI.........................................................................................................128Monetizing, Promoting,...................................................................................128And Distributing Applications........................................................................128

Distribution Control.................................................................................................132

Module XII........................................................................................................137Android Kit-Kat................................................................................................137

Android KitKat........................................................................................................138

Full-screen Immersive mode..................................................................................150

Page 6: Android Programing Course Material

Transitions framework for animating scenes..........................................................151

Translucent system UI styling................................................................................152

Enhanced notification access.................................................................................152

Chromium WebView..............................................................................................153

Screen recording....................................................................................................154

Resolution switching through adaptive playback....................................................154

Common Encryption for DASH...............................................................................154

HTTP Live Streaming.............................................................................................155

Audio Tunneling to DSP.........................................................................................155

Audio monitoring....................................................................................................156

Loudness enhancer................................................................................................156

Audio timestamps for improved AV sync................................................................156

Wi-Fi CERTIFIED Miracast™.................................................................................156

Module XIII.......................................................................................................157Business, UX, & Marketing............................................................................157

Overview................................................................................................................158

Overview................................................................................................................167

Overview................................................................................................................173

Resources........................................................................................................178

Page 7: Android Programing Course Material

Module IGetting Started

Page 8: Android Programing Course Material

What is Mobility?

is the technology used for cellular communication. Mobile code division multiple access (CDMA) technology has evolved rapidly over the past few years. 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 experts argue that the future of computer technology rests in mobile computing with wireless networking. Mobile computing by way of tablet computers are becoming more popular. Tablets are available on the 3G and 4G networks.

Importance of mobile applications development

Page 9: Android Programing Course Material

Same programming frameworks, different tools and hardware

Recently, mobile programming has grown 10 times faster than desktop programming. Though development on a desktop or a mobile both use of common programming frameworks like C++ and web, the actual environments and tools differ a lot. When a desktop programmer or web programmer tries to jump into mobile programming, they very soon realize the fundamental differences between the two environments. A modest personal PC today has, at least, a 1GHz processor, 1 GB of RAM, and a few gigabytes of disk storage

Network coverage is not reliable

Temporary lack of network coverage is a problem when dealing with mobile computing. When a user is on the move he travels through various physical locations that cause varying network coverage. This can be caused by physical obstructions or lack of sufficient network infrastructure.

Personalization is important.

The mobile device is always ON and connected with network. The device is more personal and not shared with other users. Therefore the application must be easily customized and personalized. One must be very selective on application color and their combinations.

Define difference between desktop and mobile SW development

Page 10: Android Programing Course Material

Hardware

Sony

HP

Dell

Samsung

Apple

Nokia

Software Operating System

Microsoft Windows

Apple Mac

Google Android

Some software and hardware vendorsdevelopment

Page 11: Android Programing Course Material

Linux ubuntu

Page 12: Android Programing Course Material

Android (Google)

Pros:

Global market share. Android is the undisputed world leader, with about 54 percent of the global smart phone market (as of Q4 2012). This is especially worth considering if you have a lot of international real estate clients or listings.

Google integration. As Google’s native mobile OS, Android is obviously deeply integrated with your Gmail and Google Apps accounts, tools of choice among many real estate professionals. Consequently, Android does a better job of syncing your settings and files across devices than any other platform.

Mapping. With system-wide Google Maps integration built in and turn-by-turn directions as a standard feature, Android is ideal for real estate professionals who rely on mapping when working out in the field.

Cons:

Software fragmentation. Because it’s implemented across a variety of devices made by multiple manufacturers, OS updates and fixes are often pushed to Android devices unevenly. The wide spectrum of device specifications in terms of screen resolution and capability also contributes to buggier app performance.

Few real estate apps. Currently, Apple simply has better offerings when it comes to apps for real estate professionals, such as Happy Inspector. That said, Android’s market share means it’s never far behind for developers.

IOS (Apple)

Pros:

Domestic market share. As of February 2013, Apple’s iOS is the platform of choice for American smartphone users, with over 50 percent of market share. One of the best aspects of iOS is the ability to share in Apple-exclusive features like iMessenger’s group chat. Go with another platform, and you could be missing out.

Hardware/software integration. Whether you’re on an iPhone or an iPad, Apple’s platform is designed from the ground up for its own hardware, which translates to a much more seamless and bug-free experience for users.

Strong app and peripheral ecosystem. Android is close behind, but iOS offers more high-quality apps than any other platform, and app developers almost

Pros and cons of different platformdevelopment

Page 13: Android Programing Course Material

always build their software for iOS first. Apple’s “cool” factor also gives it the strongest market for accessories like cases, camera lenses, etc.

Cons:

Limited multitasking. iOS is built for simplicity, not productivity. Simply put, iOS users can’t do two things at once. There are no widgets or tiles to provide live app information at a glance, and users must exit one app and return to the home screen in order to access another.

Lack of customizability. The flip side of Apple’s simplicity and integration is that users have to do things their way. The platform only supports a limited number of file types, and power users will miss the ability to customize their layout and alert profiles, as well as advanced features like file management.

Price. Apple’s devices are among the most expensive on the market. They also lack a number of hardware features that have become standard on other platforms, such as Wi-Fi tethering and hotspots, expandable SD storage, and near-field communication (NFC).

Windows Phone (Microsoft)

Pros:

Windows and Office integration. Windows Phone integrates deeply with Microsoft programs that many real estate professionals use heavily, including Word, Excel, PowerPoint, and Outlook. The platform is also uniform across phones, tablets, and PCs, making it easier to sync and work on multiple devices.

Dynamic interface. Window Phone’s unique interface of live tiles allows for a quick, real-time view of your latest emails, tweets, and other data without having to enter the apps themselves, saving users' time and effort.

Cons:

Lowest market share. Despite a major ad and publicity push and flagship mobile devices like the Surface tablet, Windows Phone still has the lowest market share on this list with just 3 percent.

Limited apps. Windows Phone has 125,000 apps, while the Windows 8 OS for Surface and PC is approaching 40,000. Still, this pales in comparison to Android and iOS, and some key players, most notably Google, have no plans to develop anything for the platform.

Few device options. While devices like the Nokia Lumia 920 and HTC 8X have received great reviews, Windows Phone still doesn’t offer the breadth of devices and accessories that Android has

Page 14: Android Programing Course Material

BlackBerry 10 (BlackBerry)

Pros:

Messaging. BlackBerry has always been strong when it comes to messaging, and the company continues this tradition with BB10, improving BBM and email. The keyboard software on the new Z10 has also been praised for its ease of use.

Multitasking abilities. BlackBerry 10 may be the best OS on this list for productivity. Its all-touch interface enables better multitasking than any other platform, allowing users to seamlessly switch between up to 8 active apps.

Enterprise and security. BlackBerry still provides the best security for browsing and user data, a crucial consideration in the real estate world. Continuing this tradition, BB10’s enterprise edition will offer Balance, which partitions your phone into personal and work profiles and encrypts your data.

Cons:

Brand new and untested. Despite its long development history, BlackBerry 10 is a fundamentally new platform rather than an incremental update. As such, it’s bound to have a few bugs and issues in the coming months as it’s tested out in the real world.

Fewest apps. 70,000 is a lot of apps out of the gate, and the company has worked hard to court developers. Nevertheless, BlackBerry 10, like Windows Phone, lacks several major apps, such as Instagram, Spotify, and Google Maps.

Company health. After 18 months without a major hardware or software release, BlackBerry new products represent a major gambit. If the ambitious new OS and phones don’t pan out, the company’s long-term viability could be questionable.

Page 15: Android Programing Course Material

Special considerations for mobility Platform limitations consideration

Small Screen Consideration

Data Considerations

Touch Considerations

Internet Connection Considerations

Storage Considerations

Sharing Considerations

Page 16: Android Programing Course Material

Security Considerations

The first truly open and comprehensive platform for mobile devices. It includes an operating system, user-interface and applications — all of the software to run a mobile phone but without the proprietary obstacles that have hindered mobile innovation.

More recently, Android has expanded beyond a pure mobile phone platform to provide a development platform for an increasingly wide range of hardware, including tablets and televisions.

Put simply, Android is an ecosystem made up of a combination of three components:

A free, open-source operating system for embedded devices

An open-source development platform for creating applications

Devices, particularly mobile phones, that run the Android operating system and the applications created for it

More specifically, Android is made up of several necessary and dependent parts, including the following:

A Compatibility Definition Document (CDD) and Compatibility Test Suite (CTS) that

Describe the capabilities required for a device to support the software stack.

A Linux operating system kernel that provides a low-level interface with the hardware, memory management, and process control, all optimized for mobile and embedded devices.

Open-source libraries for application development, including SQLite, WebKit, OpenGL, and a media manager.

A run time used to execute and host Android applications, including the Dalvik Virtual

Machine (VM) and the core libraries that provide Android-specific functionality. The run

Time is designed to be small and efficient for use on mobile devices.

An application framework that agnostically exposes system services to the application layer,

Including the window manager and location manager, databases, telephony, and sensors.

A user interface framework used to host and launch applications.

A set of core pre-installed applications.

Mobile Platformsdevelopment

Page 17: Android Programing Course Material

Mobile computing

Is a human–computer interaction by which a computer is expected to be transported during normal usage? Mobile computing involves mobile communication, mobile hardware, and mobile software. Communication issues include ad hoc and infrastructure networks as well as communication properties, protocols, data formats and concrete technologies. Hardware includes mobile devices or device components. Mobile software deals with the characteristics and requirements of mobile applications.

Page 18: Android Programing Course Material

IOS – previously known as iPhone and created by Apple. It was one of the first and so has the highest number of apps in its store, with over 800,000 available from functional apps to games and novelties. It is unique in that their apps will only work on Apple technology.

Android – this was developed and released only just after IOS and is similar in that a large number, if not as many apps are available on its store. The advantage of Android is that it can be used a wider variety of devices and so is becoming one of the most widely used platform.

Windows – a familiar name because of the computer software package. It is more recently released; only widely used in the last 2 years. Windows also have their own phone and has a new interface that has been marketed extensively and uses modern design language.

Symbian – this is a flexible platform in that it can be used in most major phone and tablet models. It was originally the most widely used flexible platform, but was overtaken in popularity by android in 2010.

Blackberry – carries out all of the fundamental functions of a smartphone such as calling, texting, taking photos, accessing the internet and emails and using apps, but markets itself as a ‘digital personal assistant’ and as such became more popular as a work smartphone for people who need to access their work on the move.

Difference between various mobile platforms.development

Page 19: Android Programing Course Material

Android does have the biggest share dueto its various version and the large numberof companies that adopt it system in their smart phones.

http://www.gartner.com/it/page.jsp?id=1848514

Market share of various mobile platforms

Page 20: Android Programing Course Material

Android

Android is a mobile operating system that is based on a modified version of Linux. It was originally developed by a startup of the same name, Android, Inc. In 2005, as part of its strategy to enter the mobile space, Google purchased Android and took over its development work

Mobile devices example:

Smartphones

Tablets

Readers

What is Android and why develop for it?

Page 21: Android Programing Course Material

WHY DEVELOP FOR ANDROID?

Android represents a clean break, a mobile framework based on the reality of modern mobile

Devices designed by developers, for developers.

With a simple, powerful, and open SDK, no licensing fees, excellent documentation, and a thriving

Developer community, Android represents an opportunity to create software that changes how and

Why people use their mobile phones. The barrier to entry for new Android developers is minimal:

No certification is required to become an Android developer.

Google Play provides free, up-front purchase, and in-app billing options for distribution and

Monetization of your applications.

There is no approval process for application distribution.

Developers have total control over their brands.

Page 22: Android Programing Course Material

Android is open, because it is Linux based open source so it can be developed by anyone.

Easy access to the Android App Market: Android owners are people who love to learn the phone, with Google's Android App Market you can download applications for free.

Populist Operating System: Android Phones, different from the iOS is limited to the iphone from Apple, then Android has many manufacturers, with their respective flagship gadget from HTC to Samsung.

USB full facilities. You can replace the battery, mass storage, DiskDrive, and USB tethering.

Easy in terms of notification: the operating system is able to inform you of a new SMS, Email, or even the latest articles from an RSS Reader.

Supports all Google services: Android operating system supports all of google services ranging from Gmail to Google reader. all google services can you have with one operating system, namely Android.

Install ROM modification: There are many custom ROM that you can use on Android phones, and the guarantee will not harm your device.

Android Advantage

Page 23: Android Programing Course Material

Connected to the Internet: Android can be said is in need of an active internet connection. At least there should be a GPRS internet connection in your area, so that the device is ready to go online to suit our needs.

Sometimes slow device company issued an official version of Android your own.

Android Market is less control of the manager, sometimes there are malware.

As direct service providers, users sometimes very difficult to connect with the Google.

Sometimes there are ads: because it is easy and free, sometimes often a lot of advertising. In appearance it does not interfere with the performance of the application itself, as it sometimes is in the top or bottom of the application.

Wasteful Batteries, This is because the OS is a lot of "process" in the background causing the battery quickly drains.

Android Disadvantage

Page 24: Android Programing Course Material

1. Applications— at this top layer, you will find applications that ship with the Android device (such as Phone, Contacts, Browser, etc.), as well as applications that you download and install from the Android Market. Any applications that you write are located at this layer

2. Application framework— exposes the various capabilities of the Android OS to application developers so that they can make use of them in their applications.

3. Android runtime— at the same layer as the libraries, the Android runtime provides a set of core libraries that enable developers to write Android apps using the Java programming language. The Android runtime also includes the Dalvik virtual machine, which enables every Android application to run in its own

1

2

3

4

5

The Android Architecture

Page 25: Android Programing Course Material

process, with its own instance of the Dalvik virtual machine (Android applications are compiled into Dalvik executables). Dalvik is a specialized virtual machine designed specifically for Android and optimized for battery-powered mobile devices with limited memory and CPU.

4. Libraries— these contain all the code that provides the main features of an Android OS. For example, the SQLite library provides database support so that an application can use it for data storage. The WebKit library provides functionalities for web browsing.

5. Linux kernel— this is the kernel on which Android is based. This layer contains all the low-level device drivers for the various hardware components of an Android device.

Page 26: Android Programing Course Material

The ADT is an extension to the Eclipse IDE that supports the creation and debugging of Android Applications. Using the ADT, you will be able to do the following in Eclipse:

Create new Android application projects.

Access the tools for accessing your Android emulators and devices.

Compile and debug Android applications.

Export Android applications into Android Packages (APKs).

Create digital certificates for code-signing your APK.

Android Development Requirement

Linux/MacOS X/Windows? Doesn't matter

Android SDK

Eclipse, not mandatory but can help

Eclipse Plugin

An Android device is not required

Android development tools

Page 27: Android Programing Course Material

Android SDK download and setup1. Go to http://developer.android.com/sdk/index.html

2. Download the SDK according to your OS

3. Unpack it

Page 28: Android Programing Course Material

The Android SDK Manager manages the various versions of the Android SDK currently installed on your computer. When it is launched, you will see a list of items and whether or not they currently installed on your computer Check the relevant tools, documentation, and platforms you need for your project. Once you have selected the items you want, click the Install button to download them. Because it takes a while to download from Google’s server, it is a good idea to download only what you need immediately, And download the rest when you have more time. For now, you may want to check the items shown in the figure.

It enables updating your SDK to the latest Android version.

It also enables downloading extra plugin for more programming features and capabilities, e.g.: USB plugin.

Android SDK Manager

Page 29: Android Programing Course Material

Android Project Main Parts in Eclipse

Project name Src folder with java files Auto-generated files Android's base files Compiled files Resources files Android Manifest

Page 30: Android Programing Course Material

The various folders and their files are as follows:

➤ SRC— Contains the .java source files for your project.

In this example, there is one fi le, HelloWorldActivity.java. The HelloWorldActivity.java file is the

Source fi le for your activity. You write the code for your Application in this file. The Java fi le is listed under the Package name for your project, which in this case is net.learn2develop.HelloWorld.

➤ Gen— Contains the R.java file, a compiler-generated file that references all the resources found in your project.

You should not modify this fi le. All the resources in your Project are automatically compiled into this class so that you can refer to them using the class.

➤ Android 4.0library — this item contains one file, android.jar, which contains all the class libraries needed for an Android application.

➤ Assets— this folder contains all the assets used by your application, such as HTML, text fi les, databases, etc.

➤ Bin— this folder contains the fi les built by the ADT during the build process. In particular, it generates the .apk file (Android Package). An .apk file is the application binary of an Android application. It contains everything needed to run an Android application.

Res— this folder contains all the resources used in your application. It also contains a few Other subfolders: drawable-<resolution>, layout, and values. About how you can support devices with different screen resolutions and densities.

➤ AndroidManifest.xml— this is the manifest fi le for your Android application. Here you Specify the permissions needed by your application, as well as other features (such as intent-filters, Receivers, etc.). Chapter 2 discusses the use of the AndroidManifest.xml file in more detail.

Page 31: Android Programing Course Material

Creating your first app1. Create a project under Eclipse

2. Assign an SDK target

3. Choose an application name

4. Choose a package name

5. Create an activity and assign a name

6. Run it to test that everything is ok

Creating Android Virtual Devices (AVDs)The next step is to create an Android Virtual Device (AVD) to be used for testing your Android

Applications. An AVD is an emulator instance that enables you to model an actual device. Each AVD consists of a hardware profile; a mapping to a system image; as well as emulated storage, such as a secure digital (SD) card.

Setting up development environment

Page 32: Android Programing Course Material

Module IIActivities, Fragments, and Intents

Page 33: Android Programing Course Material

Hello World!

Button1

Understanding activities An Activity corresponds to a singlescreen of the Application. An Application can be composed of multiples screens (Activities). The HomeActivity is shown when the user launches an application. Different activities can exchange information one with each other.

Understanding activities and application manifest file

Page 34: Android Programing Course Material

Manifest

The AndroidManifest.xmlfi le contains detailed confi guration information for your application. As your example application becomes more sophisticated, you will modify this fi le, and you will

See the different information you can add to it as you progress through the chapters.

Contains:

Application declaration Activities Services Permissions HW and SW resources used by the Application Intent-filters

Page 35: Android Programing Course Material

Activities in the system are managed as an activity stack. When a new activity is started, it is placed on the top of the stack and becomes the running activity -- the previous activity always remains below it in the stack, and will not come to the foreground again until the new activity exits.

An activity has essentially four states:

If an activity in the foreground of the screen (at the top of the stack), it is active or running.

If an activity has lost focus but is still visible (that is, a new non-full-sized or transparent activity has focus on top of your activity), it is paused. A paused activity is completely alive (it maintains all state and member information and remains attached to the window manager), but can be killed by the system in extreme low memory situations.

If an activity is completely obscured by another activity, it is stopped. It still retains all state and member information, however, it is no longer visible to the user so its window is hidden and it will often be killed by the system when memory is needed elsewhere.

If an activity is paused or stopped, the system can drop the activity from memory by either asking it to finish, or simply killing its process. When it is displayed again to the user, it must be completely restarted and restored to its previous state.

Activity lifecycle The ActivityManager is

responsible for creating, destroying, managing activities.

Activity lifecycle and configuration

Page 36: Android Programing Course Material

Activities can be on different states: starting, running, stopped, destroyed, paused.

Only one activity can be on the running state at a time. Activities are organized on a stack, and have an event-driven life cycle (details

later …)The Activity class defines the following events:

➤ onCreate()— Called when the activity is fi rst created

➤ onStart()— Called when the activity becomes visible to the user

➤ onResume()— Called when the activity starts interacting with the user

➤ onPause()— Called when the current activity is being paused and the previous activity is being resumed

➤ onStop()— Called when the activity is no longer visible to the user

➤ onDestroy()— Called before the activity is destroyed by the system (either manually or by the system to conserve memory)

➤ onRestart()— Called when the activity has been stopped and is restarting again

Page 37: Android Programing Course Material

Each activity is composed by a list of graphics components.

Some of these components (also called Views) can interact with the user by handling events (e.g. Buttons).

Two ways to build the graphic interface:

1- Programmatic ApproachExample:

Button button=new Button (this);

TextView text= new TextView();

text.setText(“Hello world”);

2- Declarative ApproachExample:

< TextView android.text=@string/hello” android:textcolor=@color/blue android:layout_width=“fill_parent” android:layout_height=“wrap_content” />

< Button android.id=“@+id/Button01” android:textcolor=“@color/blue” android:layout_width=“fill_parent” android:layout_height=“wrap_content” />

Best Activity Approach

Android applications typically use both the approaches!

Programmatic Approach

XML Code:

Define the Application layouts and resources used by the Application (e.g. labels).

Declarative Approach

Java Code:

Manages the events, and handles the interaction with the user.

Activity Reconfiguration

Page 38: Android Programing Course Material

XML creation

XML stands for eXtensible Markup Language.

XML is designed to transport and store data.

XML is important to know, and very easy to learn.

Create XML File

Place it under res/xml/ directory

Start the file with

<?xml version=“1.0” encoding=“utf-8”?>

Add whatever you want with <mytag>value</mytag>

<?xml version="1.0" encoding="UTF-8"?>

<note>

    <to> Tove</to>

    <from>Jani</from>

    <heading>Reminder</heading>

    <body>Don't forget me this weekend!</body>

</note>

Parse XML format

Page 39: Android Programing Course Material

Parse XML format

XmlResourceParser grades = getResources().getXml(R.xml.myxmlfile);

LinearLayout ll = (LinearLayout)findViewById(R.id.myLL);

int tag = -1;

while (tag != XmlResourceParser.END_DOCUMENT) {

if (tag == XmlResourceParser.START_TAG) {

String name = grades.getName();

if (name.equals("student")) {

TextView tv = new TextView(this);

LayoutParams lp = new LayoutParams(LayoutParams.FILL_PARENT,

LayoutParams.WRAP_CONTENT);

tv.setLayoutParams(lp);

String toWrite = grades.getAttributeValue(null, "name") + …;

tv.setText(toWrite); ll.addView(tv);

} }

try { tag = grades.next(); } catch (Exception e) { }

}

Page 40: Android Programing Course Material

Intent Definition

An intent is basically the “glue” that enables different activities from different applications to work together seamlessly, ensuring that tasks can be performed as though they all belong to one single application

Explicit Intent: The component (e.g. Activity1) specifies the destination of the intent (e.g. Activity 2).

Implicit Intent: The component (e.g. Activity1) specifies the type of the intent (e.g. “View a video”).

ViewImplicit Intent

Activity1

Activity2

Activity2Multiple choices

might be available } Intent-

Filters

LOGIN

PASSWORD

Login

Shady

**********

Welcome

Shady!

Login Intent

Activity1

Activity2

Intent Class

Page 41: Android Programing Course Material

Linking ActivitiesData can be sent between activities using intents

Send the intent:

Intent sendIntent = new Intent();

sendIntent.putExtra(MainActivity.EXTRA_ MESSAGE, "This is my text to send.");

startActivity(sendIntent);

Receive the intent:

Intent intent = getIntent();

String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);

Add it to the manifest:

<application ... >

...

<activity

android:name="com.example.myfirstapp.DisplayMessageActivity"

android:label="@string/title_activity_display_message"

android:parentActivityName="com.example.myfirstapp.MainActivity" >

<meta-data

android:name="android.support.PARENT_ACTIVITY"

android:value="com.example.myfirstapp.MainActivity" />

</activity>

</application>

Linking activities using intents

Page 42: Android Programing Course Material

Permission Using to Access Any Hardware Device on Mobile such Bluetooth or Dealing With Mobile Categories Such as Internet and Sms.

Declared in the AndroidManifest.xml

Example for monitoring incoming SMS:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

package="com.android.app.myapp" >

<uses-permission android:name="android.permission.RECEIVE_SMS" />

...

</manifest>

Permissions

Page 43: Android Programing Course Material

Activity can contain one or more of these mini-activities, depending on the screen orientation in

Which the device is held. In Android 3.0 and later, these mini-activities are known as fragments.

import android.support.v4.app.Fragment;

import android.view.LayoutInflater;

import android.view.ViewGroup;

public class ArticleFragment extends Fragment {

@Override

public View onCreateView(LayoutInflater inflater, ViewGroup container,

Bundle savedInstanceState) {

// Inflate the layout for this fragment

return inflater.inflate(R.layout.article_view, container, false);

}

}

Fragments

Page 44: Android Programing Course Material

A notification is a message you can display to the user outside of your application's normal UI Src folder with java files

You have been using the Toast class to display messages to the user. While the Toast class is a handy way to show users alerts, it is not persistent. It flashes on the screen for a few seconds and then

Disappears. If it contains important information, users may easily miss it if they are not looking at the screen. For messages that are important, you should use a more persistent method. In this case, you should use the Notification Manager to display a persistent message at the top of the device, commonly known as the status bar (sometimes also referred to as the notification bar)

Displaying notifications

Page 45: Android Programing Course Material

Module IIIAndroid User Interface

Page 46: Android Programing Course Material

Understanding the screen components

A layout defines the visual structure for a user interface, such as the UI for an activity or app widget. You can declare a layout in two ways:

Declare UI elements in XML Instantiate layout elements at runtime

Fundamentals and layouts

Page 47: Android Programing Course Material

Layouts

Some layouts are pre-defined by Android

Some of these are

LinearLayout RelativeLayout TableLayout FrameLayout AbsoluteLayout

A layout could be declared inside another layout

Page 48: Android Programing Course Material

LinearLayout

Dispose views on a single row or column, depending on android:layout_orientation

The orientation could also be declared via setOrientation(int orientation)

orientation is one of HORIZONTAL or VERTICALHas two other attributes:

gravity weight

Page 49: Android Programing Course Material

RelativeLayout

Disposes views according to the container or according to other views

The gravity attribute indicates what views are more important to define the layout

Useful to align views

Page 50: Android Programing Course Material

TableLayout

As the name say, similar to a Table

Has some attributes to customize the layout:

android:layout_column android:layout_span android:stretchColumns android:shrinkColumns android:collapseColumns

Each row is inside a <TableRow> element

Page 51: Android Programing Course Material

FrameLayout and AbsoluteLayout

FrameLayout:

Adds an attribute, android:visibility

Makes the user able to define layouts managing the visibility of views

AbsoluteLayout:

Deprecated

Specify position with x and y

Pay attention to different resolutions

Page 52: Android Programing Course Material

Common widgets

TextView

EditText

Button

CheckBox

Spinner

DatePicker

Custom Views

Understanding the screen components

Page 53: Android Programing Course Material

Java and XML code

Widgets can be created in Java

Widgets can be created in XML and accessed through Java

XML:

<TextView

android:id="@+id/name1"

android:layout_width="match_parent"

android:layout_height="wrap_content” />

Java:

public TextView text;

text=(TextView)findViewById(R.id.name1);

Page 54: Android Programing Course Material

The users interacts with the Views …

Upon certain action, an appropriate event will be fired

Reacting to this events makes the activity interactive

Events for click, long click, gestures, focus, external events …

PROBLEM: How to handle these events?

User navigation (click, touch, drag, etc...)

Page 55: Android Programing Course Material

GestureGestures allow users to interact with your app by manipulating the screen objects you provide. The following table shows the core gesture set that is supported in Android.

Page 56: Android Programing Course Material

Views and Events

Two ways to handle the View events:

Events Handlers.

Some Views have callback methods to handle specific events.

When a Button is touched onTouchEvent() called

Ex.

boolean onKeyDown(int keycode, KeyEvent event)

boolean onKeyUp(int keycode, KeyEvent event)

boolean onKeyMultiple (int keycode, KeyEvent event)

In practice: use Events Handlers for custom components …

… use Events Listeners for common View/Widget components …

PROBLEM: to intercept an event, you must extend the View class and override the callback method … not very practical!

Page 57: Android Programing Course Material

Events Listeners

A View class contain a collection of nested interfaces (listeners).

Each interface handles a single type of events…

Each interface contains a single callback method …

This method is called in occurrence of the event of the View.

Page 58: Android Programing Course Material

Dispose views on a single row or column, depending on android:layout_orientation

The orientation could also be declared via setOrientation(int orientation)

orientation is one of HORIZONTAL or VERTICAL

Ex.

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:orientation="vertical" > <!-- Also horizontal -->

</LinearLayout>

Adapting to display orientation

Page 59: Android Programing Course Material

It can contain icons for special view actions

It can also hold the menu button

Useful for giving different options without leaving the current Activity

It is mainly used for preferences and app settings

It can be created for specific view or for the whole app

@Override

public boolean onOptionsItemSelected(MenuItem item) {

switch (item.getItemId()) {

case android.R.id.home:

// app icon in action bar clicked; go home

Intent intent = new Intent(this, HomeActivity.class);

intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

startActivity(intent);

return true;

default:

return super.onOptionsItemSelected(item);

}

}

Utilizing the action bar

Page 60: Android Programing Course Material

As we noted before that we can create the view programmatically with Java

private RelativeLayout myRelativeLayout;

@Override

public void onCreate(Bundle savedInstanceState) {

myRelativeLayout = (RelativeLayout)findViewById(R.id.myRelativeLayout);

// We create a button

Button myButton = new Button(this);

layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);

// And to finish, we add the button at our RelativeLayout with layoutParams

myRelativeLayout.addView(myButton, layoutParams);

}

Creating the user interface programmatically

Page 61: Android Programing Course Material

ActionListeners

OnClickListener

method: onClick()

OnLongClickListener

method: onLongClick()

OnFocusChangeListener

method: onFocusChange()

OnKeyListener

method: onKey()

OnCheckedChangeListener

method: onCheckedChanged()

OnTouchListener

method: onTouch()

OnCreateContextMenuListener

method: onCreateContextMenu()

Listening for UI notifications

Page 62: Android Programing Course Material

To handle events through ActionListener:

Implement the callback method

Define an ActionListener object as an anonymous class

Pass an instance of the ActionListener implementation to the View through the View.setOnXXXEventListener() method

Button btn = (Button)findViewById(R.id.btn);

btn.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View view) {

// Event management

}

});

Page 63: Android Programing Course Material

Possible to perform some events in the code

Typically in the form performSomething()

Used to simulate an event

The corresponding listener (if set) will be fired …

Give a result (true or false) depending if the component has a listener or not!

Page 64: Android Programing Course Material

TextView

XML tags: <TextView></TextView>

Could be filled with strings, HTML markups

Should specify which type of text is displayed

Not directly editable by users

Usually used to display static informations

Some methods:

void setText(CharSequence text) CharSequence getText();

Using basic views, image views, and menus

Page 65: Android Programing Course Material

Linkify elements

Simple strings that could be linkified automatically.

How? Pick a normal string, and use Linkify.addLinks() to declare what kind of link should be created.

Could manage: Web addresses, Emails, phone numbers, Maps

It is possible to define custom Linkify objects

TextView textView=(TextView) findViewById(R.id.output);

Linkify.addLinks(textView, Linkify.WEB_URLS | Linkify.WEB_ADDRESSES | Linkify.PHONE_NUMBERS );

Linkify.addLinks(textView, Linkify.ALL);

Page 66: Android Programing Course Material

EditText

Similar to a TextView, but editable by the users

Used to get information by the users.

It is possible to declare in the layout file which type of text will be contained … (NORMAL, EDITABLE, SPANNABLE)

An appropriate keyboard and display will be used.

Text selection methods:

public void setSelection(int index)

public void setSelection(int start, int end)

Page 67: Android Programing Course Material

Button and CompoundButton

Not really different to manage than a Textview!

Has events related to clicks, long clicks and so on

Cannot be directly editable by users

CompoundButton: Button + state (checked/unchecked)

Subclasses: CheckBox, RadioButton, ToggleButton Methods:

o public void setChecked(boolean checked)o public void toggle()

Page 68: Android Programing Course Material

CheckedTextView

Checkable version of a TextView

Usable with a ListViewAdapter

Multiple or single selection of items (CHOICE_MODE_SINGLE, CHOICE_MODE_MULTIPLE)

Methods:

void setChoiceMode(int choiceMode) long[] getCheckItemIds() int getCheckedItemPosition()

Page 69: Android Programing Course Material

Menu: outline

They appear whenever the user presses the menu button

Useful for giving different options without leaving the current Activity

Don’t make too big menus, or they’ll cover entirely the Activity

Page 70: Android Programing Course Material

Menu: creating a menu

Two methods (again):

XML:

Place a file inside res/menu/

Inflate the menu inside the Activity

Useful if you want to create the same menu inside different activities

Java:

Create the menu directly inside the activity

Page 71: Android Programing Course Material

The declarative approach

Create res/menu/menu.xml

We need:

IDs of menu’s elements Title of each element Icon of each element

Inside the Activity, create onCreateOptionsMenu()

Inflate the menu Add functionality to the buttons

Page 72: Android Programing Course Material

Other elements …

See the official documentation for the complete list:

AnalogClock Widget DigitalClock Widget DataPicker Widget …. … …

As an alternative, it is possible to create custom View …

Ad hoc components, code reuse …

Page 73: Android Programing Course Material

ImageView

Is a subclass of the View object. XML Tag: <ImageView>

Images inside res/drawable (or obtained with other methods)

Some methods to manipulate it:

void setScaleType(enum scaleType) void setAlpha(double alpha) void setColorFilter(ColorFilter color)

Displaying pictures and managing drawing areas

Page 74: Android Programing Course Material

Module IVSensors

Page 75: Android Programing Course Material

The Android platform supports three broad categories of sensors:

Motion sensorsThese sensors measure acceleration forces and rotational forces along three axes. This category includes accelerometers, gravity sensors, gyroscopes, and rotational vector sensors.

Environmental sensorsThese sensors measure various environmental parameters, such as ambient air temperature and pressure, illumination, and humidity. This category includes barometers, photometers, and thermometers.

Position sensorsThese sensors measure the physical position of a device. This category includes orientation sensors and magnetometers.

Types

Page 76: Android Programing Course Material

Determine which sensors are available on a device.

Determine an individual sensor's capabilities, such as its maximum range, manufacturer, power requirements, and resolution.

Acquire raw sensor data and define the minimum rate at which you acquire sensor data.

Register and unregister sensor event listeners that monitor sensor changes.

Using sensors and the sensor managerTypes

Page 77: Android Programing Course Material

Acceleration sensor

Gravity sensor

Gyroscope

Linear acceleration sensor

Geomagnetic field sensor

Monitoring a device’s movement and orientation

Page 78: Android Programing Course Material

private SensorManager mSensorManager;

private Sensor mSensor;

...

mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);

mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

private SensorManager mSensorManager;

...

mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);

if (mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD) != null){

// Success! There's a magnetometer.

}

else {

// Failure! No magnetometer.

}

Calculating orientation using the accelerometer and magnetic field sensors

Page 79: Android Programing Course Material

Android gives your applications access to the location services supported by the device through classes in the android.location package. The central component of the location framework is the LocationManager system service, which provides APIs to determine location and bearing of the underlying device (if available).

With the Google Maps Android API, you can add maps to your app that are based on Google Maps data. The API automatically handles access to Google Maps servers, data downloading, map display, and touch gestures on the map. You can also use API calls to add markers, polygons and overlays, and to change the user's view of a particular map area.

Location and maps

Page 80: Android Programing Course Material

Module VBluetooth, NFC, Networks, and Wi-Fi

Page 81: Android Programing Course Material

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 then transmit and receive streams of data between devices from within your applications.

Using the Bluetooth APIs, an Android application can perform the following

Scan for other Bluetooth devices Query the local Bluetooth adapter for paired Bluetooth devices Establish RFCOMM channels Connect to other devices through service discovery Transfer data to and from other devices Manage multiple connections

Bluetooth communications

Page 82: Android Programing Course Material

A Bluetooth Server Socket is used to listen for incoming Bluetooth Socket connection requests from remote Bluetooth Devices. In order for two Bluetooth devices to be connected, one must act as a server (listening for and accepting incoming requests) and the other as a client (initiating the request to connect to the server). After the two are connected, the communications between the server and host device are handled through a Bluetooth Socket at both ends.

To have your Bluetooth Adapter act as a server, call its listenUsingRfcommWithServiceRecord method to listen for incoming connection requests. Pass in a name to identify your server and a universally unique identifier (UUID). The method will return a BluetoothServerSocket object — note that the client Bluetooth Socket that connects to this listener will need to know its UUID in order to connect.

Call accept on the Server Socket, optionally passing in a timeout duration, to have it start listening for connections. The Server Socket will now block until a remote Bluetooth Socket client with a matching UUID attempts to connect.

If a connection request is made from a remote device that is not yet paired with the local Bluetooth Adapter, the user will be prompted to accept a pairing request before the accept call returns. This prompt is made via a Notification, or a Dialog.

private class AcceptThread extends Thread {

private final BluetoothServerSocket mmServerSocket;

public AcceptThread() {

// Use a temporary object that is later assigned to mmServerSocket,

// because mmServerSocket is final

BluetoothServerSocket tmp = null;

try {

// MY_UUID is the app's UUID string, also used by the client code

Transmitting data using Bluetooth sockets

Page 83: Android Programing Course Material

tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);

} catch (IOException e) { }

mmServerSocket = tmp;

}

public void run() {

BluetoothSocket socket = null;

// Keep listening until exception occurs or a socket is returned

while (true) {

try {

socket = mmServerSocket.accept();

} catch (IOException e) {

break;

}

// If a connection was accepted

if (socket != null) {

// Do work to manage the connection (in a separate thread)

manageConnectedSocket(socket);

mmServerSocket.close();

break;

}

}

}

}

Page 84: Android Programing Course Material

The WifiManager, which represents the Android Wi-Fi Connectivity Service, can be used to configure Wi-Fi network connections, manage the current Wi-Fi connection, scan for access points, and monitor changes in Wi-Fi connectivity.

To use the Wi-Fi Manager, your application must have uses-permissions for accessing and changing the Wi-Fi state included in its manifest:

<uses-permission android:name=”android.permission.ACCESS_WIFI_STATE”/>

<uses-permission android:name=”android.permission.CHANGE_WIFI_STATE”/>

Access the Wi-Fi Manager using the getSystemService method, passing in the Context.WIFI_SERVICE constant.

You can use the Wi-Fi Manager to manage the configured network settings and control which networks to connect to. When connected, you can interrogate the active network connection to get additional details of its configuration and settings.

Get a list of the current network configurations using getConfiguredNetworks. The list of

WifiConfiguration objects returned includes the network ID, SSID, and other details for each configuration.

To use a particular network configuration, use the enableNetwork method, passing in the network ID to use and specifying true for the disableAllOthers parameter

Uses for the Wi-Fi manager:

Register Your Service on the Network

Discover Services on the Network

Connect to Services on the Network

Unregister Your Service on Application Close

Managing Wi-Fi and its configurations

Page 85: Android Programing Course Material

Wi-Fi Direct is a communications protocol designed for medium-range, high-bandwidth peer-to-peer communications. Support for Wi-Fi Direct was added to Android 4.0 (API level 14).

Compared to Bluetooth, Wi-Fi Direct is faster and more reliable, and works over greater distances.

Using the Wi-Fi Direct APIs, you can search for, and connect to, other Wi-Fi Direct devices within range. 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.

As a high bandwidth alternative to Bluetooth, Wi-Fi Direct is particularly suitable for operations such as media sharing and live media streaming.

Steps for the Wi-Fi direct peering:

Set Up Application Permissions

Set Up the Broadcast Receiver and Peer-to-Peer Manager

Initiate Peer Discovery

Fetch the List of Peers

Connect to a Peer

Transferring data using Wi-Fi direct

Page 86: Android Programing Course Material

Android allows you to transfer large files between devices using the Android Beam file transfer feature. This feature has a simple API and allows users to start the transfer process by simply touching devices. In response, Android Beam file transfer automatically copies files from one device to the other and notifies the user when it's finished.

Android 2.3 (API level 9) introduced Near Field Communication (NFC) APIs. NFC is a contact-less technology used to transmit small amounts of data across short distances (typically less than 4 centimeters).

NFC transfers can occur between two NFC-enabled devices, or between a device and an NFC “tag.” Tags can range from passive tags that transmit a URL when scanned to complex systems such as those used in NFC payment solutions, such as Google Wallet.

NFC messages in Android are handled using the NFC Data Exchange Format (NDEF).

In order to read, write, or broadcast NFC messages, your application requires the NFC manifest permission:

<uses-permission android:name=”android.permission.NFC” />

Near field communication

Page 87: Android Programing Course Material

Module VII/O file

Page 88: Android Programing Course Material

Onboard

Write to a designated place for each application Where? /data/data/<package>/files How? Use standard java I/O classes

SD card

Where? Environment.getExternalStorageDirectory() How? Use standard java I/O classes Permissions? android.permission.WRITE_EXTERNAL_STORAGE

Access local files

Page 89: Android Programing Course Material

Raw Text File

Place it under res/raw/ directory Fill it with the text you like Cannot edit it Populate a TextView with it’s content inside the code

TextView tv = (TextView)findViewById(R.id.tv_main);

tv.setText(streamToString(R.raw.myfile));

Read local files

Page 90: Android Programing Course Material

private String streamToString(int id) {

InputStream file = getResources().openRawResource(id);

StringBuffer data = new StringBuffer();

DataInputStream dataIO = new DataInputStream(file);

String line = null;

try {

while ((line = dataIO.readLine()) != null)

data.append(line + "\n");

dataIO.close();

file.close();

} catch (IOException e) { }

return data.toString();

}

Write files

Page 91: Android Programing Course Material

Module VIIDatabase

Page 92: Android Programing Course Material

Android provides structured data persistence through a combination of SQLite databases and Content Providers.

SQLite databases can be used to store application data using a managed, structured approach.

Android offers a full SQLite relational database library. Every application can create its own data-bases over which it has complete control.

Having created your underlying data store, Content Providers offer a generic, well-defined interface for using and sharing data that provides a consistent abstraction from the underlying data source.

Introducing Android databases

Page 93: Android Programing Course Material

General purpose solution

Lightweight database based on SQL

Standard SQL syntax

SELECT name FROM table WHERE name = “Luca”

Android gives a standard interface to SQL tables of other apps

For application tables no content providers are needed

Working with SQLite

Page 94: Android Programing Course Material

SQLite: how?

A database to store information

Useful for structured information

Create a DBHelper which extends SQLiteOpenHelper

Fill it with methods for managing the database

Better to use constants like

TABLE_NAME

COLUMN_NAME

Page 95: Android Programing Course Material

Our database will look like this:

grade table:

id: integer, primary key, auto increment firstName: text, not null lastName: text, not null class: text, not null grade: integer, not null

Querying a database, and adding, updating, and removing rows

Page 96: Android Programing Course Material

SQLite: better to use constants

Useful for query definition

Our constants?

private static final String DB_NAME = “grades.db”;

private static final int DB_VERSION = 1;

public static final String TABLE_GRADES = “grades”;

public static final String COL_ID = “id”;

public static final String COL_FIRSTNAME = “firstName”;

public static final String COL_LASTNAME = “lastName”;

public static final String COL_CLASS = “class”;

public static final String COL_GRADE = “grade”;

Page 97: Android Programing Course Material

SQLite: creation code

Constructor: call the superconstructor

Public mySQLiteHelper(Context context) {

super(context, DB_NAME, null, DB_VERSION);

}

onCreate(SQLiteDatabase db): create the tables

String sql_grade = “create table “ + TABLE_GRADES + “( “ +

COL_ID + “ integer primary key autoincrement, “ +

COL_FIRSTNAME + “ text not null, “ +

COL_LASTNAME + “ text not null, “ +

COL_CLASS + “ text not null, “ +

COL_GRADE + “ text not null “);”;

db.execSQL(sql_grade);

Page 98: Android Programing Course Material

SQLite: insert code

Create a public method, like insertDb(…)

mySQLiteHelper sql = new mySQLiteHelper(InsertActivity.this);

SQLiteDatabase db = mySQLiteHelper.getWritableDatabase();

ContentValues cv = new ContentValues();

cv.put(mySQLiteHelper.COL_FIRSTNAME, firstName);

cv.put(mySQLiteHelper.COL_LASTNAME, flastName);

cv.put(mySQLiteHelper.COL_FIRSTNAME, firstName);

cv.put(mySQLiteHelper.COL_FIRSTNAME, firstName);

long id = db.insert(mySQLiteHelper.TABLE_GRADES, null, values);

Page 99: Android Programing Course Material

SQLite: delete code

Create a public method, like deleteDb(…)

The delete method returns the number of rows affected

db.delete(mySQLiteHelper.TABLE_GRADES, “id = ?”, new String[]

{Integer.toString(id_to_delete)});

Page 100: Android Programing Course Material

SQLite: update code

Create a public method, like updateDb(…)

ContentValues cv = new ContentValues();

values.put(mySQLiteHelper.FIRSTNAME, firstName);

values.put(mySQLiteHelper.LASTNAME, lastName);

db.update(mySQLiteHelper.TABLE_GRADES, values, “id = ?”, new String[]

{Integer.toString(id_to_update));

Page 101: Android Programing Course Material

SQLite: search code

Create a public method, like getFromDb(…)

Cursor gradeCursor = db.query(mySQLiteHelper.TABLE_GRADES,

new String[]{mySQLiteHelper.COL_GRADE}, mySQLiteHelper.COL_ID + “ = “

+ id_to_search_for, null, null, null, null);

Page 102: Android Programing Course Material

Cursors: data handlers

A Cursor stores data given by a DB query

Some methods:

getCount() moveTo{First,Next,Last,Position,Previous}() close()

You need to look inside the Cursor to see query’s results

while (gradeCursor.moveToNext()) {

Log.v(“GRADES”,gradeCursor.getString(0));

}

Page 103: Android Programing Course Material

Cursors: methods

Manipulate the cursor (row pointer)

cursor.moveToFirst() while (cursor.moveToNext()) { /* code */ } for (cursor.moveToFirst(); !cursor.isAfterLast(); cur.moveToNext) { /* code */ }

Get column numbers from names

int nameColumn = cursor.getColumnIndex(People.NAME); int phoneColumn = cursor.getColumnIndex(People.NUMBER);

Get Data from column

String name = cursor.getString(nameColumn); String number = cursor.getString(phoneColumn

Page 104: Android Programing Course Material

To offer complex data or files to other applications

To allow users to copy complex data from your app into other apps

To provide custom search suggestions using the search framework

Content Providers provide an interface for publishing and consuming data, based around a simple URI addressing model using the content:// schema. They enable you to decouple your application layers from the underlying data layers, making your applications data-source agnostic by abstracting the underlying data source.

Content Providers can be shared between applications, queried for results, have their existing records updated or deleted, and have new records added. Any application — with the appropriate permissions — can add, remove, or update data from any other application, including the native Android Content Providers.

Several native Content Providers have been made accessible for access by third-party applications, including the contact manager, media store, and calendar.

By publishing your own Content Providers, you make it possible for you (and other developers) to incorporate and extend your data in new applications.

Using content providers

Page 105: Android Programing Course Material

The basic provider structure.

Retrieve data from the provider.

Modify data in the provider.

Write a sync adapter for synchronizing data from your server to the Contacts Provider.

Using contacts

Page 106: Android Programing Course Material

The Calendar Provider is a repository for a user's calendar events. The Calendar Provider API allows you to perform query, insert, update, and delete operations on calendars, events, attendees, reminders, and so on.

Android 4.0 (API level 14) introduced a supported API for accessing the Calendar Content Provider.

The Calendar API allows you to insert, view, and edit the complete Calendar database, providing access to calendars, events, attendees, and event reminders using either Intents or through direct manipulation of the Calendar Content Providers.

Like the Contacts Contract Content Provider, the Calendar Content Provider is designed to support multiple synchronized accounts. As a result, you can choose to read from, and contribute to, existing calendar applications and accounts; develop an alternative Calendar Provider by creating a calendar Sync Adapter; or create an alternative calendar application.

Using calendar and tasks

Page 107: Android Programing Course Material

Module VIIINetworking

Page 108: Android Programing Course Material

One common way to communicate with the outside world is through HTTP. HTTP is no stranger to most people; it is the protocol that drives much of the web’s success. Using the HTTP protocol, you can perform a wide variety of tasks, such as downloading web pages from a web server, downloading binary data, and more.

HTTP (HyperText Tranfer Protocol): Network protocol for exchange/transfer data (hypertext)

Request/Resonse Communication Model

HEAD GET POST PUT DELETE TRACE CONNECT

Because you are using the HTTP protocol to connect to the web, your application needs the INTERNET permission; hence, the first thing you did was add the permission in the AndroidManifest.xml file.

You then defined the OpenHttpConnection() method, which takes a URL string and returns an InputStream object. Using an InputStream object, you can download the data by reading bytes from the stream object. In this method, you made use of the HttpURLConnection object to open an HTTP connection with a remote URL. You set all the various properties of the connection, such as the request method, and so on.

Consuming web services using HTTP

Page 109: Android Programing Course Material

HTTP Classes

HttpClient: Interface for an HTTP client

HttpRequest: Interface for an HTTP request

HttpResponse: Interface for an HTTP response

ResponseHandler<T>: Handler that creates an object <T> from an HTTP Response

HttpContext: Context of the HTTP Request (request+response+data)

Page 110: Android Programing Course Material

Manipulating XML documents is a computationally expensive operation for mobile devices, for the following reasons:

XML documents are lengthy. They use tags to embed information, and the size of an XML document can get very big pretty quickly. A large XML document means that your device has to use more bandwidth to download it, which translates into higher cost.

XML documents are more difficult to process. As shown earlier, you have to use DOM to traverse the tree in order to locate the information you want. In addition, DOM itself has to build the entire document in memory as a tree structure before you can traverse it. This is both memory and CPU intensive.

A much more efficient way to represent information exists in the form of JSON (JavaScript Object Notation). JSON is a lightweight data-interchange format that is easy for humans to read and write.

Consuming JSON services

Page 111: Android Programing Course Material

Parsing JSON

Within array handling methods, first call beginArray() to consume the array's opening bracket. Then create a while loop that accumulates values, terminating when hasNext() is false. Finally, read the array's closing bracket by calling endArray()

Within object handling methods, first call beginObject() to consume the object's opening brace. Then create a while loop that assigns values to local variables based on their name. This loop should terminate when hasNext() is false. Finally, read the object's closing brace by calling endObject().

Page 112: Android Programing Course Material

While most web services use HTTP for communication, they inherently suffer from one huge disadvantage: They are stateless. When you connect to a web service using HTTP, every connection is treated as a new connection — the web server does not maintain a persistent connection with the clients.

Consider a scenario in which your application connects to a web service that books cinema seats.

When seats are booked on the server by a client, all the other clients are not aware of this until they connect to the web service again to obtain the new seat allocations. This constant polling by the clients incurs unnecessary bandwidth and makes your application inefficient. A much better solution is to have the server maintain individual connections to each client, and send a message to each one whenever seats are booked by another client.

If you want your application to maintain a persistent connection to the server and be notified by the server whenever changes occur, you need to use a programming technique known as sockets programming. Sockets programming is a technique through which you use to establish a connection between a client and a server. Multiple applications can connect to the server and chat at the same time.

TCP/UDP Communication: Android applications can use java.net.Socket facilities.

Use socket-based programming like in Java

Class DatagramSocket: UDP Socket

Classes Socket/ServerSocket: TCP socket

Read/Write on Sockets through InputStream/OutputStream

Sockets programming

Page 113: Android Programing Course Material

Module IXDeveloping Android Services

Page 114: Android Programing Course Material

<manifest ... >

...

<application ... >

<service android:name=".ExampleService" />

...

</application>

</manifest>

Creating your own services

Page 115: Android Programing Course Material

public class HelloIntentService extends IntentService {

public HelloIntentService() {

super("HelloIntentService");

}

@Override

protected void onHandleIntent(Intent intent) {

// Normally we would do some work here, like download a file.

// For our sample, we just sleep for 5 seconds.

long endTime = System.currentTimeMillis() + 5*1000;

while (System.currentTimeMillis() < endTime) {

synchronized (this) {

try {

wait(endTime - System.currentTimeMillis());

} catch (Exception e) {

}

}

}

}

}

Binding activities to services

Page 116: Android Programing Course Material

A Thread is a concurrent unit of execution. It has its own call stack for methods being invoked, their arguments and local variables. Each application has at least one thread running when it is started, the main thread, in the main ThreadGroup. The runtime keeps its own threads in the system thread group.

There are two ways to execute code in a new thread. You can either subclass Thread and overriding its run() method, or construct a new Thread and pass a Runnable to the constructor. In either case, the start() method must be called to actually execute the new Thread.

Each Thread has an integer priority that affect how the thread is scheduled by the OS. A new thread inherits the priority of its parent. A thread's priority can be set using the setPriority(int) method.

Understanding threading

Page 117: Android Programing Course Material

Module XAudio and Video

Page 118: Android Programing Course Material

RecordPlayback

Audio / Video

android.media.MediaPlayer android.media.MediaRecorder

Media API

Page 119: Android Programing Course Material

The playback of audio and video within Android applications is handled primarily through the MediaPlayer class. Using the Media Player, you can play media stored in application resources, local files, Content Providers, or streamed from a network URL.

The Media Player’s management of audio and video files and streams is handled as a state machine.

Can play media from:

Web: via a URL. .apk file: packaged as part of your .apk file. Secure Digital (SD) card: content from the device’s SD card.

Playing audio and video

Page 120: Android Programing Course Material

Play Media From:

Resource Folder File System Path URL

Basically

Create new instance of MediaPlayer Call prepare() Call start()

Playback of video content is slightly more involved than audio. To play a video, you first must have a Surface on which to show it.

There are two alternatives for the playback of video content. The first technique, using the VideoView class, encapsulates the creation of a Surface and allocation and preparation of video content using a Media Player.

The second technique allows you to specify your own Surface and manipulate the underlying Media Player instance directly.

Controlling media player playback

Page 121: Android Programing Course Material

If your application plays audio and/or video in a way users would associate with a media player, it should respond predictably to media button presses.

Some devices, as well as attached or Bluetooth headsets, feature play, stop, pause, skip, and previous media playback keys. When users press these keys, the system broadcasts an Intent with the ACTION_MEDIA_BUTTON action. To receive this broadcast, you must have a Broadcast Receiver declared in your manifest that listens for this action

Create Using:

URI Resource ID URI + Surface

Others:

Start Prepare Pause Release Reset SeekTo Stop

Get:

Position Duration FrameAt

Set:

Audio Stream Output Display Looping Data Source Wake Mode

Listeners:

Responding to the media player controls

Page 122: Android Programing Course Material

Buffering Update Completion Error When Prepared

Page 123: Android Programing Course Material

MediaRecorder

Create new instance of MediaRecorder

Create new instance of ContentValues

Create an output file

Set Preview Display

Set Video and Audio Source (Camera and Mic)

Set Properties (File Size, Video Size, Frame Rate)

Set Audio and Video Encoders

Call Prepare() and Start()

Call Stop() and Release()

Page 124: Android Programing Course Material

Call:

Receiving – Start mp3 background service Automatically record conversation or 3G videos

Playing Games:

Sound mp3’s in background, render video in foreground Clicking buttons sound small ticks (mp3’s)

Conference:

Recording and Playback of Mobile Conference Synchronising Playback via Bluetooth on Projector

Record Sounds or Movements, Transform into Actions

Recording sound

Page 125: Android Programing Course Material

Video

VideoView is a View that you can drop anywhere in your activity, point to a video file and play it.

XML:

<VideoView

android:id="@+id/video"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:layout_gravity="center” />

Java:

player = (VideoView) findViewById(R.id.video);

player.setVideoPath("/sdcard/samplevideo.3gp");

player.start();

Page 126: Android Programing Course Material

Sounds

Page 127: Android Programing Course Material

Video

Page 128: Android Programing Course Material

Module XIMonetizing, Promoting,And Distributing Applications

Page 129: Android Programing Course Material

Android applications must be signed before they can be installed on a device

Eclipse can sign applications

Debug mode, just to test it on your device Release mode, when it's ready for other users

Package your application for uploading to marketplace

Page 130: Android Programing Course Material

Android applications are distributed as Android package files (.APK). In order to be installed on a device or emulator, Android packages need to be signed.

During development, your applications will be signed using a debug key that is automatically generated by the ADT tools. Before distributing your application beyond your testing environment, you must compile it as a release build and sign it using a private release key — typically using a self-signed certificate.

The JDK includes the Keytool and Jarsigner command-line tools necessary to create a new keystore/signing certificate, and to sign your APK, respectively. Alternatively, you can use the Export Android Application wizard

Eclipse has a tool called Export Wizard

File > Export Export Android Application Select your key and preferences Application is compiled, signed and aligned, ready to be deployed

Keep your private key safe

Use a strong password Don't lend it to anyone

Signing and publishing applications

Page 131: Android Programing Course Material

One of the advantages of Android’s open ecosystem is the freedom to publish and distribute your applications however, and wherever, you choose. The most common and popular distribution channel is Google Play; however, you are free to distribute your applications using alternative markets, your own website, social media, or any other distribution channel.

In addition to Google Play, there are several alternatives of varying reach, including OEM and carrier pre-installs, the Amazon App Store, and carrier-specific stores.

When distributing your application, it’s important to note that application package names are used as unique identifiers for each application. As a result, each application — including variations that you plan to distribute separately — must each have a unique package name. Note that the filename of your APK does not have to be unique — it will be discarded during the installation process (only the package name is used).

Distributing applications

Page 132: Android Programing Course Material

Distribution Control

Page 133: Android Programing Course Material

As an open ecosystem, Android enables you to monetize your applications using whatever mechanism you choose. If you choose to distribute and monetize your applications using Google Play,

Three options typically are available:

1. Paid applications — Charge users an upfront fee before they download and install your application.

2. Free applications with In-App Billing (IAB) — Make the download and installation of the application free, but charge within the application for virtual goods, upgrades, and other value-adds.

3. Advertising-supported applications — Distribute the application for free, and monetize it by displaying advertising.

Monetizing applications

Page 134: Android Programing Course Material

While your marketing and promotion strategies will vary widely depending on your goals and budget, the following list details some of the most effective techniques to consider:

Offline cross promotion — If you have a significant offline presence (such as a stores or branches), or a large media presence (such as within newspapers, magazines, or on TV), cross promoting your application through those channels can be a particularly effective way to increase awareness and help to ensure users trust the download. Traditional advertising techniques such as TV and newspaper advertisements can be extremely effective in raising awareness of your application.

Online cross promotion — If you have a significant web presence, promoting your application through direct links to Google Play can be an effective way to drive downloads. If your application provides a better user experience than your mobile website, you can detect browser visitors from Android devices and direct them to Google Play to download your native app.

Third-party promotion — Distributing a promotional video on YouTube and leveraging social networks, blogs, press releases, and online review sites can help provide positive word of mouth.

Online advertising — Online advertising using in-app ad networks (such as AdMob) or traditional search-based advertising (such as Google AdWords) can drive significant impressions and downloads for your application.

Application marketing, promotion, and distribution strategies

Page 135: Android Programing Course Material
Page 136: Android Programing Course Material

Mobile application analytics packages, such as Google Analytics and Flurry, can be effective tools for you to better understand who is using your application and how they are using it. Understanding this information can help you make objective decisions on where to focus your development resources.

While the statistics provided by the Android Developer Console offer valuable insight into your users’ language, country, and handsets, using detailed analytics can provide a much richer source of information, from which you can discover bugs, prioritize your feature list, and decide where best to allocate your development resources.

Broadly speaking, you can track three types of data within your application:

1. User analytics — Understand the geographic locations (and language settings) of your users, as well as the speed of their Internet connections, their screen sizes and resolutions, and the orientation of their displays. Use this information to prioritize your translation efforts and optimize your layout and assets for different screen sizes and resolutions.

2. Application usage patterns — The first step in integrating analytics is to record each Activity as you would a web site. This will help you understand the way your application is being used, and will help you to optimize your workflows in the same way you would a web site.

3. Exception tracking — In addition to printing an error into the log output, post each unique exception thrown using your analytics. Not only does this alert you to which exceptions are being thrown, you will also gain insight into their context. Specifically, you’ll be able to see if there are particular devices, locations, or usage patterns that lead to particular exceptions.

Analytics and referral tracking

Page 137: Android Programing Course Material

Module XIIAndroid Kit-Kat

Page 138: Android Programing Course Material

Android KitKat

Page 139: Android Programing Course Material

Android 4.4 is designed to run fast, smooth, and responsively on a much broader range of devices than ever before — including on millions of entry-level devices around the world that have as little as 512MB RAM.

KitKat streamlines every major component to reduce memory use and introduces new APIs and tools to help you create innovative, responsive, memory-efficient applications.

OEMs building the next generation of Android devices can take advantage of targeted recommendations and options to run Android 4.4 efficiently, even on low-memory devices. Dalvik JIT code cache tuning, kernel samepage merging (KSM), swap to zRAM, and other optimizations help manage memory. New configuration options let OEMs tune out-of-memory levels for processes, set graphics cache sizes, control memory reclaim, and more.

In Android itself, changes across the system improve memory management and reduce memory footprint. Core system processes are trimmed to use less heap, and they now more aggressively protect system memory from apps consuming large amounts of RAM. When multiple services start at once — such as when network connectivity

Page 140: Android Programing Course Material

changes — Android now launches the services serially, in small groups, to avoid peak memory demands.

For developers, Android 4.4 helps you deliver apps that are efficient and responsive on all devices. A new API, ActivityManager.isLowRamDevice(), lets you tune your app's behavior to match the device's memory configuration. You can modify or disable large-memory features as needed, depending on the use-cases you want to support on entry-level devices.

New tools give also give you powerful insight into your app's memory use. The procstats tool details memory use over time, with run times and memory footprint for foreground apps and background services. An on-device view is also available as a new developer option. The meminfo tool is enhanced to make it easier to spot memory trends and issues, and it reveals additional memory overhead that hasn't previously been visible.

Page 141: Android Programing Course Material

Android 4.4 introduces new platform support for secure NFC-based transactions through Host Card Emulation (HCE), for payments, loyalty programs, card access, transit passes, and other custom services. With HCE, any app on an Android device can emulate an NFC smart card, letting users tap to initiate transactions with an app of their choice — no provisioned secure element (SE) in the device is needed. Apps can also use a new Reader Mode to act as readers for HCE cards and other NFC-based transactions.

Android HCE emulates ISO/IEC 7816 based smart cards that use the contactless ISO/IEC 14443-4 (ISO-DEP) protocol for transmission. These cards are used by many systems today, including the existing EMVCO NFC payment infrastructure. Android uses Application Identifiers (AIDs) as defined in ISO/IEC 7816-4 as the basis for routing transactions to the correct Android applications.

Apps declare the AIDs they support in their manifest files, along with a category identifier that indicates the type of support available (for example, "payments"). In cases where multiple apps support the same AID in the same category, Android displays a dialog that lets the user choose which app to use.

When the user taps to pay at a point-of-sale terminal, the system extracts the preferred AID and routes the transaction to the correct application. The app reads the transaction data and can use any local or network-based services to verify and then complete the transaction.

Android HCE requires an NFC controller to be present in the device. Support for HCE is already widely available on most NFC controllers, which offer dynamic support for both HCE and SE transactions. Android 4.4 devices that support NFC will include Tap & Pay for easy payments using HCE.

New NFC capabilities through Host Card Emulation

Page 142: Android Programing Course Material

Android apps can now print any type of content over Wi-Fi or cloud-hosted services such as Google Cloud Print. In print-enabled apps, users can discover available printers, change paper sizes, choose specific pages to print, and print almost any kind of document, image, or file.

Android 4.4 introduces native platform support for printing, along with APIs for managing printing and adding new types of printer support. The platform provides a print manager that mediates between apps requesting printing and installed print services that handle print requests. The print manager provides shared services and a system UI for printing, giving users consistent control over printing from any app. The print manager also ensures the security of content as it's passed across processes, from an app to a print service.

You can add printing support to your apps or develop print services to support specific types of printers.

Printer manufacturers can use new APIs to develop their own print services— pluggable components that add vendor-specific logic and services for communicating with specific types of printers. They can build print services and distribute them through Google Play, making it easy for users to find and install them on their devices. Just as with other apps, you can update print services over-the-air at any time.

Client apps can use new APIs to add printing capabilities to their apps with minimal code changes. In most cases, you would add a print action to your Action Bar and a UI for choosing items to print. You would also implement APIs to create print jobs, query the print manager for status, and cancel jobs. This lets you print nearly any type of

Printing framework

Page 143: Android Programing Course Material

content, from local images and documents to network data or a view rendered to a canvas.

For broadest compatibility, Android uses PDF as its primary file format for printing. Before printing, your app needs to generate a properly paginated PDF version of your content. For convenience, the printing API provides native and WebView helper classes to let you create PDFs using standard Android drawing APIs. If your app knows how to draw the content, it can quickly create a PDF for printing.

Most devices running Android 4.4 will include Google Cloud Print pre-installed as a print service, as well as several Google apps that support printing, including Chrome, Drive, Gallery, and QuickOffice.

Page 144: Android Programing Course Material

A new storage access framework makes it simple for users to browse and open documents, images, and other files across all of their their preferred document storage providers. A standard, easy-to-use UI lets users browse files and access recents in a consistent way across apps and providers.

 

Box and others have integrated their services into the storage access framework, giving users easy access to their documents from apps across the system.

Cloud or local storage services can participate in this ecosystem by implementing a new document provider class that encapsulates their services. The provider class includes all of the APIs needed to register the provider with the system and manage browsing, reading, and writing documents in the provider. The document provider can give users access to any remote or local data that can be represented as files — from text, photos, and wallpapers to video, audio, and more.

Storage access framework

Page 145: Android Programing Course Material

If you build a document provider for a cloud or local service, you can deliver it to users as part of your existing Android app. After downloading and installing the app, users will have instant access to your service from any app that participates in the framework. This can help you gain exposure and user engagement, since users will find your services more easily.

If you develop a client app that manages files or documents, you can integrate with the storage access framework just by using new CREATE_DOCUMENT or OPEN_DOCUMENT intents to open or create files — the system automatically displays the standard UI for browsing documents, including all available document providers.

You can integrate your client app one time, for all providers, without any vendor-specific code. As users add or remove providers, they’ll continue to have access to their preferred services from your app, without changes or updates needed in your code.

The storage access framework is integrated with the existing GET_CONTENT intent, so users also have access to all of their previous content and data sources from the new system UI for browsing. Apps can continue using GET_CONTENT as a way to let users import data. The storage access framework and system UI for browsing make it easier for users to find and import their data from a wider range of sources.

Most devices running Android 4.4 will include Google Drive and local storage pre-integrated as document providers, and Google apps that work with files also use the new framework.

Page 146: Android Programing Course Material

Android 4.4 introduces platform support for hardware sensor batching, a new optimization that can dramatically reduce power consumed by ongoing sensor activities.

With sensor batching, Android works with the device hardware to collect and deliver sensor events efficiently in batches, rather than individually as they are detected. This lets the device's application processor remain in a low-power idle state until batches are delivered. You can request batched events from any sensor using a standard event listener, and you can control the interval at which you receive batches. You can also request immediate delivery of events between batch cycles.

Sensor batching is ideal for low-power, long-running use-cases such as fitness, location tracking, monitoring, and more. It can makes your app more efficient and it lets you track sensor events continuously — even while the screen is off and the system is asleep.

Sensor batching is currently available on Nexus 5, and we're working with our chipset partners to bring it to more devices as soon as possible.

Low-power sensors

Page 147: Android Programing Course Material

 

Moves and Runtastic Pedometer are using the hardware step-detector to offer long-running, low-power services.

Page 148: Android Programing Course Material

Android 4.4 also adds platform support for two new composite sensors — step detector and step counter — that let your app track steps when the user is walking, running, or climbing stairs. These new sensors are implemented in hardware for low power consumption.

The step detector analyzes accelerometer input to recognize when the user has taken a step, then triggers an event with each step. The step counter tracks the total number of steps since the last device reboot and triggers an event with each change in the step count. Because the logic and sensor management is built into the platform and underlying hardware, you don't need to maintain your own detection algorithms in your app.

Step detector and counter sensors are available on Nexus 5, and we're working with our chipset partners to bring them to new devices as soon as possible.

Step Detector and Step Counter

Page 149: Android Programing Course Material

If you develop a messaging app that uses SMS or MMS, you can now use a shared SMS provider and new APIs to manage your app's message storage and retrieval. The new SMS provider and APIs define a standardized interaction model for all apps that handle SMS or MMS messages.

Along with the new provider and APIs, Android 4.4 introduces new semantics for receiving messages and writing to the provider. When a message is received, the system routes it directly to the user's default messaging app using the newSMS_DELIVER intent. Other apps can still listen for incoming messages using the SMS_RECEIVED intent. Also, the system now allows only the default app to write message data to the provider, although other apps can read at any time. Apps that are not the user's default can still send messages — the system handles writing those messages to the provider on behalf of the app, so that users can see them in the default app.

The new provider and semantics help to improve the user's experience when multiple messaging apps are installed, and they help you to build new messaging features with fully-supported, forward-compatible APIs.

SMS provider

Page 150: Android Programing Course Material

A new immersive mode lets apps use every pixel on the screen to show content and capture touch events.

Full-screen Immersive modeNow your apps can use every pixel on the device screen to showcase your content and capture touch events. Android 4.4 adds a new full-screen immersive mode that lets you create full-bleed UIs reaching from edge to edge on phones and tablets, hiding all system UI such as the status bar and navigation bar. It's ideal for rich visual content such as photos, videos, maps, books, and games.

In the new mode, the system UI stays hidden, even while users are interacting with your app or game — you can capture touch events from anywhere across the screen, even areas that would otherwise be occupied by the system bars. This gives you a great way

New ways to build beautiful apps

Page 151: Android Programing Course Material

to create a larger, richer, more immersive UI in your app or game and also reduce visual distraction.

To make sure that users always have easy, consistent access to system UI from full-screen immersive mode, Android 4.4 supports a new gesture — in immersive mode, an edge swipe from the top or bottom of the screen now reveals the system UI.

To return to immersive mode, users can touch the screen outside of the bar bounds or wait for a short period for the bars to auto-hide. For a consistent user experience, the new gesture also works with previous methods of hiding the status bar.

Transitions framework for animating scenesMost apps structure their flows around several key UI states that expose different actions. Many apps also use animation to help users understand their progress through those states and the actions available in each. To make it easier to create high-quality animations in your app, Android 4.4 introduces a new transitions framework.

The transitions framework lets you define scenes, typically view hierarchies, and transitions, which describe how to animate or transform the scenes when the user enters or exits them. You can use several predefined transition types to animate your scenes based on specific properties, such as layout bounds, or visibility. There's also an auto-transition type that automatically fades, moves, and resizes views during a scene change. In addition, you can define custom transitions that animate the properties that matter most to your app, and you can plug in your own animation styles if needed.

With the transitions framework you can also animate changes to your UI on the fly, without needing to define scenes. For example, you can make a series of changes to a view hierarchy and then have the TransitionManager automatically run a delayed transition on those changes.

Once you've set up transitions, it's straightforward to invoke them from your app. For example, you can call a single method to begin a transition, make various changes in your view hierarchy, and on the next frame animations will automatically begin that animate the changes you specified.

Page 152: Android Programing Course Material

Apps can use new window styles to request translucent system bars.

For custom control over the transitions that run between specific scenes in your application flow, you can use the TransitionManager. The TransitionManager lets you define the relationship between scenes and the transitions that run for specific scene changes.

Translucent system UI stylingTo get the most impact out of your content, you can now use new window styles and themes to request translucent system UI, including both the status bar and navigation bar. To ensure the legibility of navigation bar buttons or status bar information, subtle gradients is shown behind the system bars. A typical use-case would be an app that needs to show through to a wallpaper.

Enhanced notification access

Page 153: Android Programing Course Material

Notification listener services can now see more information about incoming notifications that were constructed using the notification builder APIs. Listener services can access a notification's actions as well as new extras fields — text, icon, picture, progress, chronometer, and many others — to extract cleaner information about the notification and present the information in a different way.

Chromium WebViewAndroid 4.4 includes a completely new implementation of WebView that's based onChromium. The new Chromium WebView gives you the latest in standards support, performance, and compatibility to build and display your web-based content.

Chromium WebView provides broad support for HTML5, CSS3, and JavaScript. It supports most of the HTML5 features available in Chrome for Android 30. It also brings an updated version of the JavaScript Engine (V8) that delivers dramatically improved JavaScript performance.

In addition, the new Chromium WebView supports remote debugging using Chrome DevTools. For example, you can use Chrome DevTools on your development machine to inspect, debug, and analyze your WebView content live on a mobile device.

The new Chromium WebView is included on all compatible devices running Android 4.4 and higher. You can take advantage of the new WebView right away, and with minimum modifications to existing apps and content. In most cases, your content will migrate to the new implementation seamlessly.

Page 154: Android Programing Course Material

Screen recordingNow it's easy to create high-quality video of your app, directly from your Android device. Android 4.4 adds support for screen recording and provides a screen recording utility that lets you start and stop recording on a device that's connected to your Android SDK environment over USB. It's a great new way to create walkthroughs and tutorials for your app, testing materials, marketing videos, and more.

With the screen recording utility, you can capture video of your device screen contents and store the video as an MP4 file on the device. You can record at any device-supported resolution and bitrate you want, and the output retains the aspect ratio of the display. By default, the utility selects a resolution equal or close to the device's display resolution in the current orientation. When you are done recording, you can share the video directly from your device or pull the MP4 file to your host computer for post-production.

If your app plays video or other protected content that you don’t want to be captured by the screen recorder, you can useSurfaceView.setSecure() to mark the content as secure.

You can access screen recording through the adb tool included in the Android SDK, using the commandadb shell screenrecord. You can also launch it through the DDMS panel in Android Studio.

Resolution switching through adaptive playbackAndroid 4.4 brings formal support for adaptive playback into the Android media framework. Adaptive playback is an optional feature of video decoders for MPEG-DASH and other formats that enables seamless change in resolution during playback. The client can start to feed the decoder input video frames of a new resolution and the resolution of the output buffers change automatically, and without a significant gap.

Resolution switching in Android 4.4 lets media apps offer a significantly better streaming video experience. Apps can check for adaptive playback support at runtime using existing APIs and implement resolution-switching using new APIs introduced in Android 4.4.

Common Encryption for DASHAndroid now supports the Common Encryption (CENC) for MPEG-DASH, providing a standard, multiplatform DRM scheme for managing protecting content. Apps can take

New media capabilities

Page 155: Android Programing Course Material

advantage of CENC through Android's modular DRM framework and platform APIs for supporting DASH.

HTTP Live StreamingAndroid 4.4 updates the platform's HTTP Live Streaming (HLS) support to a superset of version 7 of the HLS specification (version 4 of the protocol). See the IETF draft for details.

Audio Tunneling to DSPFor high-performance, lower-power audio playback, Android 4.4 adds platform support for audio tunneling to a digital signal processor (DSP) in the device chipset. With tunneling, audio decoding and output effects are off-loaded to the DSP, waking the application processor less often and using less battery.

Audio tunneling can dramatically improve battery life for use-cases such as listening to music over a headset with the screen off. For example, with audio tunneling, Nexus 5 offers a total off-network audio playback time of up to 60 hours, an increase of over 50% over non-tunneled audio.

Media applications can take advantage of audio tunneling on supported devices without needing to modify code. The system applies tunneling to optimize audio playback whenever it's available on the device.

Visualization of how the LoudnessEnhancer effect can make speech content more audible.

Audio tunneling requires support in the device hardware. Currently audio tunneling is available on Nexus 5 and we're working with our chipset partners to make it available on more devices as soon as possible.

Page 156: Android Programing Course Material

Audio monitoringApps can use new monitoring tools in the Visualizer effect to get updates on the peak and RMS levels of any currently playing audio on the device. For example, you could use this creatively in music visualizers or to implement playback metering in a media player.

Loudness enhancerMedia playback applications can increase the loudness of spoken content by using the new LoudnessEnhancer effect, which acts as compressor with time constants that are specifically tuned for speech.

Audio timestamps for improved AV syncThe audio framework can now report presentation timestamps from the audio output HAL to applications, for better audio-video synchronization. Audio timestamps let your app determine when a specific audio frame will be (or was) presented off-device to the user; you can use the timestamp information to more accurately synchronize audio with video frames.

Wi-Fi CERTIFIED Miracast™Android 4.4 devices can now be certified to the Wi-Fi Alliance Wi-Fi Display Specification as Miracast compatible. To help with testing, a new Wireless Display developer option exposes advanced configuration controls and settings for Wireless Display certification. You can access the option at Settings > Developer options > Wireless display certification. Nexus 5 is a Miracast certified wireless display device.

Page 157: Android Programing Course Material

Module XIIIBusiness, UX, & Marketing

Page 158: Android Programing Course Material

Overview

ICT as a general purpose technology changes fundamentally the way value is created for customers. ICT does not only allow an increase of efficiency of existing industries but also creates new or different businesses that have little in common with traditional economic activities. So the traditional units of analysis are too broad to capture the changes occurring since the very fundamentals of value creation are being changed by ICT. A business is the fundamental of any value creation and therefore the business should be the unit of analysis for any fundamental change in value creation. The more aggregated units of analysis like the industry or the business unit are well suited as soon as the fundamentals of a business are understood. But to gain the understanding one has to investigate first what a business is.

Interestingly, very seldom the term business is being defined. Even Porter (1985: 58) does not define a business. He defines only a business unit. He gives advice how to optimally segment a corporation into business units but does not write about what a business is. In this seminal work he mentioned several key parts of a business like the value chain, the customers, the suppliers and the competitors but other parts like the source of revenue he mentions only on the sideline. His focus is on the industry and how a company can obtain superior profits by finding a profitable and defendable position in that industry.

Peter Drucker is one of the few who answers what a business is by asking several questions about the fundamentals of a business: Who is your customer? And what does the customer value?

A business model is defined as the rationale of how an organization creates, delivers and captures value.

Business model innovation is a process of reinventing the business model itself in order to deliver and capture enough value associated with the new creation to bring it to market.

Business innovation Model “BiM”

Page 159: Android Programing Course Material

As Guy Kawasaki says in his book “The Art of the Start,” if you can’t describe your business model in ten words or less, you don’t have a business model. Avoid whatever business jargon is currently hip, like strategic, mission-critical, world-class, synergistic, first-mover, or scalable. Try something like, “the product costs $X, and we sell it for $Y.”

Guy also says that the smart approach is to copy somebody else. You can innovate in technology, markets, and customers, but inventing a new business model is a bad bet. Try to relate your business model to one that’s already successful and understood. Here is a summary of a half-dozen of the most common models:

Facebook model. This is the most often attempted and failed business model today on the Internet – all the services are free, and you make money off the online advertising. This model only works once you have exceeded about one million page-views per month, and spent maybe $50 million to get there.

eCommerce model. This was one of the first Internet business models, per Amazon.com, and still a popular one today. It’s the electronic version of a catalog and shopping cart, and today rarely involves any stock of product. Products are usually drop-shipped directly by the manufacturer.

Shopkeeper model. This is the most traditional and successful approach in use for centuries. It implies setting up a store in a location where potential customers are likely to be, with products and services on display, being sold at some multiple of cost to cover the overhead and realize a profit.

Bricks-and-clicks model. This is a hybrid of the shopkeeper and eCommerce models, in which a company integrates both offline (bricks) and online (clicks) presences. It is also known as click-and-mortar, as well as bricks, clicks and flips, with flips referring to catalogs. It’s great for big companies like Wal-Mart, but I don’t recommend it for startups.

Razor-and-blades model. This one has been around for many years now, and is sometimes called the “bait and hook model” or the "tied products model". The premise is offering a basic product at a very low cost, often at a loss (the "bait"), then charging compensatory recurring amounts for refills or associated products or services (the "hook"). I’m sure you can think of many examples.

Subscription or licensing model. Here a customer must pay a contracted price to have access to the product or service on a periodic basis (monthly, yearly, or seasonal). The model works online, offline, through magazines, newspapers, and television. The advantage is recurring revenue without finding new customers.

Page 160: Android Programing Course Material

There are many more, with descriptive names like the auction model, direct sales model, value-added reseller model, multi-level marketing model, and the freemium model. Take a look at Wikipedia if you want more details.

The point I am making is – pick one and provide specifics in your business plan. Define clearly who is your customer, what will the customer pay for, how much will he pay, and how much do you expect it to cost for that revenue.

Then as investors, we can argue other equally important parts of the model, like how big is the opportunity, how fast it’s growing, and who are the competitors. Don’t let your business plan be tossed before you are in the game. What are the ten words that define your business model?

Page 161: Android Programing Course Material

A new era of business is coming, one that is driven by collaboration, crowdfunding and the desire to kickstart the creative economy.

The business model is one of the key elements in the planning process. Without a rock-solid business model, no business (or social enterprise) can sustain itself over the long term. When you break down the PLAN into its basic components, the business model is the what and the strategy is the how. Business models have multiple components that combine to shape what the business will look like in the market.

Why is it so important to PLAN your business model?

Business model innovation is the essential activity for any company that wants to succeed in the new era of business. With change occurring at such a rapid rate in markets globally, consumers around the world are beginning to rapidly redefine the value curve. Spending five hours trying to reinvent your value proposition today using the business model canvas could save you from five years of frustration by going down the wrong road.

The goal is to develop a business model that can withstand and adapt to the rapid changes that are happening in the market, as the rate of change will only accelerate more going forward.

The first key to understanding how to do this is to understand what the business model is. According to the definition from Business Model Generation, a business model is defined as:

"the rationale of how an organization creates, delivers and captures value in the market".

Business Model Plan

Page 162: Android Programing Course Material

Once you understand what a business model is, you need to have the tools to experiment with your own business model.

Page 163: Android Programing Course Material

Example with a filled Business Model plan

Page 164: Android Programing Course Material

The aim of this study to study the market with real field questioner and study for the product and people acceptance and readiness to use or buy this product or service and determine the expected ROI.

You can also use verified statistics, or even real life working business modules to prove the capabilities and potentials in your business.

Feasibility or case study (success and failure) mentioning business model

Page 165: Android Programing Course Material

You have to measure and weight your Strength, Weakness, Opportunities, and Threats points to have a real understanding to your potentials and the obstacles that might delay or even stop your business.

Strength points and weakness points

Page 166: Android Programing Course Material

Think about a win-win situation. Not because your need a win means that others should lose. Everyone wants to be a winner even your user who will download your app.

Be in your user chose and think what you will benefit from your business and what is in it for you.

Benefits for all

Page 167: Android Programing Course Material

Overview

UX Track gives you the ability to create User Interface Design with focus on optimal efficiency, simplicity and functionality to create remarkable mobile apps. That improves the experience and usage of mobile apps to make people love it.

The term "user experience" was brought to wider knowledge by Donald Norman (The Ex-Vice President of the Advanced Technology Group at Apple) in the mid-1990s.

The best definition I could find was written by by Jakob Nielsen "A famous author and considered as the Father of usability" and Don Norman,

"The first requirement for an exemplary user experience is to meet the exact needs of the customer, without fuss or bother. Next comes simplicity and elegance that produce products that are a joy to own, a joy to use. True user experience goes far beyond giving customers what they say they want, or providing checklist features. In order to achieve high-quality user experience in a company's offerings there must be a seamless merging of the services of multiple disciplines, including engineering, marketing, graphical and industrial design, and interface design.

It's important to distinguish the total user experience from the user interface (UI), even though the UI is obviously an extremely important part of the design. As an example, consider a website with movie reviews. Even if the UI for finding a film is perfect, the UX will be poor for a user who wants information about a small independent release if the underlying database only contains movies from the major studios.

We should also distinguish UX and usability: According to the definition of usability, it is a quality attribute of the UI, covering whether the system is easy to learn, efficient to use, pleasant, and so forth. Again, this is very important, and again total UX is an even broader concept."

UX “User Experience”

Page 168: Android Programing Course Material

You can also refer to this recent study to gain more knowledge about User Experience and Usability importance,

Usability - The key for success or failure of web projects (http://www.grin.com/en/e-book/196416/usability-the-key-for-success-or-failure-of-web-projects).

Page 169: Android Programing Course Material

Having an app that is easy to use is of utmost importance to your business. It can be your competitive advantage when your competitors fail to do the same.

You can find that the market have more than 10 apps do same function but only 2 are having 90% of the download, that is because of the UX.

Your app could be for creating and managing tasks, if the user could create a new task in 2 or 3 click he will search for another app that can do, no matter how powerful or advanced or even free your app is.

Mobile users don't want to learn how to use new apps, all what they expecting is simple Plug and Play model.

Not to have a great app means to sacrifice the design.

Mere design is not the objective but a design that adhere UX recommendations is the one.

UI & usability as competitive advantage

Page 170: Android Programing Course Material

With good app UX and better presentation than your competitors your app can promote itself, remember that the best advertisement in the world is word of mouth.

So invest in UX and make sure that your investment will give you the best ROI for your investment.

UX from the precipitant of sales power

Page 171: Android Programing Course Material

In 1998, Pine and Gilmore in the Harvard Business Review wrote an article called “Welcome to the experience economy” where they explain that companies need to shift focus from the provision of merely goods and services to the provision of consumers with experiences. They later wrote a book about the subject called: “The experience economy: work is theatre & every business a stage”. They describe experiences as distinct, personal and memorable offerings. They allude to experience as a commodity and a unique economic offering, essential to attaining a competitive advantage in today’s market. Since 1998, there has been much written about the economic importance of creating products and services that provide consumers with a positive user experience. Today the need for providing consumers with a positive experience has become crucial.

Today customer experience is holistic spanning both multiple touch points and multiple media. A customers experience of your brand is influenced by not only your products or offerings but also by it’s packaging, the process of obtaining the product or service, putting it together, how it fits in with your other services, ease of finding it, all of the personal experiences with your staff or yourself etc. Think about how many different individuals and teams are involved on the delivery of experiences to your customers. These could include the folks on the phone, marketing people, any advertising agencies you may engage, graphic designers, distribution staff, product managers, that is all your staff and all of the organizations that you engage. In order to give your customers positive experiences all of these individuals need to deliver a consistent and positive experience to your consumers to ensure their loyalty and indeed their advocacy.

Since the days of the village markets, word of mouth has played an important role within business. Remarkable experiences leave a mark, whether the experience is remarkably good or remarkably bad! These days' consumers have so many different ways to share their experiences about your business with each other.

Below is a schema adapted from one by Adaptive Path:

Tips for promoting UX as a competitive advantage

Page 172: Android Programing Course Material
Page 173: Android Programing Course Material

Overview

Mobile app marketing is a complex procedure that takes up a lot of time and effort for the marketer involved. However, it can also yield immense benefits if a properly planned and executed marketing strategy works among the masses. So, how do you go about planning out a mobile app marketing strategy that can also guarantee success to a large extent?

You have to first understand that your main focus has to be the end-users of your app. You are essentially dealing with people and so, you will have to study their mobile behavior and understand the same, before embarking on a particular marketing strategy

Mobile Application Marketing “MAK”

Page 174: Android Programing Course Material

The primary and most important thing you should do is to focus on your target audience and find ways to engage them. Study them keenly and recognize their unique behavior patterns. While each user is unique, customers who use different mobile devices also behave differently. For instance, the younger generation easily adapts to the latest technology, including Android and the iPhone. Business professionals usually tend toward purchasing business phones, tablets and so on.

One effective method to analyse customer behavior would be to study the traffic that visits your mobile Website. The type of visitors here will let you know the kind of devices they use, their needs and requirements and so on.

You could also conduct customer surveys in order to understand your mobile customers better, so that you could serve them better.

Study Customer Behavior Patterns

Page 175: Android Programing Course Material

Your main objective should be to try and provide your customers the maximum benefit they can ever get from the use of a mobile app. Remember, the customer is the actual key to your success in the app marketplace; so see to it that he or she is completely satisfied with the services you have to offer.

In order to do this, you will have to start active interaction with your audience. Keep offering them irresistible offers and deals, provide them useful location-based information, help them share this information with friends on mobile social networks and so on. You could also add a poll or rating service in your app, so as to generate immediate feedback from your users.

App marketing is vital to you as a marketer, as it lets you connect directly with your end-users, in real-time. Take full advantage of this fact and try to give your audience the richest possible user experience from your app, each and every time.

Once your app becomes successful in the market, you could then think of monetizing the same with ads, offer premium services for a nominal extra charge and so on.

Keep in Mind Your Main Objective

Page 176: Android Programing Course Material

Once you are through with the above steps, you need to go ahead and refine your marketing strategy. This involves a lengthy process of planning, including building a team to handle the various aspects of your plan; publicizing and advertising your service; gathering and processing user information; choosing the right mobile platforms for marketing your app and so on.

You will also have to decide upon the time period for your promotional efforts. For this, you will need to know if you want short-term or long-term promotion for your mobile product or service. In case you want a long-term commitment, you will further have to decide how to plan, maintain and execute the various stages of the app marketing process.

If your app fits into a commercial venture, you can decide to price your app. Needless to say, you will have to make a detailed plan for this app pricing aspect as well.

Refine Your Marketing Strategy

Page 177: Android Programing Course Material

The final step is to choose the right type of mobile technology for marketing your app. SMS is probably the best method to reach the maximum audience, due to the fact that it is the cheapest method, which also adapts to almost all types of mobile phones. This method of communication is also the most direct and one which your audience can opt-in to receive as well.

Creating a mobile Website is a good idea too, as the majority of smartphone and other mobile device users today are known to access the Internet through their devices. Of course, you will have to think of ease of user navigation around your mobile Website, also providing the most relevant information to your customer, at all times. The latest HTML5 will eventually go on to make this whole process much easier for you.

Creating an app featuring your product or service is yet another vital app marketing strategy. Mobile apps can be easily downloaded and used. Of course, creating an app will require you to spend time and money on it. Based on your budget, you will then have to decide which mobile platforms you will want to deploy it to.

Choose the Right Mobile Technology

Page 178: Android Programing Course Material

Resources

Page 179: Android Programing Course Material

1. http://developer.android.com/index.html2. Ebook:Professional Android 4 Application Development3. Ebook: Android 4 Application Development