Interaction Programming with Android

baroohspottyΚινητά – Ασύρματες Τεχνολογίες

19 Ιουλ 2012 (πριν από 5 χρόνια και 1 μήνα)

331 εμφανίσεις

DH2641
Android Interaction Programming
1
Interaction Programming with
Android
DH2641 Interaction programming
Interaction Programming concepts

Recap

Components

Layout

Events, Listeners

How are these concepts implemented in Android?

Android specifics

Multitouch
interaction

Program startup (Activity, Intent)

Development environment (SDK, Emulator, Virtual Device)
Useful resources
Android developers -

http://developer.android.com/
Open Handset Alliance -

http://www.openhandsetalliance.com/
Android Market -

http://www.android.com/market/
Bachelor theses at CSC:
- Peter Grundström:

Mobile Development for iPhone and Android
- Michael Lindblom &

Aked Hindi:

Dalvik Virtual Machine - Hjälper eller stjälper?
Sams Teach Yourself Android

Application Development in 24 Hours
http://proquestcombo.safaribooksonline.com/book/programming/android/9780768
696349?bookview=overview
Book: Hello, Android (Ed Burnette) -
http://www.pragprog.com/titles/eband/hello-android
About Android
Android Inc. bought by Google in 2005.
Continued development and launched November 15, 2007.
Currently maintained by Open Handset Alliance, which includes
a number of mobile operators, manufacturers, software
companies et.c.
Today most handset manufacturers
have at least one
Android phone.
Fundamentals
Java and open source
Each application runs in its own process, and

each process has
its own virtual machine (isolated from other apps).
Modified version of
Linux Kernel
, using Dalvik Virtual Machine
(not Java VM).

Optimized for memory and processor constraints on mobile devices

Multiple classes in one .
dex
file

One String pool per .
dex
file

Multiple
Dalvik VMs
can run at the same time efficiently
(with Native Development Kit, parts of applications can be
written in C or C++, but not whole applications.)
http://developer.android.com/guide/topics/fundamentals.html
Architecture
http://developer.android.com/guide/basics/what-is-android.html
DH2641
Android Interaction Programming
2
Application components
Not single point of entry, i.e. no main()
There are components the system can instantiate and run:
Activities
What is shown to the user, can be just one or several activities.
Implemented as subclass of
Activity
base class.
The visual content is provided by a hierarchy of views (
View
class), there are several pre-
configured views (e.g.

buttons, text fields, scroll bars).

This

is our concern in this lecture (i.e. Not the
whole of Android)
Services
Not visually shown, runs in background (e.g. music playing) and doesn't stop when switching to another
application.
Broadcast receivers
No user interface either, it simply receives and reacts to broadcast announcements (e.g. battery running
low) and can start activities or make notifications (e.g. flashing, vibration) using the
NotificationManager
.
Extends the
BroadcastReceiver
class.
Content providers
Makes a specific set of the application's data available to other applications.

Extends the
ContentProvider
class, but uses the
ContentResolver
to call it's methods.
Application components, cont.
Starting components: intents
Activities, services, and broadcast receivers are activated by
Intent
objects

Intents are an encapsulation of action and its data
Content providers

are activated by
ContentResolver
.
Shutting down components
Activities

via
finish()
or
finishActivity()
(when started by another activity).
Services

stopSelf
()
, or

Context.stopService()
.
Content providers

alive according to
ContentResolver
Broadcast receivers

alive when responding (no need to shut down)
Activity lifecycle
http://developer.android.com/guide/topics/fundamentals.html#lcycles
Activities can be:
- active (running)
- paused (remains its state,

but out of focus)
- stopped (not visible, state can be retained, can
be killed if memory is needed)
State transitions:
void onCreate(Bundle savedInstanceState)
void onStart()
void onRestart()
void onResume()
void onPause()
void onStop()
void onDestroy()
Save
dynamic
activity state:
Implement
onSaveInstanceState(Bundle)
called just after
onPause
()
And
onRestoreInstanceState
(Bundle)
called before

onResume
()
Save
persistent

activity state:
onPause
()
data that needs to survive between
different
runnings
of the application, or
between applications (
SQLite
)
User interface
The interface is built using
View
and
ViewGroup

objects,
hierarchically arranged.
The activity calls
setContentView()
with reference to root node.
Define your layout using an
XML layout file
.
Widgets
are used for interaction (e.g. buttons, date picker).



http://developer.android.com/reference/android/widget/package-summary.html
Define
event listeners
and register with the View, to capture
user interaction (e.g.

View.OnClickListener
,
View.OnKeyListener
).
http://developer.android.com/guide/topics/ui/index.html
Hello

Android

Make a graphical scene

In this case a simple
TextView

Install it in
onCreate
() via
setContentView
()

Don

t forget super.
onCreate
()

Same

goes for
onPause
() and
other lifecycle methods

To

log something, use the
Log class

Log.v(tag, message)

and the Log Cat

Eclipse view
(Window/Show
View/Other/Android/Log Cat)
src/com/example/helloandroid/HelloAndroid
.java
package com.example.helloandroid;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class HelloAndroid extends Activity {

/** Called when the activity is first





created. */

@Override

public void onCreate(Bundle





savedInstanceState) {





super.onCreate(savedInstanceState);





TextView tv = new TextView(this);





tv.setText("Hello Android!");





setContentView(
tv
);

}
}
Layout
1.
Use XML
Separate code from presentation.
Layout is external from code and
doesn't have to be recompiled.
Easier to create different layouts
(landscape/portrait, devices).
2.
Programmatically
Create Views and ViewGroups in
code
(You can use a mix of 1 and 2.)

Write the XML
One root node (
View

or

ViewGroup
)
Nested, hierarchical nodes of layout
objects and widgets

Save in res/layout

Load XML in
Activity.onCreate
using
setContentView(R.layout.
xmlfile
)

Use attributes to control behaviour
<?xml version="1.0" encoding="utf-8"?>
<TableLayout
attributes
>



<TableRow attributes>





<TextView
attributes
>







<TextView
attributes
>





<TextView
attributes
>



</TableRow>



<View attributes />



<TableRow attributes>





<TextView

attributes
>







<TextView

attributes
>





<TextView

attributes
>



</TableRow>
</TableLayout>
http://developer.android.com/guide/topics/ui/declaring-layout.html
DH2641
Android Interaction Programming
3
XML resources

res/layout/main
.xml
<?
xml

version
=
"1.0"

encoding
=
"utf-8"
?>
<
TextView
xmlns
:android
=
"http://schemas.android.
com/apk/res/android"

android:id
=
"@+
id/textview"

android:
layout_width
=
"fill_parent"

android:
layout_height
=
"fill_parent"

android:text
=
"
@string/hello
"
/>

res/values/string
.xml
<?
xml

version
=
"1.0"

encoding
=
"utf-8"
?>
<
resources
>

<
string

name
=
"hello"
>
Hello,
Android
! I am a string
resource!
</
string
>

<
string

name
=
"app_name"
>
Hello,
Android
</
string
>
</
resources
>
Using a resource layout

The graphical scene is
defined in

a layout XML
file

To access the layout, use
the R generated class

R was designed to be
easily accessible

for auto-
completion in
IDEs
package com.example.helloandroid;
import android.app.Activity;
import android.os.Bundle;
public class
HelloAndroid
extends Activity {

/** Called when the activity is first





created. */

@Override

public void onCreate(Bundle





savedInstanceState) {





super.onCreate(savedInstanceState);






setContentView
(
R.layout.main
);

}
}
Examples of layouts
Linear layout



One line of elements, either horizontal or vertical.
Relative layout



Arrange elements in relation to parent, sibling elements.
Table layout



Use rows, and e.g. text views to position text as in a table.
Grid layout



For instance to create grid of images.
Tab layout



Use tabs to switch between views or entire activities.
List view



Creates a scrollable list of items.
http://developer.android.com/resources/tutorials/views/index.html
Menus

Options menu
When pressing menu button

Context menu
When long-pressing a view

Submenu
Floating list of items when pressing menu item in options or
context menu
Define using XML, stored in res/menu
http://developer.android.com/guide/topics/ui/menus.html
Dialogs
Four
Dialog
objects:

AlertDialog
Can include 0-3 buttons, checkboxes, radio buttons.

ProgressDialog
Progress wheel or bar, which supports buttons.

DatePickerDialog

TimePickerDialog
http://developer.android.com/guide/topics/ui/dialogs.html
Style
Style is stored as XML in

res/values/.
Define the XML to format text:
<?xml version="1.0" encoding="utf-8"?>
<resources>



<style name="BigFont">







<item name="android:layout_width">fill_parent</item>







<item name="android:layout_height">wrap_content</item>







<item name="android:textSize">#20sp</item>





<item name="android:textColor">#FF0000</item>







<item name="android:typeface">sans</item>



</style>
</resources>
(For more info on e.g. text formating, see
http://developer.android.com/reference/android/widget/TextView.html
)
Apply the style:

To an individual View, using style attribute

To an entire activity, by adding android:theme in Android manifest
http://developer.android.com/guide/topics/ui/themes.html
BigFont
DH2641
Android Interaction Programming
4
Event subscription

http://developer.android.com/guide/topics/ui/ui-events.html

Conceptually similar to Swing but the

listener names

and their
interfaces are different

With
setOnXXXListener
you can only register one

listener (the
existing listener is lost)
TextView tv=

;
tv
.
setOnClickListener
(

new
View.
OnClickListener
(){
public

void

onClick
(View view) {
Log.
v
(
"click"
, view.
toString
());
}
});

If you do not instantiate a

view programmatically but via XML, you
can still find it and attach a listener
findViewById
(R.id.
textview
).
setOnClickListener
(

.);
Event types

Click

Long click (touch and hold)

Focus change

Key

Touch

Create context menu

Long click, Key and Touch event can be
consumed

by
returning true in their handler methods
Multitouch
interaction

(a) Tap, (b) drag, (c) pinch zoom

Multitouch
is detected via the Touch listener
public
boolean onTouch
(View v,
MotionEvent
event)

MotionEvent
.
getAction
() type of action

ACTION_DOWN first finger down

ACTION_POINTER_DOWN 2nd,

3rd

ACTION_MOVE move any
numbe
of fingers

ACTION_POINTER_UP

ACTION_UP last finger up

MotionEvent
.
getPointerCount
() returns the number of fingers

MotionEvent
.
getPointerId
(
int
) returns the pointer (finger)

getX
(),
getY
() all get an index argument to see where the
respective finger is
http://www.zdnet.com/blog/burnette/how-to-use-multi-touch-in-android-2/1747
Drawing graphics
Android supports both 2D and 3D graphics.
Depending on the level of animations and graphics in your app,
you should at once consider drawing:
1.
Into a View - for simple, static drawings which don't really
have to be updated (images, shapes, colors, pre-defined
animations, etc.).
2.
Onto the Canvas - for more advanced graphics and control

of the animation, e.g. video game.
http://developer.android.com/guide/topics/graphics/index.html
Hello World
Set up the environment and create a
first app.
Setting up the environment
1.
Make sure you have JDK
http://www.oracle.com/technetwork/java/javase/downloads/index.html
2.
IDE: Eclipse is preferred
E.g. Eclipse IDE for Java and Report Developers,
http://www.eclipse.org/downloads/
3.
Download SDK and add PATH
http://developer.android.com/sdk/index.html
4.
Install Android Development Tools (ADT) Plugin for Eclipse
http://developer.android.com/sdk/eclipse-adt.html
http://developer.android.com/sdk/eclipse-adt.html#installing
5.
Add Android platforms (and extras) under

Window/Android
SDK

http://developer.android.com/resources/tutorials/hello-world.html
6.
Create AVD (Android Virtual Device) for a platform
Quick instructions
http://developer.android.com/sdk/index.html
Detailed instructions
http://developer.android.com/sdk/installing.html
DH2641
Android Interaction Programming
5
What's in the SDK
Name
Description
add-ons/
Contains add-ons to the Android SDK development environment, which let you develop against external libraries that
are available on some devices.
docs/
A full set of documentation in HTML format, including the Developer's Guide, API Reference, and other information. To
read the documentation, load the file offline.html in a web browser.
platforms/
Contains a set of Android platform versions that you can develop applications against, each in a separate directory.



<
platform
>/
Platform version directory, for example "android-1.6". All platform version directories contain a similar set of files and
subdirectory structure.







data/
Storage area for default fonts and resource definitions.







images/
Storage area for default disk images, including the Android system image, the default userdata image, the default
ramdisk image, and more. The images are used in emulator sessions.







skins/
A set of emulator skins available for the platform version. Each skin is designed for a specific screen resolution.







templates/
Storage area for file templates used by the SDK development tools.







tools/
Any development tools that are specific to the platform version.







android.jar
The Android library used when compiling applications against this platform version.
samples/
Sample code and apps that are specific to platform version.
tools/
Contains the set of development and profiling tools available to you, such as the emulator, the android tool, adb, ddms,
and more.
SDK Readme.txt
A file that explains how to perform the initial setup of your SDK, including how to launch the Android SDK and AVD
Manager tool on all platforms
SDK Setup.exe
Windows SDK only. A shortcut that launches the Android SDK and AVD Manager tool, which you use to add
components to your SDK.
http://developer.android.com/sdk/installing.html
Create a new Android project in Eclipse
File > New > Project
Android > Android Project
Add name details (e.g. Hello World)



Project name: HelloAndroid



Application name: Hello, Android



Package name: com.example.helloandroid



Create Activity: HelloAndroid
Open helloworld.java



HelloWorld > src > com.example.
helloandroid



Existing code

New code
Run, select "Android Application"
(emulator may take a while to boot)
package com.example.helloandroid;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class HelloAndroid extends Activity {

/** Called when the activity is first





created. */

@Override

public void onCreate(Bundle





savedInstanceState) {





super.onCreate(savedInstanceState);





TextView tv = new TextView(this);





tv.setText("Hello Android!");





setContentView(
tv
);

}
}
http://developer.android.com/resources/tutorials/hello-world.html
Check out
developer.android.com
There is a lot of useful information, resources, examples et.c. to
found there.
For you interaction designers out there:
don't forget to take a look at the User Interface Guidelines!
http://developer.android.com/guide/practices/ui_guidelines/index.html