Download 7.Java_applicationFundamentals_new

Document related concepts
no text concepts found
Transcript
JAVA Introduction
Application Fundamentals
Android Application Development
Workshop
1
Agenda
Classes, objects, and methods are the
basic components used in Java
programming.
 We have discuss:





How to
How to
How to
How to
classes
define a class
create objects
add data fields and methods to classes
access data fields and methods to
Android Application Development
2
Java Indroduction

Java is an object-oriented language, with
a syntax similar to C


Structured around objects and methods
A method is an action or something you do
with the object
Android Application Development Workshop
3
Classes

A class is a collection of fields (data) and
methods (procedure or function) that
operate on that data.
class classname
{
field declarations
{ initialization code
}
Constructors
Methods
}
Android Application Development
Circle
centre
radius
circumference()
area()
4
Classes

The basic syntax for a class definition:
class ClassName [extends SuperClassName]
{
[fields declaration]
[methods declaration]
}

Bare bone class – no fields, no methods
public class Circle
{
// my circle class
}
Android Application Development Workshop
5
Adding Fields:
Class Circle with fields

Add fields
public class Circle
{
public double x, y; // centre coordinate
public double r; // radius of the circle
}

The fields (data) are also called the
instance varaibles.
Android Application Development
6
Adding Methods
A class with only data fields has no life.
Objects created by such a class cannot
respond to any messages.
 Methods are declared inside the body of
the class but immediately after the
declaration of data fields.
 The general form of a method declaration
is:

type MethodName (parameter-list)
{
Method-body;
}
Android Application Development
7
Adding Methods to Class Circle
public class Circle {
public double x, y; // centre of the circle
public double r; // radius of circle
//Methods to return circumference and area
public double circumference() {
return 2*3.14*r;
}
public double area() {
return 3.14 * r * r;
}
}
Android Application Development
8
Data Abstraction

Declare the Circle class, have created a
new data type – Data Abstraction

Can define variables (objects) of that
type:
Circle aCircle;
Circle bCircle;
Android Application Development
9
Creating objects of a class
Objects are created dynamically using the
new keyword.
 aCircle and bCircle refer to Circle objects

aCircle = new Circle() ;
bCircle = new Circle() ;
Android Application Development
10
Accessing Object/Circle Data

Similar to C syntax for accessing data
defined in a structure.
ObjectName.VariableName
ObjectName.MethodName(parameter-list)
Circle aCircle = new Circle();
aCircle.x = 2.0 // initialize center and radius
aCircle.y = 2.0
aCircle.r = 1.0
Android Application Development
11
Executing Methods in
Object/Circle

Using Object Methods:
sent ‘message’ to aCircle
Circle aCircle = new Circle();
double area;
aCircle.r = 1.0;
area = aCircle.area();
Android Application Development
12
Using Circle Class
// Circle.java: Contains both Circle class and its user class
//Add Circle class code here
class MyMain
{
public static void main(String args[])
{
Circle aCircle; // creating reference
aCircle = new Circle(); // creating object
aCircle.x = 10; // assigning value to data field
aCircle.y = 20;
aCircle.r = 5;
double area = aCircle.area(); // invoking method
double circumf = aCircle.circumference();
System.out.println("Radius="+aCircle.r+" Area="+area);
System.out.println("Radius="+aCircle.r+" Circumference
="+circumf);
}
}
Output:
Radius=5.0 Area=78.5
Radius=5.0 Circumference =31.400000000000002
Android Application Development
13
Constructors

constructor: Initializes the state of new
objects.

has the same name as the class

can have any of the same access modifiers as class
members

similar to methods. A class can have multiple
constructors as long as they have different parameter
list. Constructors have NO return type.

Constructors with no arguments are called no-arg
constructors.
Android Application Development
14
Constructor example
class Body {
private long idNum;
private String name= “empty”;
private Body orbits;
private static long nextID = 0;
Body( ) {
idNum = nextID++;
}
Body(String bodyName, Body orbitsAround) {
this( );
name = bodyName;
orbits = orbitsAround;
}
}
Android Application Development
15
Usage of this

inside a constructor, you can use this to
invoke another constructor in the same
class. This is called explicit constructor
invocation. It MUST be the first statement
in the constructor body if exists.

this can also be used as a reference of
the current object. It CANNOT be used in
a static method
Android Application Development
16
Example: usage of this as a reference of the
current object
class Body {
private long idNum;
private String name;
private Body orbits;
private static long nextID = 0;
private static LinkedList bodyList = new LinkedList();
. . .
Body(String name, Body orbits) {
this.name = name;
this.orbits = orbits;
}
. . .
private void inQueue() {
bodyList.add(this);
}
. . .
}
Android Application Development
17
Inheritance





Reusability is achieved by INHERITANCE
Java classes Can be Reused by extending a class.
Extending an existing class is nothing but reusing
properties of the existing classes.
The class whose properties are extended is known
as super or base or parent class.
The class which extends the properties of super
class is known as sub or derived or child class
A class can either extends another class or can
implement an interface
Android Application Development
18
Inheritance

class B extends A { ….. }
A
<<class>>
B
<<class>>
A super class
B sub class
class B implements A { ….. }
A interface
B sub class
A
B
Android Application Development
<<class>>
<<class>>
19
interface implementation

A class can implement an interface, this
means that it provides implementations
for all the methods in the interface.

Java classes can implement any number
of interfaces (multiple interface
inheritance).
Android Application Development
20
Various Forms of Inheritance
Single Inheritance
A
B
Hierarchical Inheritance
A
B
X
A
MultiLevel Inheritance
A
A
B
B
C
C
B
X
C
A
B
C
NOT SUPPORTED BY JAVA
Multiple Inheritance
SUPPORTED BY JAVA
A
B
C
Android Application Development
A
B
C
21
Forms of Inheritance

Multiple Inheritance can be implemented
by implementing multiple interfaces not
by extending multiple classes
Example :
class Z extends A implements C , D
A
C
D
{ …………}
Z
OK
class Z extends A ,B
class Z extends A extends B
{
{
WRONG
}
OR
WRONG
}
Android Application Development
22
Abstract

Abstract modifier means that the class can
be used as a superclass only.


no objects of this class can be created.
can have attributes, even code



Class modifier
all are inherited
methods can be overridden
Used in inheritance hierarchies
Android Application Development
23
Interesting Method Modifiers


private/protected/public:
 protected means private to all but subclasses
 what if none of these specified?
abstract: no implementation given, must
be supplied by subclass.


the class itself must also be declared abstract
final: the method cannot be changed by a
subclass (no alternative implementation
can be provided by a subclass).
Android Application Development
24
Interesting Method Modifiers
•
•
native: the method is written in
some local code (C/C++) - the
implementation is not provided in
Java (recall assembler routines
linked with C)
synchronized: only one thread at a
time can call the method
Android Application Development
25
USE OF super KEYWORD
Can be used to call super class constrctor
super();
super(<parameter-list>);
 Can refer to super class instance
variables/Methods

super.<super class instance
variable/Method>
Android Application Development
26
class A
class B extends A
{
{
private int a;
private int b;
A( int a)
private double c;
{
B(int a,int b,double c)
this.a =a;
{
System.out.println("This is
super(a);
constructor of class A");
this.b=b;
}
this.c=c;
void print()
System.out.println("This is
{
constructor of class B");
System.out.println("a="+a);
}
}
void show()
void display()
{
{
print();
System.out.println("hello This is System.out.println("b="+b);
Display in A");
System.out.println("c="+c);
}
}
} // End of class A
} // End of class B
Android Application Development
27
Packages

Classes can be grouped in a collection called
package

Java’s standard library consists of hierarchical
packages, such as java.lang and java.util
http://java.sun.com/j2se/1.4.2/docs/api

Main reason to use package is to guarantee the
uniqueness of class names


classes with same names can be encapsulated in
different packages
tradition of package name: reverse of the company’s
Internet domain name
e.g. hostname.com -> com.hostname
Android Application Development
28
Class importation

Two ways of accessing PUBLIC classes of another
package
1)
explicitly give the full package name before the class
name.

E.g.
java.util.Date today = new java.util.Date( );
2)
import the package by using the import statement at
the top of your source files (but below package
statements). No need to give package name any more.

to import a single class from the java.util package
import java.util.Date;
Date today = new Date( );

to import all the public classes from the java.util package
import java.util.*;
Date today = new Date( );

* is used to import classes at the current package level. It
will NOT import classes in a sub-package.
Android Application Development
29
Naming conventions

Package names: start with lowercase letter




x, out, abs . . .
E.g.
PI . . .
Multi-word names: capitalize the first letter of each word after
the first one


E.g.
Constant names: all uppercase letters


E.g.
File, Math . . .
avoid name conflicts with packages
avoid name conflicts with standard keywords in java system
Variable, field and method names: start with lowercase letter


java.util, java.net, java.io . . .
Class names: start with uppercase letter


E.g.
E.g.
HelloWorldApp, getName . . .
Exception class names: (1) start with uppercase letter (2) end
with “Exception” with normal exception and “Error” with fatal
exception

E.g.
OutOfMemoryError, FileNotFoundException
Android Application Development
30
Example:Shapes

Shape:

color, layer fields

draw()
draw itself on the screen

calcArea()
calculates it's own area.

serialize()
generate a string that can
be saved and later used to
re-generate the object.
Android Application Development
31
Kinds of Shapes

Rectangle

Triangle

Circle
Each could be a kind of shape (could be
specializations of the shape class).
Each knows how to draw itself, etc.
Could write code to have all shapes draw
themselves, or save the whole collection to a
file.
Android Application Development
32
XML Introduction
Application Fundamentals
Android Application Development
Workshop
33
Overview
Data exchanges between your app and
some other application you might be
exchanging data in an open format like
Extensible Markup language or XML.
 It is a set of rules for encoding documents
in machine-readable form.
 sharing data on the internet.

Android Application Development
34
Overview
XML is plain text.
 XML represents data without defining how
the data should be displayed.
 XML can be transformed into other
formats via XSL.
 XML can be easily processed via standard
parsers. XML files are hierarchical.

Android Application Development
35
Overview
A XML document consists out of elements,
each element has a start tag, content and
an end tag.
 A XML document must have exactly one
root element,
 e.g. one tag which encloses the remaining
tags. XML differentiates between capital
and non-capital letters.

Android Application Development
36
Overview
The Java programming language provides
several standard libraries for processing
XML files.
 The SAX and the DOM XML parsers are
available on Android.
 Android it is recommended to use the
XmlPullParser.
 It has a relatively simple API compared to
SAX and DOM and is fast and requires less
memory then the DOM API.

Android Application Development
37
Android Introduction
Application Fundamentals
Android Application Development
Workshop
38
What is Android?
Android is a software package and Linux
based operating system for mobile devices
 Android is a software stack for mobile
devices that includes:

Operating System
Linux version 2.6
•Services include hardware drivers, power, process
and memory management; security and network.
•The Linux 2.6 kernel handles core system
services
Android Application Development
39
What is Android?


Middleware



Libraries (i.e. SQLite, OpenGL, WebKit, etc)
Android Runtime (Dalvik Virtual Machine and core
libraries)
Application Framework
 Abstraction for hardware access; manages application
resources and the UI; provides classes for developing
applications for Android

Applications


Native apps: Contacts, Phone, Browser, etc.
Third-party apps: developer’s applications.
Android Application Development
40
History
Andy Rubin has been credited as the father
of the Android platform -2003
 In Aug 17,2005 Google acquired Android
Inc. and later Handed to Open Handset
Alliances(OHA)
 OHA is consortium of 84 companies such as
google, samsung, AKM, Ebay, Intel,LG etc.
– established on 5th Nov 2007
 OHA is a business alliance comprised of
many of the largest and most successful
mobile companies on the planet.

Android Application Development
41
History
Google hosts the Android open source
project
 provides online Android documentation,
tools, forums, and the Software
Development Kit (SDK) for developers.
 Key employees of Android Inc. are Andy
Robin, Rich Miner, Nick Sear

Android Application Development
42
Version

2008






Google sponsors 1st Android Developer Challenge
T-Mobile G1 announced
SDK 1.0 released
Android released open source (Apache License)
Android Dev Phone 1 released
2009

SDK 1.5 (Cupcake)


SDK 1.6 (Donut)


New soft keyboard with “autocomplete” feature
Support Wide VGA
SDK 2.0/2.0.1/2.1 (Eclair)

Revamped UI, browser
Android Application Development
43

2010


Nexus One released to the public
SDK 2.2 (Froyo)


SDK 2.3 (Gingerbread)


Flash support, tethering
UI update, system-wide copy-paste
2011

SDK 3.0/3.1/3.2 (Honeycomb) for tablets only


New UI for tablets, support multi-core processors
SDK 4.0/4.0.1/4.0.2/4.0.3 (Ice Cream Sandwich)
 Changes to the UI, Voice input, NFC
Ice cream Sandwich
Android Application Development
Android 4.0+
44
Flavours of Android
Android Application Development
45
Overview
Linux Kernel: memory management,
process management, networking, and
other operating system services.
 Native Libraries: written in C or C++,
including: Surface Manager, 2D and 3D
graphics, Media codes, SQL database,
Browser engine, etc. only to be called by
higher level programs

Android Application Development
46
Overview
Android Runtime: including the Dalvik
virtual machine and the core Java
libraries. (not J2SE/J2ME)
 Application Framework: Activity manager,
Content providers, Resource manager,
Notification manager
 Applications and Widgets: the real
programs display information and interact
with users.

Android Application Development
47
Layers

Relying on Linux Kernel 2.6 for core system services





Power Management
Memory Management
Driver Model
Security
Linux Kernel provides an abstraction layer between
the H/W and
Android Application Development
48
Layers
•
•
•
•
Surface Manager – manages access to the
display subsystem
Media framework: allows the recording and
playback of different media formats
SQLite: database engine used for data storage
purposes
OpenGL: Used to render 2D or 3D graphics
content to the screen
Android Application Development
49
Layers
FreeType – bitmap and vector font
rendering
 WebKit - It is the browser engine used to
display HTML content.
 SGL – the underlying 2D graphics engine.
 SSL – stands for Secure Socket Layer
which
provides
security
for
communications over networks.
 libc – A standard C system library.

Android Application Development
50

Core Libraries
•
•
Providing most of the functionality available in
the core libraries of the Java language
APIs





Data Structures
Utilities
File Access
Network Access
Graphics
Android Application Development
51
Activity Manager

Each activity has a default
window

Most applications have
several activities that
start each other as
needed

Each is implemented as a
subclass of the base
Activity class
Window Manager

responsible for organizing
the screen
Content Providers
Enabling applications to
access data from other
applications or to share
their own data.
View
Resource Manager

The content of the window is
a view or a group of views 
Providing access to non(derived from View or
code
ViewGroup)
resources (localized strings,

Example of views: buttons, graphics, and layout files)
text fields, scroll bars, menu
items, check boxes, etc.
Location Manager

View(Group) made visible
via

obtains
the
device's
Activity.setContentView()
position.
method.

manages UI elements
Notification Manager
Package Manager

manages application
packages that are current
installed on the device.
Telephony Manager

handles making and
receiving phone calls.
Android Application Development

Enabling all applications
to
display customer
alerts in the status bar.
52
Architecture
CORE ANDROID + LIBRARIES
TCMD
CONNECTIVITY
HAL
Multimedia / Graphics
USB
BLUETOOTH
Wi-Fi
HAL
CONNECTIVITY
MODEM + RIL
GPS
KERNEL+BSP
MBM / Boot loader
Android Application Development
53
Life Cycle
Seven life cycle methods are defined in the
android.app.Activity class:
public class Activity
{
protected void onCreate(Bundle savedInstanceState);
protected void onStart();
protected void onRestart();
protected void onResume();
protected void onPause();
protected void onStop();
protected void onDestroy();
}
Android Application Development
54
DDMS
■
■
■
■
■
■
Task management
File management
Memory management
Emulator interaction
Logging
Screen captures
Android Application Development
55
Exploring the Android Application
Framework

The Android application framework is
provided in the android.jar file.
Android Application Development
56
Android Application Development
57
Android Manifest
It describes the application’s components
(activities, services, broadcast receivers,
and content providers) and their
capabilities in terms of the intents that
they can handle.
 It declares which permissions are required
in order to access protected parts of the
Android runtime and also interact with
other applications running on the system.

Android Application Development
58
Android Manifest



The Android manifest file presents essential
information about the application to the system
Check Android platform correctly run the
application's code and to grant the necessary
privileges during installation.
The Android manifest file provides the following
information to the system:
It includes the name, package name, and
the version number of the application.
 It indicates the minimum version of the
API required for running the application.

Android Application Development
59
Android Manifest

Its main purpose in life is to declare the components to the
system:
<?xml version="1.0" encoding="utf-8"?>
<manifest . . . >
<application . . . >
<activity
android:name="com.example.project.FreneticActivity"
android:icon="@drawable/small_pic.png"
android:label="@string/freneticLabel"
... >
</activity>
...
</application>
</manifest>
Android Application Development
60
Packaging
The Android Package File (APK) file format is used to package and
distribute Android applications.
 APK files are actually archive files in ZIP file format. They
partially follow the JAR file format, except for the way that the
application class files are packaged.
APK files contain the following:
 META-INF/MANIFEST.MF: This is the JAR manifest file for
the package file itself.
 META-INF/CERT.SF: This contains SHA1 hashes for the files
that are included in the package file. The file is signed by the
application developer’s certificate.
 META-INF/CERT.RSA: This is the public key of the
certificate that is used to sign the CERT.SF file.

Android Application Development
61
R file



The R file consists of a number of public static final
constants, each one referring to an XML resource. The
constants are grouped into interfaces according to XML
resource type.
final declaration is one that cannot be changed. Classes,
methods, fields, parameters,and local variables can all be
final.
Static -only one instance of that object (the object that is
declared static) in the class
Android Application Development
62
Android Application Development
63
Broadcast Receivers
Receive and react to broadcast
announcements
 Extend the class BroadcastReceiver
 Examples of broadcasts:



Low battery, power connected, shutdown,
timezone changed, etc.
Other applications can initiate broadcasts
Android Application Development
64
Intents


An intent is an Intent object with a message
content.
Activities, services and broadcast receivers are
started by intents. ContentProviders are started
by ContentResolvers:



An activity is started by Context.startActivity(Intent
intent) or Activity.startActivityForResult(Intent intent,
int RequestCode)
A service is started by Context.startService(Intent
service)
An application can initiate a broadcast by using an
Intent in any of Context.sendBroadcast(Intent intent),
Context.sendOrderedBroadcast(), and
Context.sendStickyBroadcast()
Android Application Development
65
Intent Filters

Declare Intents handled by the current application (in the
AndroidManifest):
<?xml version="1.0" encoding="utf-8"?>
Shows in the
<manifest . . . >
Launcher and
<application . . . >
<activity android:name="com.example.project.FreneticActivity"
is the main
android:icon="@drawable/small_pic.png"
activity to
android:label="@string/freneticLabel"
... >
start
<intent-filter . . . >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter . . . >
<action android:name="com.example.project.BOUNCE" />
<data android:mimeType="image/jpeg" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
...
Handles JPEG
</application>
</manifest>
images in
some way
Android Application Development
66
Android Market

http://www.android.com/market/
Has various categories, allows ratings
 Have both free/paid apps
 Featured apps on web and on phone
 The Android Market (and iTunes/App
Store) is great for developers



Level playing field, allowing third-party apps
Revenue sharing
Android Application Development
67
Publishing to Android Market

Requires Google Developer Account


$25 fee
Link to a Merchant Account



Google Checkout
Link to your checking account
Google takes 30% of app purchase price
Android Application Development
68
Android Application Development
69
Conclusion
Apps are written in Java
 Bundled by Android Asset Packaging Tool
 Every App runs its own Linux process
 Each process has it’s own Java Virtual
Machine
 Each App is assigned a unique Linux user
ID
 Apps can share the same user ID to see
each other’s files

Android Application Development
70
Android Application Development
71