+ All Categories
Home > Documents > Mobile app

Mobile app

Date post: 13-May-2015
Category:
Upload: attaporn-ninsuwan
View: 471 times
Download: 22 times
Share this document with a friend
Popular Tags:
174
Mobile Application Development Dejvuth Suwimonteerabuth
Transcript
Page 1: Mobile app

Mobile Application Development

Dejvuth Suwimonteerabuth

Page 2: Mobile app

Why mobile application development?

Worldwide mobile device sales to end users totaled 1.55 billionunits in 2011, a 11 percent increase from 2010 [IDC]

Sales for the first quarter of 2012 [IDC]:

Page 3: Mobile app

Phones get “smarter”

Around 26% of worldwide sales in 2011 are smartphones, andestimated to reach 1 billion (47%) in 2015 [Gartner]

In U.S., 49.7% have smartphones, the trend is accelerating [Nielsen]

Page 4: Mobile app

Smartphones aren’t smart without apps

More than 600,000 apps available [Business Insider]

Page 5: Mobile app

Apps can make a lot of money

The mobile app market will reach $15 billion by 2013[Research2guidance]

Page 6: Mobile app

Mobile applications are not ported desktop apps!

Factors that need to consider when working on a mobile app:Memory

Limited, and much of it is already allocatedApp speed

Usage patterns of mobile app are differentApps need to load and work quickly

Internet accessNetwork is not always available and typically slow

DisplaySmaller display

User inputButtons, touch screen

Page 7: Mobile app

A bit of history and outlook

Page 8: Mobile app

Brief history of mobile devices

PDA (Personal Digital Assistant)

Page 9: Mobile app

PDA Phone

PDA + mobile phone→ PDA phone

Page 10: Mobile app

Smartphones

Now PDA phones are called smartphones, offering manycomputer-like functionalities

Page 11: Mobile app

Mobile applications

Applications for handheld devices such as PDA, smartphones

Development environment:

Page 12: Mobile app

Wars on smartphone platform (2010) [Canalys]

Page 13: Mobile app

Wars on smartphone platform (2012) [Gartner, IDC]

Page 14: Mobile app

Wars on smartphone platform [Nielsen]

Page 15: Mobile app

Apple vs. Google

Battle continues, arguments varied . . .

. . . depending on who you ask

A look into history: compare with Mac/PC battlesSimilar (many PC manufacturers, one Apple)Different (Microsoft sells Windows, Google gives awayAndroid)

Page 16: Mobile app

Apple still dominates the market, but . . .

Page 17: Mobile app

Another look at recent trendsIn April 2011, Android added 28,000 new apps, Apple 11,000apps [Research2guidance]

Page 18: Mobile app

This course

Page 19: Mobile app

This course

Application development for the Android platform

Introduction to iOS

Emphasis on basics to make the contents robust to changes.

Theories behind mobile communication

Prerequisite: strong Java programming skills

Important: Things change and not everything can be covered inthis course. Self-learning skill is necessary.

Android phone is not required

Page 20: Mobile app

Topics

Java refresher

Key concepts of Android

Designing the user interface

2D graphics

Multimedia

Local data storage

Network access

Embedded database

3D graphics in OpenGL

Multi-touch

Widget

Page 21: Mobile app

Schedule

On

10 Jun, 24 Jun, 8 Jul, 22 Jul, 19 Aug, 2 Sep, 16 Sep, 30 Sep

Lecture: 08:30–12:00

Lab: 13:00–17:00

Don’t come to class late!

Page 22: Mobile app

Grading

Midterm exam 25%

Final exam 25%

Project 25%

Lab 15%

Attendance & Participation 10%

Below 50% is fail, above 80% is A

The rests are proportional

Page 23: Mobile app

Project

At the end of the course, each of you must program anapplication on Android

You can program anything you want (but use your creativity!)

Due date: 30 September

Each of you must give a presentation on that day

Make sure your program is fully tested (non-functionalprograms are worse than simple but functional programs)!

Write down a documentation of what your program does

Marks are given based on creativity, complexity,documentations, and the presentation

Page 24: Mobile app

Literature

The slides will be updated during the course of the lecture

References:“Hello, Android – Introducing Google’s MobileDevelopment Platform”, Ed Burnette, 3rd Edition (2010).http://developer.android.com

Any Java and Android books on the market

Page 25: Mobile app

Java refresher

Page 26: Mobile app

Why refresh?

Android applications are written in Java

Without fully understanding Java, you will not be able to writeany Android applications

Important: Take your time with Java, make sure you understandits concepts

We will use the slides Java Refresher Course fromAndrea Camesi, EPFL

Page 27: Mobile app

Key Concepts

Page 28: Mobile app

What is Android?

An open source software stack that includesOperating system: Linux kernel, provides low levelinterface with hardware, memory management, andprocess controlMiddleware: A run time to execute Android applications,including Dalvik virtual machine and core librariesKey mobile apps: Email, SMS, PIM, web browser, etcAPI libraries for writing mobile app such as SQLite,WebKit, and OpenGL ES

Open-source development platform for creating mobile apps

Page 29: Mobile app

Android history

Android Inc. founded in 2003. Google acquired Android Inc.in 2005

Open Handset Alliance established on 5 November 2007Led by Google with 34 members (now 80 firms)Android is first announced on that day

Code name based on adessert item, inalphabetical order:1.5 Cupcake, 1.6 Donut,2.0/2.1 Eclair, 2.2 Froyo,2.3 Gingerbread,3.0/3.1 Honeycomb, and4.0 Ice Cream Sandwich

Page 30: Mobile app

Android SDK features

No licensing, distributions, or development frees or releaseapproval processes

GSM, EDGE, and 3G networks for telephony and data transfer

Full multimedia hardware control

APIs for using sensor hardware including accelerometer andthe compass.

APIs for location based services

Inter-process communication

Shared data storage

Background applications and processes

Home screen widgets, Live Folders

HTML5 WebKit-based web browser

And many more . . .

Page 31: Mobile app

Android SDK

The Android SDK includesThe Android APIs: the core of the SDKDevelopment tools: for compiling and debuggingThe Android Virtual Device (AVD) Manager and EmulatorDocumentationsSample code

There is no dedicated IDE for Android

However, Android has a special plugin for Eclipse, called ADTPlugin, for creating Android projects

ADT Plugin tightly integrates Eclipse with the Android Emulatorand debugging tools

Page 32: Mobile app

Android architecture

Page 33: Mobile app

Android architecture

Page 34: Mobile app

Linux kernel

Android is built on top of a solid and proven foundation: theLinux kernel

Created by Linus Torvalds in 1991

Linux can be found today in everything from wristwatches tosupercomputer

It provides the hardware abstraction layer for Android as well asmemory management, process management, networking, andother operating system services

Android phone user will never see Linux, and your programswill not make Linux calls directly

Page 35: Mobile app

Native libraries

Next layer above the kernel, written in C or C++

Compiled for the particular hardware architecture used by thephone, and preinstalled by the phone vendor

Important libraries include:Surface Manager: a compositing window manager2D and 3D graphicsMedia codecs for recording and playing variety of formatsincluding AAC, AVC (H.264), H.263, MP3, and MPEG-4SQLite database for storing persistent dataWebKit: a browser engine for fast display of HTML content

Libraries are not applications by themselves. They are only tobe called by higher-level layers.

Page 36: Mobile app

Android runtime

Another layer on top of the kernel.

Android runtime includes the Dalvik virtual machine (VM) andthe core Java libraries.

Dalvik VM is Google’s implementation of Java, optimized formobile devices

Differ from traditional Java VM:Dalvik VM runs .dex files, converted at compile time fromstandard .class and .jar files. Reason: .dex files aremore compact.Android’s core Java libraries are different from both theJava Standard Edition (Java SE) libraries and the JavaMobile Edition (Java ME) libraries

Page 37: Mobile app

Application framework

Sitting above the native libraries and runtime

Provides high-level building blocks for creating applications

Comes pre-installed with Android, can be extend if needed

Important parts are:Activity manager controls the life cycles of applications anduser navigationContent providers encapsulate data that needs to beshared between applications, such as contactsResource manager provides access to non-code resourcessuch as localized strings, graphics, and layout filesLocation manager provides location informationNotification manager presents messages to users

Page 38: Mobile app

Applications and widgets

The highest layer. They are what users see.

Applications are programs that take over the whole screen andinteract with users

Widgets operate only in a small rectangle of the Home screenapplication

Standard system applications: phone dialer, email, contacts,web browser, Android markets

The most part of this course will cover application development.Widgets development is at the end of the course.

Page 39: Mobile app

Life cycle

Page 40: Mobile app

One foreground application at a time

On PC, many applications running and visible at once indifferent windows. One of the windows has keyboard focus, butotherwise all the programs are equal.

In Android, one foreground application, typically takes over thewhole screen except for the status line.

Users first see the Home application when turning on theirphones

Page 41: Mobile app

Application stack

When the user runs an application, Android starts it and bringsit to the foreground.

From that application, the user might invoke anotherapplication, or another screen in the same application, and thenanother and another.

All these programs and screens are recorded on the applicationstack by the system’s Activity Manager.

At any time, the user can press the Back button to the previousscreen on the stack.

Page 42: Mobile app

Process 6= application

Internally, each user interface screen is represented by anActivity class

Each activity has its own life cycle

An application is one or more activities plus a Linux process tocontain them

However, the activity life cycle is not tied to the process lifecycle

Processes are just disposable containers for activities, so anapplication can be “alive” even if its process has been killed!

Page 43: Mobile app

Life cycle

During its lifetime, each activity of an Android program can bein one of the following states:

Page 44: Mobile app

Life cycle (cont.)

Developers do not have control over what states their programsare in

The system manages changes of states and notify developerswhen they are about to change through the onXX() methodcalls

We override these methods in the Activity class, andAndroid will call them at the appropriate time:

onCreate(Bundle): This is called when the activity firststarts up.You can use it to perform one-time initialization such ascreating the user interface. onCreate() takes oneparameter that is either null or some state informationpreviously saved by the onSaveInstanceState()method.

Page 45: Mobile app

Life cycle (cont.)

onStart(): This indicates the activity is about to bedisplayed to the useronResume(): This is called when your activity can startinteracting with the user. This is a good place to startanimations and music.onPause(): This runs when the activity is about to go intothe background, usually because another activity has beenlaunched in front of it. This is where you should save yourprogram’s persistent state, such as a database recordbeing edited.onStop(): This is called when your activity is no longervisible to the user and it won’t be needed for a while. Ifmemory is tight, onStop() may never be called (thesystem may simply terminate your process).

Page 46: Mobile app

Life cycle (cont.)

onRestart(): Indicates that your activity is beingredisplayed to the user from a stopped stateonDestroy(): This is called right before your activity isdestroyed. If memory is tight, onDestroy() may never becalled (the system may simply terminate your process).onSaveInstanceState(Bundle): Android will call thismethod to allow the activity to save per-instance state,such as a cursor position within a text field. Usually youwon’t need to override it because the defaultimplementation saves the state for all your user interfacecontrols automatically.onRestoreInstanceState(Bundle): This is calledwhen the activity is being reinitialized from a statepreviously saved by the onSaveInstanceState()method. The default implementation restores the state ofyour user interface.

Page 47: Mobile app

Caveat

Activities that are not running in the foreground may bestopped, or the Linux process that houses them may be killedat any time in order to make room for new activities

So, design your app with this in mind!

In some cases, onPause() may be the last method called inyour activity, so that’s where you should save any data you wantto keep around for next time.

Page 48: Mobile app

Building blocks

Page 49: Mobile app

Activities

An activity is a user interface screen

Applications can define one or more activities to handledifferent phases of the program.

As discussed earlier, each activity is responsible for saving itsown state so that it can be restored later as part of theapplication life cycle

Page 50: Mobile app

Intents

An intent is a mechanism for describing a specific action, suchas “pick a photo”, “phone home”, or “open the pod bay doors”

Just about everything goes through intents, many componentscan be replaced or reused

For example, there is an intent for “send an email”. Your appcan invoke that intent to send emails.

Or you can write a new email application, and register anactivity to handle that intent and replace the standard mailprogram

Next time somebody tries to send an email, they’ll get theoption to use your program instead of the standard one

Page 51: Mobile app

Services

A service is a task that runs in the background without theuser’s direct interaction

For example, consider a music player. The music may bestarted by an activity, but you want it to keep playing even whenthe user has moved on to a different program.

So, the code that does the actual playing should be in aservice.

Later, another activity may bind to that service and tell it toswitch tracks or stop playing.

Android comes with many services built in, along withconvenient APIs to access them.

Page 52: Mobile app

Content providers

A content provider is a set of data wrapped up in a custom APIto read and write it

This is the best way to share global data between applications.

For example, Google provides a content provider for contacts.All the information there—names, addresses, phone numbers,and so forth—can be shared by any application that wants touse it.

Page 53: Mobile app

Resources

A resource is a localized text string, bitmap, or other smallpiece of noncode information that your program needs.

Useful for internationalization and for supporting multiple devicetypes

Inside your project, resources are stored in the res directory.Its subfolders determine the content types, e.g. PNG and JPGin res/drawable and XMLs for screen layouts inres/layout

At build time all resources get compiled into the application.The compiler generates a class named R that containsidentifiers that can be used to reference those resources in theprogram

Page 54: Mobile app

The AndroidManifest.xml file

Every application must have an AndroidManifest.xml file(with precisely that name) in its root directory.

The manifest presents essential information about theapplication to the Android system

Among other things, the manifestnames the Java package for the applicationdescribes the components of the application—theactivities, services, broadcast receivers, and contentproviders that the application is composed ofdetermines which processes will host applicationcomponentsdeclares which permissions the application must havedeclares the minimum level of the Android API that theapplication requires.

Page 55: Mobile app

Security

As mentioned earlier, every application runs in its own Linuxprocess

The hardware forbids one process from accessing anotherprocess’s memory

Furthermore, every application is assigned a specific user ID.Any files it creates cannot be read or written by otherapplications.

Access to certain critical operations are restricted. To usethem, permissions must be specifically asked in a file namedAndroidManifest.xml

When installing, the Package Manager either grants or doesn’tgrant the permissions based on certificates and, if necessary,user prompts

Page 56: Mobile app

Permissions in AndroidManifest.xml

Common permissions:INTERNET: Access the InternetREAD_CONTACTS: Read the user’s contacts dataWRITE_CONTACTS: Write the user’s contacts dataRECEIVE_SMS: Monitor incoming SMS messagesACCESS_COARSE_LOCATION: Use a coarse locationprovider such as cell towers or wifiACCESS_FINE_LOCATION: Use a more accurate locationprovider such as GPS

E.g., add the following tag to monitor incoming SMS messages:

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

Page 57: Mobile app

Designing the User Interface

Page 58: Mobile app

Designing the User Interface

In this section: how to design user interfaces

We will learn by going through examples based on Sudoku

Page 59: Mobile app

Sudoku

You have a grid of 81 tiles (9× 9)

When the game starts, some numbers are already filled in

You try to fill in the rest so that each column, each row, andeach of the 3× 3 sub-grids contains the numbers 1 through 9only once

Page 60: Mobile app

Procedural vs. declarative UI design

Procedural design is done in code, e.g. Java Swing where codemust be written to create and manipulate UI objects such asJFrame and JButton

Declarative design does not involve code, e.g. HTML where youdescribe what you want to see, not how you want to do it

Android can handle both, either in Java or XML

It is recommended, however, to use XML as much as possibleas it is often shorter and easier to understand, and less likely tochange

Page 61: Mobile app

R.java

By default, the main (declarative) UI of your program is kept inmain.xml in the res/layout directory

The file can be referred in the code by using the resourceidentifier R.layout.main

Eclipse plug-in automatically generates the class R.java fromfiles in the res directory

Values in R.java are not objects, but simply handles that referto the real data

public static final class layout {public static final int main=0x7f030000;

}

Page 62: Mobile app

Layout resource

Define the architecture for the UI in an Activity or a componentof a UI

Start with

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

Technically, a layout resource contains ViewGroup and View

For example,

<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical"android:layout_width="fill_parent"android:layout_height="fill_parent" ><TextView

android:id="@+id/nameTextbox"... />

<!- ... -></LinearLayout>

Page 63: Mobile app

ViewGroup

A container for View elements

FrameLayout arranges its children so they all start at the topleft of the screen. This is used for tabbed views and imageswitchers.

LinearLayout arranges its children in a single column or row.This is the most common layout you will use.

RelativeLayout arranges its children in relation to eachother or to the parent

TableLayout arranges its children in rows and columns,similar to an HTML table

Page 64: Mobile app

View

An individual UI component, generally referred to as a “widget”,e.g. TextView, Button, CheckBox

Use @+id/name to define an ID

In Java, use findViewById(R.id.nameTextbox) to referto the TextView nameTextBox

Reference to layout resource:http://developer.android.com/guide/topics/resources/layout-resource.html

Page 65: Mobile app

Don’t forget to check out the reference

Page 66: Mobile app

Some parameters to all layouts

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

Defines the XML namespace for Android. You should definethis once, on the first XML tag in the file.

android:layout_width="fill_parent",android:layout_height="fill_parent"

Takes up the entire width and height of the parent (in this case,the window)

android:layout_width="wrap_content",android:layout_height="wrap_content"

Just big enough to enclose its content

Page 67: Mobile app

strings.xml

Do not hard-code strings. Instead, define them inres/values/strings.xml.

For example,

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

<string name="app_name">Sudoku</string><string name="main_title">Android Sudoku</string><!- ... ->

</resources>

Use @string/resid to refer the the string resid

app_name, used in AndroidManifest.xml, is the app name

main_title can be used in main.xml, e.g.

<TextViewandroid:layout_width="fill_parent"android:layout_height="wrap_content"android:text="@string/main_title" />

Page 68: Mobile app

colors.xml

Define colors in res/values/colors.xml

For example,

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

<color name="background">#3500ffff</color></resources>

Colors are defined in Alpha-Red-Green-Blue format

Use @color/resid to refer to the color resid, e.g.

android:background="@color/background"

Page 69: Mobile app

Activity (revisited)

An activity is a single, focused thing that the user can do

The Activity class takes care of creating a window.

Subclasses of Activity should implement:onCreate(Bundle) initialize your activity.Call setContentView(int) with a layout resource todefine UI.Use findViewById(int) to retrieve the widgets in thatUI that you need to interact with programmatically.onPause() deals with the user leaving your activity. Anychanges made by the user should be committed at thispoint.

Page 70: Mobile app

Intent (revisited)

An intent is an abstract description of an operation to beperformed.

It can be used with startActivity(Intent) to launch anActivity

Declare all activities you start in AndroidManifest.xml, e.g.

<activity android:name=".About"android:label="@string/about_title" >

</activity>

Think of an intent as a glue between activities, basically apassive data structure holding an abstract description of anaction to be performed.

Page 71: Mobile app

Styles

A style is a collection of properties that specify the look andformat for a View or window.

A style can specify properties such as height, padding, fontcolor, font size, background color, etc.

Similar to cascading stylesheets (CSS)

Define a style using XML in res/values/

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

<style name="CodeFont"parent="@android:style/TextAppearance.Medium">

<item name="android:layout_width">fill_parent</item><item name="android:layout_height">wrap_content</item><item name="android:textColor">#00FF00</item><item name="android:typeface">monospace</item>

</style></resources>

Page 72: Mobile app

Styles and Themes

Apply a style to a View

<TextViewstyle="@style/CodeFont"android:text="@string/hello" />

A theme is a style applied to an entire Activity orapplication. When applied, every View in the Activity orapplication will apply each style property that it supports

Apply a theme to an Activity

<activity android:theme="@android:style/Theme.Dialog">

The @android: prefix means this is a reference to a resourcedefined by Android, not one that is defined in your program

Page 73: Mobile app

Options menu

Define a menu using XML in res/menu/

<?xml version="1.0" encoding="utf-8"?><menu xmlns:android="http://schemas.android.com/apk/res/android">

<item android:id="@+id/settings"android:title="@string/settings_label"android:alphabeticShortcut="@string/settings_shortcut" />

</menu>

Override Activity.onCreateOptionsMenu(Menu)

@Overridepublic boolean onCreateOptionsMenu(Menu menu) {

super.onCreateOptionsMenu(menu);MenuInflater inflater = getMenuInflater();inflater.inflate(R.menu.menu, menu);return true;

}

getMenuInflater() is used to read the menu definition frommain.xml and turns it into a real view

Page 74: Mobile app

Options menu and context menu

When the user selects any menu item,onOptionsItemSelected() will be called

@Overridepublic boolean onOptionsItemSelected(MenuItem item) {

switch (item.getItemId()) {case R.id.settings:

startActivity(new Intent(this, Prefs.class));return true;

// More items go here (if any) ...}return false;

}

Apart from options menu, a context menu can be used toprovide the user access to actions that pertain to a specific item

In this case, use onCreateContextMenu andonContextItemSelected instead

Page 75: Mobile app

Preferences

Define a preference screen using XML in res/xml/

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

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

android:key="music"android:title="@string/music_title"android:summary="@string/music_summary"android:defaultValue="true" />

<!- ... -></PreferenceScreen>

Subclass PreferenceActivity, and override onCreate tocall addPreferencesFromResource

public class Prefs extends PreferenceActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);addPreferencesFromResource(R.xml.settings);

}}

Page 76: Mobile app

AlertDialog

A Dialog that can display an array of things

new AlertDialog.Builder(this).setTitle(R.string.new_game_title).setItems(R.array.difficulty,

new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialoginterface,

int i) {startGame(i);

}})

.show();

An array can be defined using XML in res/values

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

<array name="difficulty"><item>@string/easy_label</item><item>@string/medium_label</item><item>@string/hard_label</item>

</array></resources>

Page 77: Mobile app

Debugging

The Log class provides several static methods to printmessages of various severity levels to the Android system log:

Log.e(): ErrorsLog.w(): WarningsLog.i(): InformationLog.d(): DebuggingLog.v(): VerboseLog.wtf(): What a Terrible Failure

Open LogCat to view the logs

In addition, the Eclipse debugger can be used to setbreakpoints, single step, and view the state of your program.

Add android:debuggable=“true” inAndroidManifest.xml

Page 78: Mobile app

Graphics

Page 79: Mobile app

Graphics in Android

In this section: how to make graphics in Android

Good graphics is very important these days

Android has very powerful graphics libraries: both 2D and 3D

We cover 2D graphics here, and apply it to the Sudoku example

3D graphics will be covered later

Page 80: Mobile app

The basics

Native 2D graphics library: android.graphics package

Let’s start with Color, Paint, Canvas, Path, Drawableclasses

Page 81: Mobile app

Color

Colors are represented with four numbers: alpha, red, green,and blue (ARGB)

Each has 8 bits or 256 possible values

Alpha is a measure of transparency: 0 is completelytransparent.Example:int b = Color.BLUE; // solid blueint c = Color.argb(127, 255, 0, 255); // translucent purple

Define your colors in an XML resource file<?xml version="1.0" encoding="utf-8"?><resources>

<color name="mycolor">#1fff00ff</color></resources>

In Java, we can reference colors by their namescolor = getResources().getColor(R.color.mycolor);

Page 82: Mobile app

Paint

Hold the style and color information about how to drawgeometries, text and bitmaps

Examples:setColor(int): sets the paint’s colorsetTextSize(float): sets the paint’s text sizesetStyle(Paint.Style): sets the paint’s style, usedfor controlling how primitives’ geometries are interpreted(filled and/or stroked)

Page 83: Mobile app

Path

Hold a set of vector-drawing commands such as lines,rectangles, and curves

Example of a circle at position x = 150, y = 150, with radius of100 pixels.

circle = new Path();circle.addCircle(150, 150, 100, Direction.CW);

Page 84: Mobile app

Canvas

Represent a surface to draw upon

Initially, it has no contents. Use its methods to draw lines,rectangles, circles, or other arbitrary graphics.

Activity hosts View, which in turn hosts Canvas

Override the method View.onDraw(Canvas) to draw yourcontents on the canvas

Example:

private static final String QUOTE = "Now is the time for all "+ "good men to come to the aid of their country.";

canvas.drawPath(circle, cPaint);canvas.drawTextOnPath(QUOTE, circle, 0, 20, tPaint);

Page 85: Mobile app

Drawable

An abstract class for “something that can be drawn”

Drawables can take a variety of forms:Bitmap: the simplest drawable, a PNG or JPEG imageNine Patch: a stretchable PNG imageShape: vector-drawing commands, based on Path

Layers: a container for child drawables, on top of eachotherStates: a container that shows one of its child drawablesbased on its state (a bit mask)Levels: a container that shows one of its child drawablesbased on its level (a range of integers)Scale: a container for one child drawable that modifies itssize based on the current level

Page 86: Mobile app

The book’s example

Page 87: Mobile app

Adding graphics to Sudoku

Page 88: Mobile app

What have been done so far?

Page 89: Mobile app

Now, draw the board

Page 90: Mobile app

Next, draw the numbers

Page 91: Mobile app

Draw the hints

Page 92: Mobile app

Draw the selection

Page 93: Mobile app

Multimedia

Page 94: Mobile app

Multimedia

Android provides support for encoding and decoding a varietyof common media types

Easy to integrate audio, video, and images into applications

Use the package: android.media

In particular, the MediaPlayer class

An object of this class can fetch, decode, and play both audioand video with minimal setup

Support several media sources:Local resourcesInternal URIsExternal URLs (streaming)

Page 95: Mobile app

Play audioPlay from a local raw resource (in res/raw)

MediaPlayer mp = MediaPlayer.create(context, R.raw.sound_file_1);mp.start();

Play from a URI, available locally in the system

Uri uri = ...; // initialize Uri hereMediaPlayer mp = new MediaPlayer();mp.setAudioStreamType(AudioManager.STREAM_MUSIC);mp.setDataSource(getApplicationContext(), uri);mp.prepare();mp.start();

Play from a remote URL via HTTP streaming

String url = ...; // your URL hereMediaPlayer mp = new MediaPlayer();mp.setAudioStreamType(AudioManager.STREAM_MUSIC);mp.setDataSource(url);mp.prepare(); // might take long! (for buffering, etc)mp.start();

Page 96: Mobile app

Asynchronous preparation

prepare() can take a long time, because it might involvefetching and decoding media data

So, never call it from UI thread

Instead, use the convenient method prepareAsync(). Itspawns another thread to prepare MediaPlayer and notify themain thread when done.

Use MediaPlayer.OnPreparedListener for thenotification

Page 97: Mobile app

MediaPlayer’s state diagram

Page 98: Mobile app

Releasing the MediaPlayer

A MediaPlayer can consume valuable system resources

So, call release() to release system resources allocated to it

For example, release it in Activity.onStop()

mp.release();mp = null;

Page 99: Mobile app

Using a Service with MediaPlayer

Use Service to play media in the background. So, It willcontinue playing even the user is interacting with otherapplications.

Use wake locks to guarantee that the service keeps playingeven if the phone is idle

The following will keep the CPU to remain wakemp = new MediaPlayer();mp.setWakeMode(getApplicationContext(),

PowerManager.PARTIAL_WAKE_LOCK);

Acquire WifiLock, if streaming media over the network:WifiLock wifiLock =

((WifiManager) getSystemService(Context.WIFI_SERVICE)).createWifiLock(WifiManager.WIFI_MODE_FULL, "mylock");

wifiLock.acquire();

To release:wifilock.release();

Page 100: Mobile app

Data Storage

Page 101: Mobile app

Data Storage

Android provides several options to save persistent applicationdata

Shared preferences: store private primitive data inkey-value pairsInternal storage: store private data on the device memoryExternal storage: store public data on the shared externalstorageSQLite database: store structured data in a privatedatabaseNetwork connection: store data on the web with your ownnetwork server

We will cover the first three today

Page 102: Mobile app

Using shared preferences

The SharedPreferences class provides a generalframework for saving and retrieving persistent key-value pairsof primitive data types

Use getSharedPreferences() to get an object

To write values:Call edit() to get a SharedPreferences.Editor

Adds values with methods such as putBoolean() andputString()

Commit the new values with commit()

To read values, use methods such as getBoolean() andgetString()

Page 103: Mobile app

Example of shared preferences

public class Calc extends Activity {public static final String PREFS_NAME = "MyPrefsFile";

@Overrideprotected void onCreate(Bundle state){super.onCreate(state);...

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);boolean silent = settings.getBoolean("silentMode", false);setSilent(silent);

}

@Overrideprotected void onStop(){super.onStop();

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);SharedPreferences.Editor editor = settings.edit();editor.putBoolean("silentMode", mSilentMode);

editor.commit();}

}

Page 104: Mobile app

Using the internal storage

You can save files directly on the device’s internal storage

By default, files saved to the internal storage are private to yourapplication

When the application is uninstalled, these files are removed.

To create and write a private file:Call openFileOutput() with the name of the file and theoperating modeWrite with write()

Close with stream with close()

To read a file:Call openFileInput() with the name of the file. Itreturns FileInputStreamRead bytes with read ()

Close with stream with close()

Page 105: Mobile app

Example of internal storageExample:

String FILENAME = "hello_file";String string = "hello world!";

FileOutputStream fos = openFileOutput(FILENAME,Context.MODE_PRIVATE);

fos.write(string.getBytes());fos.close();

Some useful methods:getFilesDir() – Gets the absolute path to the directorywhere internal files are savedgetDir() – Creates (or opens an existing) directorywithin your internal storage spacedeleteFile() – Deletes a file saved on the internalstoragefileList() – Returns an array of files currently saved byyour application

Page 106: Mobile app

Using the external storage

Every Android device supports a shared “external storage” thatyou can use to save files

This can be a removable storage media (such as an SD card)or an internal (non-removable) storage

Files saved to the external storage are world-readable and canbe modified by the user when they enable USB mass storage totransfer files on a computer

Page 107: Mobile app

Some useful methods

Before doing any work with external storage, callgetExternalStorageState() to check whether the mediais available

Use getExternalFilesDir() to open a directory. Thisdirectory is local to the app and will be deleted when the app isuninstalled.

Use getExternalStoragePublicDirectory() to open adirectory. This directory is shared and will NOT be deletedwhen the app is uninstalled.

In both cases, use e.g. DIRECTORY_MUSIC,DIRECTORY_RINGTONES, or DIRECTORY_PICTURES tospecify the type of subdirectory

Page 108: Mobile app

The Web

Page 109: Mobile app

The Web

In this chapter: connect your app to the web

Two simple approaches:Open an external web browser from your appEmbed a browser into your app

Also include:How to connect JavaScript and Android’s Java codeWeb services

Page 110: Mobile app

Browsing by Intent

The simplest thing you can do: open a browser from your app

All it takes are three lines of code!

private void openBrowser() {Uri uri = Uri.parse(urlText.getText().toString());Intent intent = new Intent(Intent.ACTION_VIEW, uri);startActivity(intent);

}

This codepauses your app, andstarts the Browser activity with its own view

Remember the app stack: when the Back key is pressed, thebrowser will go away, and your app will continue

Page 111: Mobile app

Web with a View

Android provides a wrapper around the WebKit browser enginecalled WebView

WebView works like any other view, except that it has a fewextra methods specific to the browser

private void openBrowser() {webView.getSettings().setJavaScriptEnabled(true);webView.loadUrl(urlText.getText().toString());

}

The loadUrl() method causes the browser engine to beginloading and display a web page. It does not wait for the loadingto finish and returns immediately.

To access the Internet, add this line toAndroidManifest.xml

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

Page 112: Mobile app

Some WebView’s useful methods

addJavascriptInterface(): Allows a Java object to beaccessed from JavaScript

createSnapshot(): Creates a screenshot of the currentpage

getSettings(): Returns a WebSettings object used tocontrol the settings

loadData(): Loads the given string data into the browser

loadDataWithBaseURL(): Loads the given data using abase URL

loadUrl(): Loads a web page from the given URL

Page 113: Mobile app

Some WebView’s useful methods (cont.)

setDownloadListener(): Registers callbacks for downloadevents, such as when the user downloads a .zip or .apk file

setWebChromeClient(): Registers callbacks for events thatneed to be done outside the WebView rectangle, such asupdating the title or progress bar or opening a JavaScript dialogbox

setWebViewClient(): Lets the application set hooks in thebrowser to intercept events such as resource loads, keypresses, and authorization requests

stopLoading(): Stops the current page from loading

Page 114: Mobile app

Calling JavaScript from Java

Use the WebView’s loadUrl() method, passing it a URL ofthe form javascript:code-to-execute

Example: define function callJS() in assets/index.html

<script language="JavaScript">function callJS(arg) {document.getElementById(’replaceme’).innerHTML = arg;

}</script>...<p id="replaceme"></p>

In Java, first load the index.html

webView.loadUrl("file:///android_asset/index.html");

The function callJS() can be called by

webView.loadUrl("javascript:callJS(’Hello from Android’)");

Page 115: Mobile app

Calling Java from JavaScript

Use the WebView’s addJavascriptInterface() method todefine objects that JavaScript code can access

Example: define a class to be exposed to JavaScript

private class AndroidBridge {public void callAndroid(final String arg) {handler.post(new Runnable() {public void run() {textView.setText(arg);

}});

}}

Then, register it to JavaScript

webView.addJavascriptInterface(new AndroidBridge(), "android");

Page 116: Mobile app

Calling Java from JavaScript (cont.)

For alerts or progress updates, use setWebChromeClient()

webView.setWebChromeClient(new WebChromeClient() {@Overridepublic boolean onJsAlert(final WebView view,

final String url, final String message, JsResult result) {Toast.makeText(LocalBrowser.this, message, 3000).show();result.confirm();return true; // I handled it

}});

Calls from JavaScript

<a href="#"onclick="window.alert(’Alert from JavaScript’)">Display JavaScript alert</a>

<a href="#"onclick="window.android.callAndroid(’Hello from Browser’)">Call Android from JavaScript</a>

Page 117: Mobile app

Using web services

Android fully supports java.net.HttpURLConnection formaking requests to a HTTP server

Example:

String q = URLEncoder.encode(original, "UTF-8" );URL url = new URL(

"http://ajax.googleapis.com/ajax/services/language/translate"+ "?v=1.0" + "&q=" + q + "&langpair=" + from+ "%7C" + to);

// Creates a connection and set parameterscon = (HttpURLConnection) url.openConnection();con.setReadTimeout(10000 /* milliseconds */);con.setConnectTimeout(15000 /* milliseconds */);con.setRequestMethod("GET" );con.addRequestProperty("Referer" ,

"http://www.pragprog.com/titles/eband3/hello-android" );con.setDoInput(true);

// Starts the querycon.connect();

Page 118: Mobile app

Using web services (cont.)

However, such calls must be made asynchronously to makesure that your app remains responsive

Trick: use the java.util.concurrent package

Use ExecutorService to manage threadsSubmit an instance of Runnable or CallableAn instance of the Future class is returned

A Future instance represents the as-yet-unknown future valuethat will be returned by your task (if any)

Page 119: Mobile app

An example: Google Translation API

Page 120: Mobile app

GPS

Page 121: Mobile app

GPS

The Global Positioning System (GPS) is a constellation of 27Earth-orbiting satellites (24 in operation + 3 extras)

The US military developed it as a military navigation system,later opened up for everybody

Each satellite circles the globe at about 19,300 km, making twocomplete rotations everyday

The orbits: at any time, anywhere on Earth, there are at leastfour satellites visible in the sky

GPS receivers locate at least four satellites, figure the distanceto each, and use this information to deduce its own location.

This operation is based on a simple math principle calledtrilateration

Page 122: Mobile app

2D Trilateration

To simplify explanations: let’s start with two-dimensionaltrilateration

Imagine that you are totally lost. You find a friendly local andask, “Where am I?”. He says, “You are 700 km from Bangkok”

You could be anywhere on a circle around Bangkok that has aradius of 700 km:

Bangkok

Page 123: Mobile app

Second circle

You ask somebody else, and she says, “You are 640 km fromKuala Lumpur”

Combining with the previous information, you know that youmust be at one of the two intersection points

Bangkok

KL

Page 124: Mobile app

Third circle

If a third person tells you that you are 1000 km from Yangon,you can eliminate one of the possibilities, and know exactlywhere you are (can you guess where?)

Bangkok

KL

Yangon

Page 125: Mobile app

3D Trilateration

Generalize the concept to 3D: spheres instead of circles

Imagine you are X miles from satellite A in the sky. You couldbe anywhere on the surface of an imaginary sphere with X-kmradius.

Page 126: Mobile app

Second sphere

If you also know you are Y miles from satellite B, you canoverlap the first sphere with this sphere

Two spheres overlap in a circle

Page 127: Mobile app

Third sphere

The third satellite will give a third sphere, which intersects thecircle at two points

Page 128: Mobile app

Fourth sphere

The Earth can act as a fourth sphere, i.e. only one of the twopossible points is on the surface of the planet

However, receivers generally look to four or more satellites toimprove accuracy and provide precise altitude information

Page 129: Mobile app

To make the calculation, GPS receiver needs to know twothings:

The location of at least three satellitesThe distance between you and each of the satellites

Idea: determine the time delays when signals travel fromsatellites to the receiver

For this to work, clocks on the satellites and the receiver mustbe synchronized to nanoseconds

Quite a few techniques involved. Anyway, details are beyondthe scope of this lecture

In this course: how to use GPS in your app!

Page 130: Mobile app

Finding locations

To gain access to location information, both from GPS andcoarse-grained location provider such as cell towertriangulation, add the following lines toAndroidManifest.xml

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

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

Get a LocationManager from your Context

LocationManager mgr= (LocationManager) getSystemService(LOCATION_SERVICE);

Select the best location provider. A Criteria object can beused to select a location provider based on e.g. power oraccuracy (in this case, no restrictions).

Criteria criteria = new Criteria();String best = mgr.getBestProvider(criteria, true);

Page 131: Mobile app

Finding locations (cont)

Query the last known (possibly outdated) location

Location location = mgr.getLastKnownLocation(best);

Edit onResume and onPause to have Android updateslocations only when your app is in the foreground (assume thatyour class implements LocationListener)

@Overrideprotected void onResume() {

super.onResume();mgr.requestLocationUpdates(best, 15000, 1, this);

}

@Overrideprotected void onPause() {

super.onPause();mgr.removeUpdates(this);

}

Page 132: Mobile app

Sensors

Page 133: Mobile app

Sensors

Android SDK supports many different types of sensor devicesTYPE_ACCELEROMETER: Measures acceleration in the x-,y-, and z-axesTYPE_LIGHT: Tells you how bright your surrounding areaisTYPE_MAGNETIC_FIELD: Returns magnetic attraction inthe x-, y-, and z-axesTYPE_ORIENTATION: Measures the yaw, pitch, and roll ofthe deviceTYPE_PRESSURE: Senses the current atmosphericpressureTYPE_PROXIMITY: Provides the distance between thesensor and some objectTYPE_TEMPERATURE: Measures the temperature of thesurrounding area

Page 134: Mobile app

SensorManager

Similar to LocationManager, here we use SensorManager

SensorManager mgr= (SensorManager) getSystemService(SENSOR_SERVICE)

Then, call registerListener() in onResume() andunregisterListener() in onPause() to start/stop gettingupdates

The sensor service will call onSensorChanged() every time avalue changes. It should look like this:

public void onSensorChanged(SensorEvent event) {for (int i = 0; i < event.values.length; i++) {// ...

}}

Page 135: Mobile app

Sensor readings

All sensors return an array of floating-point values. The size ofthe array depends on the particular sensor.

Turning sensor readings into meaningful information can bevery tricky

Do experiments on what you want!

Most of time it is not possible to test sensor readings on theemulator. If your application relies heavily on one of thesesensors, you will need to a real device to test

Page 136: Mobile app

SQLite

Page 137: Mobile app

SQLite

A tiny but powerful database engine, created by Dr. RichardHipp in 2000

Widely used, e.g. in Mozilla Firefox, Skype, PHP, Adobe AIR,Mac OS X, iPhone, and of course Android

Notable features:FreeSmall, less than 325KBRequire no setup, no server, no config file, noadministration

An SQLite database is just a file

Android stores it in /data/data/packagename/databases

Page 138: Mobile app

SQL refresher

A Data Definition Language (DDL) statement to create a table

create table mytable (_id integer primary key autoincrement,name text,phone text );

Note column types in SQLite are not strict. So, it’s possible toe.g. store a string in an integer column.

Insert a record

insert into mytable values(null, ’Steven King’ , ’555-1212’ );

Query for a record

select * from mytable where(_id=3);

Page 139: Mobile app

SQLiteOpenHelper

Subclass SQLiteOpenHelper to manage database creationand versionspublic class EventsData extends SQLiteOpenHelper {

private static final String DATABASE_NAME = "events.db";private static final int DATABASE_VERSION = 1;

public EventsData(Context ctx) {super(ctx, DATABASE_NAME, null, DATABASE_VERSION);

}

@Overridepublic void onCreate(SQLiteDatabase db) {db.execSQL("CREATE TABLE " + TABLE_NAME + " (" + _ID+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + TIME+ " INTEGER," + TITLE + " TEXT NOT NULL);" );

}

@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion,

int newVersion) {db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);onCreate(db);

}}

Page 140: Mobile app

Adding a row

Use getWritableDatabase() to get a read/write handle tothe events database, and then use insertOrThrow() to dothe actual INSERT

private void addEvents(String string) {SQLiteDatabase db = events.getWritableDatabase();ContentValues values = new ContentValues();values.put(TIME, System.currentTimeMillis());values.put(TITLE, string);db.insertOrThrow(TABLE_NAME, null, values);

}

Page 141: Mobile app

Running a query

Use getReadableDatabase() to get a read-only handle tothe events database, and then use query() to do the actualSELECT

private static String[] FROM = _ID, TIME, TITLE, ;private static String ORDER_BY = TIME + " DESC" ;private Cursor getEvents() {

SQLiteDatabase db = events.getReadableDatabase();Cursor cursor = db.query(TABLE_NAME, FROM, null, null, null,

null, ORDER_BY);startManagingCursor(cursor);return cursor;

}

The method startManagingCursor() tells the activity totake care of managing the cursor’s life cycle based on theactivity’s life cycle. E.g., deactivate the cursor when the activityis paused, or close it when the activity is terminated

Page 142: Mobile app

Display the query results

Use Cursor to iterate through all result rows

while (cursor.moveToNext()) {long id = cursor.getLong(0);long time = cursor.getLong(1);String title = cursor.getString(2);...

}

Alternatively, instead of using 0, 1, or 2 in getXXX(), usegetColumnIndexOrThrow() to get column index numbers

Page 143: Mobile app

Data binding

Android provides a convenient way to display query results:

Create a layout for items, call it e.g. item.xml

Subclass ListActivity and use SimpleCursorAdapter

private static int[] TO = { R.id.rowid, R.id.time, R.id.title };...SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,

R.layout.item, cursor, FROM, TO);setListAdapter(adapter);

Define your activity layout main.xml like this

<ListViewandroid:id="@android:id/list"... />

<TextViewandroid:id="@android:id/empty"... />

If the list has items, android:id/list will be displayed,otherwise android:id/empty will be displayed

Page 144: Mobile app

Content provider

Recall that one application cannot access data own by anotherapplication

A way to share data is to use ContentProvider:

Processes register themselves to the system as providers ofcertain kinds of data. When that information is requested, theyare called by Android through a fixed API to query or modify thecontent

Page 145: Mobile app

Content provider (cont)

Any piece of information managed by a ContentProvider isaddressed through a URI that looks like this:

content://authority/path/id

whereauthority is the name of the provider, usually the packagenamepath is a virtual directory within the providerid is the primary key of the requested record. Omit this torequest all records.

Android comes with several providers built in, includingcontent://browser

content://contacts

content://media

content://settings

Page 146: Mobile app

Using ContentProvider

Example of a valid URI:

public static final String AUTHORITY = "org.example.events" ;public static final Uri CONTENT_URI = Uri.parse("content://"+ AUTHORITY + "/" + TABLE_NAME);

Adding a row

getContentResolver().insert(CONTENT_URI, values);

Running a query

Cursor cursor = managedQuery(CONTENT_URI, FROM, null,null, ORDER_BY);

Page 147: Mobile app

Implement a ContentProvider

Refer to the lab!

Page 148: Mobile app

Services

Page 149: Mobile app

Services

A service is an application component that can performoperations in the background and does not provide a UI

Another application component can start a service. It willcontinue to run in the background, even if the user switches toanother application

Also, a component can bind to a service to interact with it andeven perform interprocess communication (IPC)

Examples: network transactions, play music, perform file I/O

Page 150: Mobile app

Types of services

A service can take two forms:

Started when an application component call startService()Once started, a service can run indefinitely, even if thecomponent is destroyedUsually perform a single operation, does not return a resultExample: download or upload file over the networkWhen the operation is done, it should stop itself

Bound when an application component call bindService()Offer a client-server interface that allows components tointeract with the service, send requests, get results, do IPCRun as long as another component is bound to itMultiple components can bind to the service at once

Page 151: Mobile app

Types of services (cont.)

A service can be of both types: it can be started to runindefinitely and also allow binding. Just implement bothonStartCommand() and onBind()

Just like an activity, a service started with an Intent

Caution: a service runs in the main thread of its hostingprocesses, it does not create its own thread and does not run ina separate process

Use a separate thread if your service can be slow

Page 152: Mobile app

The basics

To create a service, subclass Service and override thefollowing callback methods:

onStartCommand(): the system calls this method whenanother component call startService(). The servicewill run indefinitely unless stopSelf() orstopService() is calledonBind(): the system calls this method when anothercomponent call bindService(). You must alwaysimplement this method (simply return null if binding is notallowed)onCreate(): the system calls this method when theservice is first created. Use it to perform one-time setup.onDestroy(): the system calls this method when theservice is being destroyed. Use it to clean up resources.

Page 153: Mobile app

Declaring a service in the manifest

Add a <service> element as a child of the <application>element

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

</application></manifest>

android:name is the only required attribute

To make a service private, set android:exported="false"

Reference:http://developer.android.com/guide/topics/manifest/service-element.html

Page 154: Mobile app

IntentService

In most case, you can implement a service usingIntentService, a subclass of Service

It creates a worker thread to handle intents delivered toonStartCommand(), separate from your main thread

Provides to default implementation of onStartCommand() tosend one intent at a time to onHandleIntent()

Stops the service after all start requests have been handled, sono need to call stopSelf()

Provides default implementation of onBind() that returns null

All you need to do is implement onHandleIntent()

Page 155: Mobile app

References

API:http://developer.android.com/reference/android/app/

Service.html

Fundamentals:http://developer.android.com/guide/topics/fundamentals/

services.html

Page 156: Mobile app

A Very Brief Introduction to OpenGL

Page 157: Mobile app

3D with OpenGL

Android supports high performance 3D graphics with the OpenGraphics Library (OpenGL), specifically, the OpenGL ES API

OpenGL is a cross-platform graphics API that specifies astandard software interface for 3D graphics processinghardware

OpenGL ES is a subset of OpenGL, designed for embeddedsystems

OpenGL ES 1.0 and 1.1 have been supported sinceAndroid 1.1

Beginning with Android 2.2, OpenGL ES 2.0 is also supported

Page 158: Mobile app

GLSurfaceView

Two foundational classes:

GLSurfaceView: a View you can draw and manipulateobjects through API calls

GLSurfaceView.Renderer: an interface that definesmethods required for drawing graphics in GLSurfaceView.

You must implement this interface, and attach it toGLSurfaceView by using setRenderer().

Page 159: Mobile app

GLSurfaceView.Renderer

To implement the GLSurfaceView.Renderer interface, thefollowing methods must be implemented:

onSurfaceCreated(): The system calls this methodonce, when creating the GLSurfaceView. Use it to set upenvironment or initialize graphic objects.onDrawFrame(): The system calls this method on eachredraw of the GLSurfaceView. Use it to draw graphicobjects.onSurfaceChanged(): The system calls this methodwhen the GLSurfaceView geometry changes, e.g.screen orientation change

Page 160: Mobile app

Define a triangle

OpenGL allows you to define objects using coordinates inthree-dimensional space

By default, the coordinate (0,0,0) is the center of the screen,(1,1,0) is the top right, and (−1,−1,0) is the bottom left

private void initShapes() {float triangleCoords[] = { // X, Y, Z-0.5f, -0.25f, 0, 0.5f, -0.25f, 0, 0.0f, 0.559016994f, 0

};// initialize vertex Buffer for triangleByteBuffer vbb = ByteBuffer.allocateDirect(

// (# of coordinate values * 4 bytes per float)triangleCoords.length * 4);

vbb.order(ByteOrder.nativeOrder()); // use native byte ordertriangleVB = vbb.asFloatBuffer(); // create fp buffertriangleVB.put(triangleCoords); // add coords to fp buffertriangleVB.position(0); // set buffer to read 1st coord

}

Page 161: Mobile app

Projection

Problem: OpenGL assumes a square, uniform coordinatesystem. Androids monitors usually vary in size and shape.

Solution in OpenGL ES 1.0: create a projection matrix usingthe geometry of the device screen

public void onSurfaceChanged(GL10 gl, int width, int height) {gl.glViewport(0, 0, width, height);

// make adjustments for screen ratiofloat ratio = (float) width / height;

// set matrix to projection modegl.glMatrixMode(GL10.GL_PROJECTION);

// reset the matrix to its default stategl.glLoadIdentity();

// apply the projection matrixgl.glFrustumf(-ratio, ratio, -1, 1, 3, 7);

}

Page 162: Mobile app

Example: draw a rotating triangle

Page 163: Mobile app

Widgets

Page 164: Mobile app

App Widgets

Introduced in Android 1.5 (Cupcake)

App Widgets are miniature application views embedded inother applications (such as the Home screen) and receivedperiodic updates

These views are referred to as widgets

An application that is able to hold App Widgets is called an AppWidget host

Several App Widgets are shipped with Android, e.g. analogclock, music controller, picture frame

This section is about how to create your own widgets

Page 165: Mobile app

Create an App Widget

Create res/xml/widget.xml

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

xmlns:android="http://schemas.android.com/apk/res/android"android:minWidth="146dip"android:minHeight="72dip"android:updatePeriodMillis="1800000"android:initialLayout="@layout/main" />

to specify a minimum size of the widget, how often it should beupdated, and a reference to its starting layout

Create a BroadcastReceiver by subclassingAppWidgetProvider

public class Widget extends AppWidgetProvider {}

Page 166: Mobile app

Create an App Widget (cont.)

Declare the broadcast receiver inside <application> inAndroidManifest.xml

<receiver android:name=".Widget"android:label="@string/widget_name"><intent-filter><actionandroid:name="android.appwidget.action.APPWIDGET_UPDATE"

/></intent-filter><meta-data android:name="android.appwidget.provider"android:resource="@xml/widget" />

</receiver>

To run, select Run As > Android Application as usual

Widgets can be opened by pressing and holding your finger (ormouse) on the Home screen

Page 167: Mobile app

Example: HelloWidget

Page 168: Mobile app

Update your widget

Implement onUpdate() to handle APPWIDGET_UPDATEintent, the action we declared in AndroidManifest.xml

Example:

private SimpleDateFormat formatter = new SimpleDateFormat("EEEEEEEEE\nd MMM yyyy");

@Overridepublic void onUpdate(Context context,

AppWidgetManager appWidgetManager, int[] appWidgetIds) {String now = formatter.format(new Date());

RemoteViews updateViews = new RemoteViews(context.getPackageName(), R.layout.main);

updateViews.setTextViewText(R.id.text, now);appWidgetManager.updateAppWidget(appWidgetIds, updateViews);

super.onUpdate(context, appWidgetManager, appWidgetIds);}

Page 169: Mobile app

Explanations & tips

SimpleDateFormat is used to format the current date: day ofthe week, day of the month, month name, and year

RemoteViews is used for the new view layout that the widgetwill display

In this example, the same layout R.layout.main is used

The update frequency is controlled byandroid:updatePeriodMillis in res/xml/widget.xml.The value 1800000 is 30 minutes.

However, updates requested with updatePeriodMillis willnot be delivered more than once every 30 minutes

For more information, seehttp://developer.android.com/guide/topics/appwidgets/index.html

Page 170: Mobile app

Calendar widget

Page 171: Mobile app

Live wallpaper

Page 172: Mobile app

Live wallpaper

Introduced in Android 2.1

Live wallpapers are rich, animated, interactive backgrounds onhome screens

Similar to normal app, a live wallpaper has access to allfacilities of the platform: SGL, OpenGL, GPS, accelerometers,network access, etc

Page 173: Mobile app

Implementing a live wallpaper

Similar to implementing a service, with an additional methodonCreateEngine() to create WallpaperService.Engine

The engine is responsible for handling the lifecycle and drawingof a wallpaper

Drawing a wall paper can be expensive, so optimize your codeas much as possible

The Home application can send commands to theonCommands method of your live wallpaper:

android.wallpaper.tap: when the user taps an emptyspace on the workspaceandroid.home.drop: when the user drops an icon or awidget on the workspace

Page 174: Mobile app

References

Article:http://developer.android.com/resources/articles/

live-wallpapers.html

Samples:http://developer.android.com/resources/samples/

CubeLiveWallpaper/index.html


Recommended