Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
Programim Mobile
Leksion
Tema: Programimi Mobile
në Java
Në këtë leksion....
Familja Java dhe J2ME
Konfigurimet CLDC dhe CDC, Paketat
Opsionale
Krijimi i aplikacioneve MIDP dhe CDC
Shembuj aplikacionesh
Hyrje në familjen Java
J2EE kryesisht shërben për ndërtimin e aplikacioneve
enterprise që e vënë theksin në zhvillimin e
aplikacioneve server-side dhe për web.
J2SE është e destinuar për ndërtimin e aplikacioneve
konvencionalë për kompjuterat desktop.
J2ME është nëngrup i J2SE që shërben për zhvillimin e
programeve për pajisjet e ndërfutura që nuk mund të
suportojnë implementim të plotë të J2SE.
Java Card ofron një mjedis për zhvillimin e
aplikacioneve që ekzekutohen në karta smart.
Për shembull do të ishte jo efiçente që në një makinë desktop të
përdorej J2EE e cila përfshin paketa për aplikacione enterprise.
Gjithashtu implementimi i plotë i J2SE nuk mund të suportohet nga
pajisjet e vogla që kanë më pak burime se një makinë desktop.
Platforma J2ME
J2ME është pjesë e familjes Java e ndërtuar me qëllim
që të shërbejë për ndërtimin e aplikacioneve që
ekzekutohen në mjedise që punojnë me bateri dhe jo me
energji elektrike.
Pajisjet me aftësi të ngjashme grupohen në konfigurime
dhe brenda secilit konfigurim krijohen profile për të
klasifikuar më tej llojin e pajisjes.
J2ME nuk është gjuhë e re por është një version i
përshtatur i Java për pajisjet e vogla duke hequr nga
J2SE ato pjesë që nuk mund të suportohen. Megjithatë
platforma J2ME mund të ekzekutohet në një larmi
pajisjesh si TV, PDA, libra elektronikë, telefona etj.
Për momentin në platformën
J2ME ekzistojnë dy konfigurime:
CLDC(Connected Limited Device Configuration), për
pajisje me
Ndërfaqe përdoruesi shumë të thjeshtë
Kujtesë të vogël (160Kb deri në 512 Kb)
Komunikim wireless
Procesor 16 ose 32 bit
Energji e kufizuar, zakonisht me bateri
Shembuj: telefonat celularë, librat elektronikë, PDA të
thjeshta etj. Këtyre pajisjeve do i referohemi si pajisje më
pak të afta.
CDC(Connected Device
Configuration), për pajisje me
Ndërfaqe
përdoruesi më të
larmishme
Kujtesë nga 2 – 16 M.
Lidhje me disa tipe rrjetash.
Procesorë 16 ose 32 bit.
Shembuj: Tv, PDA etj.
Këtyre pajisjeve do i
referohemi si pajisje më
shumë të afta.
Pajisjet më pak të afta:
Konfigurimi CLDC
Për momentin ekzistojnë dy versione CLDC:
CLDC 1.0 i cili është lëshimi i parë i specifikimit CLDC.
CLDC 1.1 i cili është version i përmirësuar i 1.0.
CLDC ofron një mjedis ekzekutimi Java (JRE) bazë, por
grupi i klasave bazë zakonisht është i vogël dhe ka
nevojë që të përmirësohet nga klasa shtesë. Në fakt
CLDC nuk ka ndonjë API të integruar për menaxhimin e
ndërfaqes me përdoruesin, nuk implementon ndonjë
model I/O dhe ka mangësi në arritjen e sigurisë.
MIDP (Mobile Information
Device Profile)
Profili MIDP i shtohet konfigurimit CLDC për të mbushur
funksionalitetet që mungojnë. MIDP në fakt është një
grup API-sh dhe librarish që ofrojnë funksionalitete si
ndërfaqe përdoruesi, lidhje në rrjet, ruajtje të dhënash
etj. Aktualisht ekzistojnë dy versione MIDP të cilët
implementohen në pajisje reale:
MIDP 1.0 është lëshimi i parë i profilit dhe përfshin
ndërfaqe përdoruesi (nivel jo i avancuar) e siguri në rrjet.
MIDP 2.0 ka përshtatshmëri kthimi me MIDP 1.0 dhe ka
funksione shtesë si ndërfaqe më të avancuar.
Multimedia, lojëra etj.
Aktualisht është specifikuar edhe gjenerata e tretë e
MIDP me emrin JSR271.
Ky specifikim bazohet në MIDP 2.0 dhe ka
përshtatshmëri kthimi me të. Një aplikacion që zhvillohet
sipas profilit MIDP quhet MIDlet.
Këto lloj aplikacionesh nuk përdorin një metodë statike
main për pikë hyrëse sikurse ndodh në aplikacionet
tradicionalë desktop.
Pika hyrëse e një aplikacioni MIDlet është një klasë që
trashëgon nga java.microedition.midlet.MIDlet. Klasa
MIDlet ka të përcaktuara disa metoda abstrakte që
thirren kur gjendja e MIDlet-it ndryshon.
Metoda
Përshkrimi
startApp()
Thirret nga AMS kur MIDlet fillon të ekzekutohet nga e para ose kur rimëkëmbet nga
një gjendje e pezulluar.
destroyApp()
Thirret nga AMS kur MIDlet përfundon.
pauseApp()
Thirret nga AMS kur MIDlet pezullohet
notifyDestroyed()
Thirret nga MIDlet. I kërkon AMS që ta shkatërrojë vetë MIDlet-in.
notifyPaused()
Thirret nga MIDlet. I kërkon AMS që ta pezullojë vetë MIDlet-in.
resumeRequest()
Thirret nga MIDlet-i i pezulluar(p.sh nga një thred në background). I tregon AMS se
MIDlet-i do të dalë nga gjendja e pezulluar dhe të bëhet sërish aktiv.
Tabelë 1- Metodat e ciklit jetësor të MIDlet
Një ose më shumë MIDlet-e së bashku me të gjithë skedarët dhe klasat
e tjera që i duhen aplikacionit paketohen në një suitë MIDlet. Një suitë
MIDlet përbëhet nga një skedar JAR dhe një skedar JAD. Skedari JAR
është skedari që duhet të dërgohet në telefon për të instaluar
aplikacionin. CDC është plotësisht i përshtatshëm me CLDC.
Suporti për rrjetat
J2ME ofron ndërfaqe rrjeti
për zhvillimin e aplikacioneve
wireless dhe shfrytëzon
aftësitë e këtyre pajisjeve për
tu lidhur në rrjet sipas
teknologjive të ndryshme të
rrjetit wireless. Suporti për
lidhjen e pajisjeve në rrjet
kryhet nga GCF hierarkia e
së cilës tregohet në Figurë
Qëllimi kryesor i GCF është që të përcaktojë një
arkitekturë rrjeti sa më të përgjithshme dhe të lejojë
akses për tiparet që lidhen me protokollet. GCF i ofron
përdoruesit një grup të vetëm abstragimesh për të
menaxhuar disa protokolle. GCF përdoret edhe nga
CLDC edhe nga CDC por ka disa ndryshime në
protokollet që suportojnë. Disa nga llojet e lidhjeve që
mund të krijohen janë HttpConnection,
UDPDatagramConnection, SipConnection.
Protocol:Protokolli që do të përdoret për lidhjen. Protokolli përdoret
nga GCF për të gjetur klasën e saktë që do të përdoret.
Address:Adresa në rrjet e pikës fundore të lidhjes. Klasat
Connection që suportojnë funksionalitete server të lejojnë të
specifikosh vetëm portën e lidhjes, p.sh socket://:80 krijon një lidhje
socket në server në portën 80 të localhost.
Parameters:Në lidhje mund të përcaktohen në mënyrë opsionale
disa parametra ekstra. P.sh lidhja SipConnection të lejon të shtosh
parametra transporti. Parametrat gjithmonë specifikohen si listë me
çifte name = value të cilët ndahen nga njëri-tjetri me pikëpresje.
P.sh:
SipConnection sc = ( SipConnection )Connector.open
(“sip:+475551234567; postd = pp22@foo.com; user=phone“);
Teknologjia e standardizimit
në Java
E gjithë teknologjia Java kalon përmes procesit JCP
(Java Community Process.Procesi mbikëqyret nga
EC(Executive Committee). Ekzistojnë dy komitete
ekzekutive: një për J2SE dhe J2EE, dhe një për
J2ME. Është detyrë e EC që të mbledhë, zhvillojë
dhe të aprovojë JSR(Java Specification Request).
Rezultati i këtij procesi përbëhet nga tre artefakte:
Specifikimi: Është API përfundimtare, përmban
klasat dhe manualin që i shpjegon përdoruesit se si
ta përdorë këtë teknologji.
TCK(Test Compatibility Kit): Përfshin testet që
duhet të kalojë një specifikimin.
RI(Reference Implementation): Është implementim
i specifikimit i cili i lejon përdoruesit që të fillojnë të
punojnë me të.
Mobile Service Architecture
MSA u finalizua në Dhjetor
2006 si zhvillim i JTWI. Në këtë
specifikim janë shtuar shumë
më tepër paketa opsionale, siç
tregohet në Figurën 6. Përveç
MSA dhe MSA Subset ekziston
gjithashtu MSA Advanced
Specifikation. Si konfigurim për
MSA mund të përdoret edhe
CDC. Pajisjet mobile mund të
suportojnë të gjithë MSA ose
vetëm një pjesë të teknologjive
të përfshira në të.
Mjedisi zhvillues
Për të programuar në NetBeans me J2ME është e nevojshme që
paraprakisht në kompjuter të jenë të instaluar:
Java SE Development Kit (JDK) 5.0.6 e tutje.
NetBeans IDE
NetBeans Mobility Pack për CLDC dhe/ose CDC.
Paketat duhet të instalohen sipas radhës së mësipërme. Gjithashtu
ekziston një opsion për shkarkimin e NetBeans IDE së bashku me
JDK-në.
Shtimi i një librarie të re në
Netbeans
Mobile information devices
20
most people probably think of portable devices as intelligent phones
or personal digital assistants (PDAs), the distinction is arbitrary.
For the purposes of this course we will use the term MID to include
any handheld device which has some form of micro-processor in it
and which can have new applications loaded onto it.
Lecture 1 Introduction
Programming
Handheld and Mobile
devices
Shembull: Krijimi i një
aplikacioni MIDlet
Dy hapat e tjerë kanë të bëjnë me konffigurimin e pajisjes emulator për
sa i përket tipit dhe pam jes së saj. Më pas paketën <default package>
të projektit mund të shtohen MIDlet-e. Më poshtë tregohet kodi burim i
një MIDlet-i të thjeshtë dhe pamja se si duket në emulator.
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
public class HelloWorld extends MIDlet {
Display display ;
Form form ;
public void startApp() {
display = Display.getDisplay(this); form =
new Form("Helloworld example");
form.append("Hello World!");
display.setCurrent(form);
}
public void pauseApp() {}
public void destroyApp(boolean
unconditional) { notifyDestroyed( );
}}
Hedhja e MIDlet-it në telefon
Pasi projekti kompilohet, NetBeans krijon Suitën MIDlet
për projektin e cila gjendet në folderin HelloWorld/dist.
Në polder gjenden dy skedarë HelloWorld.jad dhe
Helloworld.jar. Skedari i dytë është arkivi që ka të gjithë
skedarët që i duhen aplikacionit që të punojë.
Rrjedhimisht për të instaluar MIDlet-in në telefon ky arkiv
duhet të transferohet fillimisht në telefon. Në disa raste
të veçantë duhet të transferohet edhe skedari .jad. Pasi
dërgohet skedari në telefon, fillohet instalimi duke hapur
këtë skedar.
Mobile information devices
The emergence of genuinely portable devices which
contain sufficient computing power to support a range of
applications, many of which were originally developed for
conventional personal computers, is one of the major
changes in the world of technology in recent years.
It has accompanied the emergence of very widespread
adoption of mobile phones and these technologies are
now merging, creating mobile information devices (MIDs)
with the ability to connect with each other and with
conventional computer networks
25
Operating environments
Palm OS
J2ME
Other Java environments
.Net Compact
Symbian
Linux
26
Languages
27
C/C++
Palm OS
Symbian
.NET
Linux
Java
J2ME
Other Java environments
C#
.NET
Visual Basic
.NET
Python scripting
Some mobile phones
Mobile scripting languages
Many mobile phones
Lecture 1 Introduction
Programming
Handheld and Mobile
devices
Issues to bear in mind
Screen Size
Most
Palm Powered handheld screens are
only 160x160 pixels, so the amount of
information you can display at one time is
limited.
Quick Turnaround Expected
On
28
a PC, users don’t mind waiting a few
seconds while an application loads because
they plan to use the application for an Programming
Handheld and Mobile
extended amount
of1 Introduction
time. By contrast, the devices
Lecture
More issues to bear in mind
29
PC Connectivity
PC connectivity is an integral component of the Palm Powered
handheld. The handheld comes with a cradle that connects to a
desktop PC and with software for the PC that provides “one
button” backup and synchronization of all data on the handheld
with the user’s PC.
Input Methods
Most users of Palm Powered handhelds don’t have a keyboard
or mouse. Users enter data into the handheld using a pen. They
can either write characters in the input area or use the keyboard
dialog provided on the handheld.
Lecture 1 Introduction
Programming
Handheld and Mobile
devices
More issues to bear in mind
Power
Handhelds run on batteries and thus do not have the same
processing power as a desktop PC. The handheld is intended as
a satellite viewer for corresponding desktop applications. If your
application needs to perform a computationally intensive task,
you should implement that task in the desktop application
instead of the handheld application.
Memory
Palm Powered handhelds have limited heap space and storage
space. Different versions of the handheld have between 512K
and 8MB total of dynamic memory and storage available. The
handheld does not have a disk drive or PCMCIA support.
Programming
30
Lecture 1 Introduction
Handheld and Mobile
devices
More issues to bear in mind
File System
Because
of the limited storage space, and to
make synchronization with the desktop
computer more efficient, Palm OS does not
use a traditional file system. You store data in
memory chunks called records, which are
grouped into databases.
Backward Compatibility
Different
31
versions of Palm Powered
handhelds are available, and each runsProgramming
a
Handheld and Mobile
different versionLecture
of Palm
OS.
Users
are notdevices
1 Introduction
Binary executable files on the device.
Can access all API’s made available by OS vendor.
SDK’s are platform-specific.
Each mobile OS comes with its own unique tools and
GUI toolkit.
Different tools, languages and distribution channels associated with leading mobile operating
systems
* IBM, Native, web or hybrid mobile app development, 2012. IBM Software Thought Leadership White
Paper
PROS
Easy low-level hardware
access services.
Easy access to high level
services important to
personal mobile experience.
Full use of all functionalities
that modern mobile devices
have to offer.
CONS
Code Reusability : Low
Development &
maintenance: Timeconsuming & expensive.
Designers are required to be
familiar with different UI
components of each OS.
Upgrade flexibility: Low.
High usability.
Separates build environment from target environment.
Platform-independent API using a mainstream programming language like
JavaScript, Ruby or Java.
The cross-compiler then transforms the code into platform-specific native
apps.
The software artifact generated can be deployed and executed natively on the
device.
ADVANTAGES:
Improved performance and User Experience.
Full access to functionalities of underlying mobile OS and device specific
capabilities.
DISADVANTAGES:
Highly complex as cross-compilers are difficult to program.
Need to be kept consistent with fragmented mobile platforms and operating
systems available.
A virtual machine is used to abstract the target platform details from the
application’s running code.
The framework provides both the API and runtime environment.
The runtime executes on the mobile device and enables interoperability
between the device’s OS and the mobile application.
ADVANTAGES:
Improved performance and User Experience.
Full access to functionalities of underlying mobile OS and device specific
capabilities.
Portability: VM’s are easier to maintain & more flexible to extend.
DISADVANTAGES:
Slower due to runtime interpretation latency.
Use standard web technologies such as HTML 5, CSS 3 & JavaScript.
Features of HTML 5 - Advanced UI components, access to rich media types,
geolocation services & offline availability.
Increasing popularity of HTML 5 in rendering engines such as WebKit.
Runs on a standalone mobile web browser.
Installed shortcut, launched like a native app.
UI logic resides locally; makes the app responsive and accessible offline.
ADVANTAGES:
Multiplatform support.
Low development cost.
Leverage existing knowledge.
DISADVANTAGES:
Limited access to OS API’s.
Combines native development with web technology.
The web app runs inside a thin wrapper native app.
The wrapper native app uses the OS API’s to create an embedded HTML
rendering engine which provides a bridge between the browser and device
API’s.
The communication between web app and native app normally happens over
JavaScript via custom built API’s.
ADVANTAGES:
Flexibility of web apps combined with feature richness of native apps.
Simplified deployment and immediate availability.
Leverage existing knowledge.
DISADVANTAGES:
Poorer user experience as compared to native apps.
Access to advanced device capabilities normally restricted.
CONS
PROS
Code Reusability
Plugins
Easy for web developers
Might not support every
feature of OS
Cannot use own tools/IDE
Slower.
Reduced development costs
Support for enterprise &
cloud services
Easy Deployment
High end graphics & 3D
support limited
Vendor lock-in
* http://setandbma.files.wordpress.com/2011/12/wora-platforms.png
TECHNICAL ARCHITECTURE:
Cross compilation using Virtual Machine.
Single source codebase written in Ruby and UI constructed using HTML 5,
CSS 3, JavaScript running on Ruby interpreter on the device.
Support for SQLite enables the local storage of relational data, enabling offline
capabilities for both hybrid and native HTML 5 applications.
DESIGN PATTERNS:
Model-View-Controller pattern for maintainability and best practices.
Object Relational Mapper design for easy data manipulation.
SUPPORTED PLATFORMS:
WM /WEHH , WinCE5.0+, Android 2.1+, iOS 3.0+, BB 4.6+, WP7
*http://leckylao.files.wordpress.com/2010/06/screen-shot-2010-06-12-at-3-28-30pm.png
HTML 5 FEATURES:
App Caching, WebSockets, WebWorkers, Local & Session Storage, SQLite,
Semantic Elements, Form Attributes
IDE USED:
RhoStudio – An Eclipse based IDE
STRENGTHS:
Design patterns used.
Applications look and behave identically on all devices.
WEAKNESSES:
Updating HTML/JavaScript code needs a complete rebuild.
Need to know Ruby well, which is not as popular as other programming
languages.
Doesn’t generate source code, only native package which can restrict any
further tweaking of the app.
* http://floatlearning.com/2011/07/which-cross-platform-framework-is-right-for-me/
TECHNICAL ARCHITECTURE:
Web approach using hybrid model.
Single source codebase written HTML 5, CSS 3, JavaScript running on a mobile
browser embedded in a native app wrapper.
Device capabilities accessed through device-independent JavaScript API.
SUPPORTED PLATFORMS:
iOS, Android, Blackberry, WP7, Symbian, Palm, Samsung Bada
IDE USED:
MAC OS X & XCODE for iPhone & iPad.
Google Android SDK, Eclipse ADT Plugin, Ant as well as Eclipse IDE for
Android.
ARCHITECT
URE:
* http://arnab.ch/images/phonegap-architecture.jpg
STRENGTHS:
Native wrapper source code is provided so it can be customized further.
Simple ‘drop-in libraries’ concept makes it easier to develop.
Lowers barriers of adoption for web developers.
WEAKNESSES:
Lack of support for native UI components, design patterns & development
tools.
The capabilities offered by the framework is limited to what a “WebView” can
do.
Different projects for different platforms
Different JavaScript files on each platform for PhoneGap itself and plugins
No native UI support
Java, Objective-C or C# requirement to create new plugins
No built-in support for push notifications
* http://floatlearning.com/2011/07/which-cross-platform-framework-is-right-for-me/
TECHNICAL ARCHITECTURE:
Cross compilation technique – Pre-compilation, front-end compilation, platform
& package compilation.
Single source codebase written in JavaScript, compiled into native code and
packaged for different target platforms.
Does not use browser engine to render user interface on mobile devices.
Instead the UI elements are converted to true native UI elements when
deployed to the phone.
SUPPORTED PLATFORMS:
iOS, Android, Windows & Blackberry
IDE USED:
Studio, an Eclipse-based IDE
* http://www.linux-mag.com/s/i/articles/7719/architecture1.png
STRENGTHS:
Native code output very quick and fluid on the phone.
Easy setup and startup for developers.
Excellent documentation & examples.
Strong community forum to find out answers.
Intuitive app management environment.
Support for desktop and tablet development
WEAKNESSES:
Potentially restrictive API’s
Tries to solve too many problems in one shot supporting phones, tablets &
desktops.
* http://floatlearning.com/2011/07/which-cross-platform-framework-is-right-for-me/
TECHNICAL ARCHITECTURE:
Cross compilation using Virtual Machine.
Single source codebase written in C/C++ or HTML/JavaScript or a combination
of both.
C++ source code platform-independent intermediate code application
package
SUPPORTED PLATFORMS:
iOS, Android, Windows Mobile, Moblin/MeeGo, Symbian & Blackberry
IDE USED:
MoSync IDE based on Eclipse.
http://www.straightforward.se/storyserver/sites/straightforward.se.storyserver/files/im
ages/MoSyncAppArchitecture.preview.png
STRENGTHS:
Only one project structure for all the platforms.
The same JavaScript file.
Extend JavaScript functionality using C++ or Java and Objective-C
Native UI support
Built-in support for push notifications
Target group: Both web developers looking to enter the mobile space, as well
as the ordinary PC/Mac desktop developer with knowledge of C/C++.
WEAKNESSES:
No support for accelerometer or camera in most phones.
Contains XML parsing libraries but lacking support for JSON or other data
formats.
Doesn’t provide support for MVC; requires little extra effort to create views for
data.
* http://floatlearning.com/2011/07/which-cross-platform-framework-is-right-for-me/
Below is a summary of each platform and whether it offers adequate support
for a given area. (Scored 2 or better in that criteria)
* http://floatlearning.com/2011/07/which-cross-platform-framework-is-right-for-me/
Tools
Phone
Eclipse ( http://www.eclipse.org/downloads/ )
Android
Plugin (ADT)
Android SDK ( http://developer.android.com/sdk/index.html
)
Install
everything except Additional SDK
Platforms, unless you want to
Windows Users: may need to install
Motorola Driver directly (
http://www.motorola.com/Support/US-EN/Support-
Android SDK
Once installed open the SDK Manager
Install the desired packages
Create an Android Virtual Device (AVD)
SDK Manager
AVD
ADT Plugin (1)
In Eclipse, go to Help -> Install New Software
Click ‘Add’ in top right
Enter:
Name: ADT Plugin
Location: https://dl-ssl.google.com/android/eclipse/
Click OK, then select ‘Developer Tools’, click Next
Click Next and then Finish
Afterwards, restart Eclipse
Specify SDK location (next 3 slides)
Must do this every time start a new project in a new
location (at least in Windows)
ADT Plugin (2)
ADT Plugin (3)
ADT Plugin (4)
Creating a Project (1)
Creating a Project (2)
Need
the
items
circled
Then
click
Finish
Project Components
src – your source code
gen – auto-generated code (usually just
R.java)
Included libraries
Resources
Drawables
(like .png images)
Layouts
Values
(like strings)
Manifest file
XML
Used to define some of the resources
Layouts
(UI)
Strings
Manifest file
Shouldn’t usually have to edit it directly,
Eclipse can do that for you
Preferred way of creating UIs
Separates
the description of the layout from
any actual code that controls it
Can easily take a UI from one platform to
R Class
Auto-generated: you shouldn’t edit it
Contains IDs of the project resources
Enforces good software engineering
Use findViewById and Resources object to
get access to the resources
Ex.
Button b =
(Button)findViewById(R.id.button1)
Ex. getResources().getString(R.string.hello));
Layouts (1)
Eclipse has a great UI creator
Generates
the XML for you
Composed of View objects
Can be specified for portrait and
landscape mode
Use
same file name, so can make completely
different UIs for the orientations without
modifying any code
Layouts (2)
Layouts (3)
Click ‘Create’ to make layout modifications
When in portrait mode can select ‘Portrait’ to make a
res sub folder for portrait layouts
Likewise for Landscape layouts while in landscape mode
Will create folders titled ‘layout-port’ and ‘layout-land’
Note: these ‘port’ and ‘land’ folders are examples of
‘alternate layouts’, see here for more info
http://developer.android.com/guide/topics/resources/providing-resources.html
Avoid errors by making sure components have the
same id in both orientations, and that you’ve tested
each orientation thoroughly
Layouts (4)
Strings
In res/values
strings.xml
Application wide available strings
Promotes good software engineering
UI components made in the UI editor
should have text defined in strings.xml
Strings are just one kind of ‘Value’ there
are many others
Manifest File (1)
Contains characteristics about your application
When have more than one Activity in app, NEED to
specify it in manifest file
Go to graphical view of the manifest file
Add an Activity in the bottom right
Browse for the name of the activity
Need to specify Services and other components too
Also important to define permissions and external
libraries, like Google Maps API
Manifest File (2) – Adding an
Activity
Android Programming
Components
Activity
http://developer.android.com/guide/topics/fundamentals/activities.html
Service
http://developer.android.com/guide/topics/fundamentals/services.html
Content Providers
Broadcast Receivers
Android in a nutshell:
http://developer.android.com/guide/topics/fundamentals.html
Activities (1)
The basis of android applications
A single Activity defines a single viewable
screen
the
actions, not the layout
Can have multiple per application
Each is a separate entity
They have a structured life cycle
Different
events in their life happen either via
the user touching buttons or programmatically
Activities (2)
Services (1)
Run in the background
Can continue even if Activity that started it dies
Should be used if something needs to be done while the user is not
interacting with application
Should create a new thread in the service to do work in, since the
service runs in the main thread
Can be bound to an application
In which case will terminate when all applications bound to it unbind
Allows multiple applications to communicate with it via a common
interface
Needs to be declared in manifest file
Like Activities, has a structured life cycle
Otherwise, a thread is probably more applicable
Services (2)
Running in Eclipse (1)
Similar to launching a regular Java app,
use the launch configurations
Specify an Android Application and create
a new one
Specify activity to be run
Can select a manual option, so each time
program is run, you are asked whether
you want to use the actual phone or the
emulator
Otherwise,
it should be smart and use
Running in Eclipse (2)
Running in Eclipse (3)
Running in Eclipse (4)
USB Debugging
Should be enabled on phone to use
developer features
In the main apps screen select Settings ->
Applications -> Development -> USB
debugging (it needs to be checked)
Android Debug Bridge
Used for a wide variety of developer tasks
Read
from the log file
Show what android devices are available
Install android applications (.apk files)
In the ‘platform-tools’ directory of the main
android sdk directory
Recommend
putting this directory and the
‘tools’ directory on the system path
adb.exe
Debugging
Instead of using traditional System.out.println, use the Log class
Imported with android.util.Log
Multiple types of output (debug, warning, error, …)
Log.d(<tag>,<string>)
Can be read using logcat.
Print out the whole log, which auto-updates
Erase log
adb logcat –c
Filter output via tags
adb logcat
adb logcat <tag>:<msg type> *:S
can have multiple <tag>:<msg type> filters
<msg type> corresponds to debug, warning, error, etc.
If use Log.d(), then <msg type> = D
Reference
http://developer.android.com/guide/developing/debugging/debugging-log.html
Screen Shots
Some say you need to root the phone –
that is not true
One option: Android Screen Capture
http://www.mightypocket.com/2010/08/androi
d-screenshots-screen-capture-screen-cast/
It’s slow, but fine for screenshots of
applications whose screens aren’t changing
fast
Read their installation help, following the extra
steps if need be (I had to copy adb.exe and
some dll files, as they explain)
Maps Example (1)
Using Google Maps in your app
Setup project to use ‘Google API’ version
Edit Manifest file
To indicate the app will use maps and the internet
Get a maps API key
Note: Google Maps API can display a map and draw overlays,
but is not the full Google Maps experience you enjoy on the web
For example, there does not seem to be inherent support for
drawing routes between points (if you find it let me
know)…however, you can draw lines between points and almost
any type of overlay, but that’s different than street routes
The directions API is a web service, which is different, among
several other Google web services
Read the Google API terms of use
Maps Example (2)
Maps Example (3) – Manifest
(1)
Open Manifest file
Add map library tag
Indicate the app will access the internet
Add the ‘Uses Library’ com.google.android.maps
Add the ‘Permission’ android.permission.lNTERNET
End goal is to add the following two lines to XML
file, under the <manifest> and <application tags>,
respectively
Under the <manifest> tag
Under the <application> tag
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-library android:name="com.google.android.maps"></uses-library>
Following is GUI way to add them
Maps Example (4) – Manifest
(2)
1
2
Maps Example (5) – Manifest
(3)
Select ‘Add’ under ‘Uses Library’ (last
slide)
Then select ‘Uses Library at this prompt
Set name as: com.google.android.maps
(next slide) and save
Maps Example (6) – Manifest
(4)
Maps Example (7) – Manifest
(5)
2
1
Maps Example (8) – Manifest
(6)
Select ‘Permissions’ and then ‘Add’ (last
slide)
Select ‘Uses Permissions’ at this prompt
Set name to:
android.permission.INTERNET and save
(next slide)
Maps Example (9) – Manifest
(7)
Maps Example (10) – Maps API
Key (1)
All Android applications need to be signed
The
debug mode signs for you with special
debug certificate
All MapView elements in map applications
need to have an API key associated with
them
That
key must be registered with the
certificate used to sign the app
When releasing app, need to sign with a
release certificate and get a new API Key
Maps Example (11) – Maps API
Key (2)
For debug mode, get the MD5 fingerprint of the debug certificate
Locate the ‘keystore’
Windows Vista: C:\Users\<user>\.android\debug.keystore
Windows XP: C:\Documents and Settings\<user>\.android\debug.keystore
OS X and Linux: ~/.android/debug.keystore
Use Keytool (comes with Java, in the bin directory with the other
Java tools, should put that dir on system PATH) to get fingerprint
keytool -list –v -alias androiddebugkey -keystore
“<path_to_debug_keystore>” -storepass android -keypass android
If don’t include –v option, then will probably get only 1 fingerprint, and if
it’s not MD5, then need –v (Java 7 needs –v)
Extract the MD5 fingerprint, SHA will not work unfortunately
Go to https://code.google. com/android/maps-api-signup.html ,
agree to terms and paste MD5 fingerprint, you will then be given
an API Key
Maps Example (12)
Need to put MapView tag in XML
com.google.android.maps.MapView
MapView is the basic view that represents a Google Map
display
Must include API Key in XML, inside a layout
<com.google.android.maps.MapView
android:id="@+id/mapview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:clickable="true"
android:apiKey=“<api key>”/>
Maps API Reference
http://code.google.com/android/add-ons/google-apis/reference/index.html
Acknowledgements
Android Developer’s Website
Activity and Service life-cycle flow charts
Tons of other Android info
Google Maps API external library
MightyPocket
http://www.mightypocket.com/2010/08/android-screenshots-screen-capture-screen-cast/
Numerous Forums & other developer sites, including:
http://www.javacodegeeks.com/2011/02/android-google-maps-tutorial.html
http://efreedom.com/Question/1-6070968/Google-Maps-Api-Directions
http://www.mail-archive.com/android-developers@googlegroups.com/msg28487.html
http://android.bigresource.com/ threads
http://groups.google.com/group/android-developers threads
Many http://stackoverflow.com threads
http://www.anddev.org/google_driving_directions_-_mapview_overlayed-t826.html
http://code.google.com/android/add-ons/google-apis/maps-overview.html
Zainan Victor Zhou – for advice and his own tutorial
Advanced Android Topics
The first mile on Android: relatively straight forward
Should already know Java
GUI is roughly drag and drop
Lots of documentation and examples online…
Let’s get a little more advanced…
Debugging on an Android device
Persistent application storage (Preferences, Database)
Writing and linking non-Java code (e.g., C and C++)
Cross-compiling useful libraries to Android
Modifying the kernel (e.g., to add support, remove
permissions)
NFC support
Some More Advanced Layouts
As mentioned, we have a research project on
Android which uses a lot of advanced features
and different layouts
Good
examples of how to embed layouts within
each other…
https://github.com/gnychis/android These layouts are available
wmon/tree/master/application/res/layout
in our project:
Root: What do you need it for?
Like “jailbreaking” -- a term most are familiar with
Think of it as: it literally just gives you Linux root access
What don’t you need it for?
Writing a standard application that uses standard APIs and HW
Writing native code that does not touch some aspects of F.S.
What do you need it for?
Modifying and replacing the kernel
E.g., to remove permission checks, modify TCP, modify WiFi stack…
Loading and/or removing new kernel modules
Modifying anything in /system or snooping around /data
Modifying the Android OS or APIs
Changing the ROM on the device (new OS + kernel)
Debugging
As usual, two ways to have debug
information:
Android has a logging utility to print
Tag
Message
information to
2. Full debugger through ADB and Eclipse
1.
Logging utility: good for printing periodic
status of application and/or certain
variables
Persistent Storage
You are likely going to want to persistently
store data
In Android, there are 5 main ways to store
data:
Shared Preferences – private key-value pair
storage
2. Internal Storage – private storage perapplication
1.
Shared Preferences Overview
Good for basic data storage, simple
examples:
Has
the user completed the application
settings? (boolean)
What is the user’s username? (string)
Shared Preferences accessed by string
key, value can be:
boolean,
float, int, long, string
Shared Preferences Example
Name preference file (does not need to be
globally unique)
Get a handle to your preferences:
Can read in values by key, specify value if
Do not forget
does not exist
SQLite Database
Should hopefully know the basics of
databases
Best to store your main data/objects
Marshal
your classes to and from a row in a
database
Android provides some useful helper
classes
Writing Native Code (JNI)
JNI: framework that allows Java code to call, or be called by,
native applications/libraries in other languages
E.g., Java code can call a function written in C++, and visa-versa
Easiest way to integrate pre-existing code and libraries in other
languages (e.g., a pre-existing C encryption library)
Good to implement certain functionality which can be written
more optimally in C, for example
Native code still runs within the application’s VM
Follows AndroidManifest (e.g., need “INTERNET” for sockets)
Android NDK: Toolset integrate/compile JNI in to Android app
The Structure of Native Code
Directory structure: native code fits in “jni”
directory
ndk-build uses Android.mk in each native directory
Top-Level Android.mk
Best way to make top-level Android.mk:
List each subdirectory for ndk-build
to enter and build individually.
You can cross-reference in-between libraries
E.g.,
stringlib can use a function found in mathlib, the
stringlib Android.mk file just needs to specify it links
mathlib
Individual Library Android.mk
Each library needs its own Android.mk, with:
Local source files, linker/compiler flags, output
(e.g., shared lib)
Something a little more advanced, for example:
Creates lib_____.so (i.e., libawmon.so)
Simple Native C Code Example
Need to include JNI environment header,
logging
also useful
__android_log_print(ANDROID_LOG_INFO,
“NativeMath”, ”Error:
%d”, eval);
Native function is passed …
Java
environment: often used to allocate new
Java objects
Java class object:
Your Parameters: any C/C++ primitives
Must match your package
name
(case sensitive)
Must match the class
accessing and calling the
native code
(case sensitive)
Building NDK Code
Make sure ndk-build is in your PATH env.
Variable
Standard Android documentation should get
you this far…
From the base of your application directory
(outside jni dir):
All of your built libraries are copied to
libs/armeabi/
The Eclipse Gotcha
YOU MUST REFRESH YOUR DIRECTORY
IN ECLIPSE!!
Eclipse
does not look
for changes, even if
you were to rebuild app
You must refresh every
time you run ndk-build
otherwise your changes
will not be included
Maybe something built in
to Eclipse now?
Accessing Native Code in Java
Must load each native library: e.g.,
Can be done in any class or thread
It is a blocking call, to keep in mind if loading large
libraries…
Must create native function prototypes in respective
classes:
Once done, you can access these functions directly:
Using External Libraries
“I need a library to help me with _____, but it is a
standard C or Linux implementation” (e.g.,
crypto library)
Proceed in this order:
1. Google “____ Android” – many libraries
already cross-compiled
2. Write custom Android.mk to cross-compile it
You will be surprised how many libraries you find crosscompiled, and even if an older version: use their
Android.mk
Cross-Compiling Libraries
For many libraries, look at the Makefile and see which source files it
uses to build the library
Add these sources to Android.mk “LOCAL_SRC_FILES”
Use similar CFLAGS, LDFLAGS
Common for libraries to link to pthread, remove –lpthread but keep
most pthread code. Custom pthread force linked
Look at the many examples online, including our own:
libpcap, libnl, libgcrpyt, libglib, libgpg, libusb ….
https://github.com/gnychis/android-wmon/tree/master/application/jni
Modifying the Kernel
Several key steps to modifying the
kernel…
1.
2.
3.
4.
Obtaining the proper source code for HW + OS
version
If you get the wrong kernel: phone will not boot (I’ll
help you…)
Modifying the kernel (we’ll give you some pointers…)
Cross-compiling the kernel using the NDK
Installing the kernel (BE CAREFUL: CAN BRICK
PHONE)
Best to use something called “AnyKernel” package
This needs to be done in Linux (e.g., in a Virtual Machine)
Obtaining Kernel Source Code
The two possible phones you are using for this class:
Galaxy Nexus: code name “maguro” (“tuna” for
kernel)
Galaxy S: code name “crespo”
Best to start at this link:
https://android.googlesource.com/
Kernel source code depends on the HW, for you:
Galaxy Nexus:
https://android.googlesource.com/kernel/omap.git
Nexus
S:
https://android.googlesource.com/kernel/sa
3.0.31-g<hash> (i.e., d5a18e0)
msung.git
… make sure to drop the g that is
prepended to the hash
In “About Phone” you can find your git kernel commit:
Building the Kernel
Build using cross-compiler provided by Google:
Setup your environment:
Checkout your kernel version: git checkout <hash>
Setup with the proper configuration
Galaxy Nexus:
Nexus S:
make tuna_defconfig
make crespo_defconfig
Finally, you can build with: make
Packaging the Kernel – Pt1
Need to create a ramdisk with the the proper init scripts
Can be extracted from the device, but we will provide
you with it
See example…
Modifications to ramdisk are needed if you want to:
Load kernel modules on boot
Set permissions to certain devices/files on boot
Change the order services are initialized
Packaging the Kernel – Pt2
This is very tricky, and must be done properly or you will
“brick” the phone, i.e., it will not boot and must be
repaired
Install without building the entire OS by creating “update”
ZIP
Runs a script to mount FS and extract kernel &
modules
Usually includes system directory which is extracted
What the updater script looks like for Galaxy Nexus:
Packaging the Kernel – Pt3
Example hierarchy of the update ZIP
Boot image with kernel at
root
These are standard
Specific to device,
updater script
MUST put all
kernel modules
in here that were
rebuilt with kernel
Installing the Kernel
Need to use “recovery” mode on the phone to install
Dedicated, bootable partition with recovery console
Put your updater zip on your SD card, then:
Use recovery to
install the ZIP
Kernel Pointers
Based on the project page, some kernel locations you might be
interested in….
WiFi Driver: drivers/net/wireless/bcmdhd
TCP Protocol / Sockets:
net/ipv4
include/net
Permissions (e.g., sockets): kernel/capability.c
Near Field Communication
Low rate short distance wireless communication
Approx. 10 centimeters supported
424 kbit/s across 13.56MHz
Current applications: payments, smart posters, check-ins…
Two major NFC modes:
Reader / Writer mode
Peer-to-Peer mode (emulate tags on Android)
Nexus S was first phone to really “mainstream” NFC
NDEF (NFC Data Exchange
Format)
Standard data format created by NFC Forum
NDEF Messages: basic transportation mechanism
Can contain one or more NDEF Records
NDEF Record:
contain specific
structure with
payload
TNF contains the
record type
(e.g., URI)
Tag Read / Write Example
Start with basic tag read and write example
Includes P2P mode ability
This was an example posted by Google that we
modified to make a little more intuitive
Sample code was posted for you:
https://github.com/gnychis/stickynotes
The Basic NFC Permissions
As usual, you need to have Android permissions
Important to specify minimum SDK
Ensure that the phone has NFC support
Receiving NFC Tag Information
Remember, all information in Android is broadcast
For NFC, you register to receive TAG read broadcasts:
Registering for NFC Data
Specify that the Activity should receive NFC Intents:
Can specify which data types the application should receive:
Need a handle to the “NFC Adapter” (i.e., hardware)
Apply and enable the filter in onResume()
Receiving the NFC Data – Pt1
Receive callbacks in “onNewIntent()” you
override:
Receiving the NFC Data – Pt2
NDEF Messages come in as an array
Then, you can go through the msgs array and get the payload:
Detecting Nearby Tag to Write
Just like you registered to receive NFC tag data, you register to
know when a tag is simply detected and then use it to trigger a write
to it:
When the user specifies to write, you enable this filter and use a
software flag to know that you should write when the tag is detected
nearby: