Operating System Support for Mobile Devices

Download Report

Transcript Operating System Support for Mobile Devices

Mobile Software Development
Framework
10/2/2012
Y. Richard Yang
1
Admin.
Homework 2
Start to think about project
2
Recap: OFDM
Basic: use multiple subcarriers to reduce
symbol rate per carrier
Key idea 1: orthogonal subcarriers to avoid
inter-carrier-interference (ICI): chose
each subcarrier frequency so that an
integral number of cycles in a symbol
period
Key idea 2: iFFT as an efficient algorithm
for modulation on multiple subcarriers
Idea 3: cyclic prefix (guard interval)
3
Recap: Summary of Wireless PHY
4
Recap: GNURadio
A software development toolkit that
provides signal processing blocks to
implement software-defined radio systems.
Some key ideas
Hybrid software system (Python/C++)
Composite pattern to build a hierarchy of blocks
• http://en.wikipedia.org/wiki/Composite_pattern
Internal scheduler to orchestrate data flows
among blocks
Define gr_block as a reusable base so that
defining a new block typically means only rewrite
general_work and forecast
5
Recap: TinyOS
A free and open source component based
operating system and platform targeting
wireless sensor networks (WSNs)
Some design features
TinyOS: Generate customized
OS + application: support one app
at a time but flexible reprogramming
6
TinyOS: Software Concepts
A TinyOS consists of one or
more components/modules
linked together
software components
motivated by hardware
component
Each component specifies:
it provides some interfaces
• allows other components to
control it
also uses some interfaces
• control other components
7
Interface
An interface
declares
a set of
functions called
commands that
provider must
implement
another set of
functions called
events that the
interface user
must implement
A uses interfaces I1 and I2
I1
commands events commands
B provides I1
I2
events
C provides I2
C provides I3
8
Interface: Examples
StdControl.nc
interface
command
command
command
}
StdControl {
result_t init();
result_t start();
result_t stop();
ADC.nc
interface ADC {
async command result_t
getdata();
Timer.nc
interface Timer {
command result_t start(
char type,
uint32_t interval);
command result_t stop();
event result_t fired();
}
async command result_t
getContinuousData();
event result_t dataReady(uint
16_t data);
}
9
Example Application
A simple TinyOS
application which
periodically reads
in the light
intensity value,
computes a
moving average,
displays it on the
LED
10
Module: Definition
SenseTaskM.nc
module SenseTaskM {
provides {
interface StdControl;
}
uses {
interface Timer;
interface ADC;
interface StdControl
as ADCControl;
interface Leds;
}
}
A uses interfaces I1 and I2
I1
commands events commands
B provides I1
I2
events
C provides I2
C provides I3
11
Module: Implementation
Define
commands and event handlers
Component
Internal Tasks
Internal State
frame (storage)
• statically allocated, fixed
size to know memory
requirement and avoid
overhead of dynamic
allocation
Commands
Events
See SenseTaskM.nc
12
Linking Components
Two types of components:
modules: individual components
configurations : assemble components together,
connecting interfaces (objects) used by
components to interfaces (objects) provided by
others
• See SenseTask.nc
13
TinyOS Execution Model
A uses interfaces I1 and I2
commands events commands
B provides I1
events
C provides I2
C provides I3
14
TinyOS Execution Model
Concurrency model: only two threads
long running tasks that can be interrupted by hardware
event handlers
Each task is atomic with respect to other tasks
run to completion, but can be preempted by events
the task scheduler is a simple FIFO scheduler
Tasks perform the primary computation work
commands and event handlers post tasks
call lower level commands
signal higher level events
schedule other tasks within a component
15
Running tinyOS Program
make mica
ncc -o main.exe -target=mica SenseTask.nc
avr-objcopy --output-target=srec main.exe
main.srec
Use uisp to install
16
A More Complete Sample Application
Sensor network
monitoring
monitor temperature and
light conditions
periodically transmit
measurements to a base
station
sensors can forward data
for other sensors that are
out of range of the base
station
dynamically determine the
correct routing topology for
the network
17
Internal Component Graph
Ad hoc Routing Application
application
Active Messages
packet
Radio Packet
UART Packet
Temp
Radio byte
UART
I2C
SW
byte
HW
Light
bit
RFM
Clocks
18
Message Send Transition
Total propagation delay up the 5 layer radio
communication stack is about 80 instructions
Timing diagram of event propagation
19
Evaluation: Storage
 Scheduler only occupies
178 bytes
 Complete application
only requires 3 KB of
instruction memory and
226 bytes of data (less
than 50% of the 512
bytes available)
 Only processor_init,
TinyOS scheduler, and C
runtime are required
Component Name
Code
Size
(bytes)
Data
Size
(bytes)
Routing
AM_dispatch
AM_temperature
AM_light
AM
RADIO_packet
RADIO_byte
RFM
Light
Temp
UART
UART_packet
I2C
88
40
78
146
356
334
810
310
84
64
196
314
198
0
0
32
8
40
40
8
1
1
1
1
40
8
Processor_init
TinyOS scheduler
C runtime
172
178
82
30
16
0
3450
226
Total
20
Evaluation: Timing
Operations
Byte copy
Cost
(cycles)
Time
(µs)
Normalized
to byte copy
8
2
1
10
10
46
51
2.5
2.5
11.5
12.75
1.25
1.25
6
6
Interrupt (hardware cost)
9
2.25
1
Interrupt (software cost)
71
17.75
9
Post an Event
Call a Command
Post a task to scheduler
Context switch overhead
21
Summary: TinyOS
Components
provide commands and
require callback hooks
for event-driven
programming
Configurations
Link components
TinyOS
an app (configuration)
at a time, linking
only necessary
components
Two threads exec
one for event
one for task
ADC.nc
interface ADC {
async command result_t getdata();
async command result_t
getContinuousData();
event result_t dataReady(uint 16_t
data);
}
configuration SenseTask {
// this module does not provide any interfaces
}
implementation
{
components Main, SenseTaskM, LedsC, TimerC,
DemoSensorC as Sensor;
Main.StdControl -> TimerC;
Main.StdControl -> Sensor;
Main.StdControl -> SenseTaskM;
SenseTaskM.Timer ->
TimerC.Timer[unique("Timer")];
SenseTaskM.ADC -> Sensor;
SenseTaskM.Leds -> LedsC;
}
22
Discussion: Compare TinyOS/GNURadio
What are some similar software concepts?
What are some differences?
23
Discussion
Can we use GNURadio/TinyOS for writing
mobile applications for mobile phones, or in
other words, what are missing?
24
Java2 Micro Edition (J2ME)
25
Outline
Admin and recap
Mobile/wireless development framework
GNURadio
TinyOS
J2ME
26
Java Platforms
Java2 is divided into three platforms
J2EE (Java2 Enterprise Edition)
• business applications
J2SE (Java2 Standard Edition)
• general applications
J2ME (Java2 Micro Edition)
• small devices such as mobile phone, PDA, car
navigation
Oracle’s claims on Java on mobile devices
http://www.java.com/en/about/
27
J2ME Basic Concepts:
Versioning
To accommodate heterogeneous mobile
devices, define configurations and profiles
-A configuration provides fundamental
services for a broad category of devices
(e.g., lang, io, util)
- A profile supports higher-level services
common to a more specific class of
devices or market (e.g., life cycle, GUI)
-An optional package adds specialized
services that are useful on devices of
many kinds, but not necessary on all of
them
http://developers.sun.com/techtopics/mobility/getstart/articles/survey/
28
J2ME
Upto 2M mem 128-512K mem
16-32 bit proc
32 bit proc
29
Example J2ME Configurations
Connected Limited Device Configuration (CLDC)
160 KB to 512 KB of total memory available
16-bit or 32-bit processor
low power consumption and often operating with battery
power
connectivity with limited bandwidth
examples: cell phones, certain PDAs
Connected Device Configuration (CDC)
2 MB or more memory for Java platform
32-bit processor
high bandwidth network connection, most often using TCP/IP
examples: set-top boxes, certain PDAs
30
CLDC Available Packages
java.lang
java.util
java.io
javax.microedition.io
31
CLDC Classes
Boolean
Byte
Character
Class
Integer
Long
Math
Object
Runnable
Runtime
Short
String
StringBuffer
System
Thread
Throwable
java.lang
Calendar
Date
Enumeration
Hashtable
Random
Stack
TimeZone
Vector
java.util
ByteArrayOutputStream
ByteArrayInputStream
DataOuput
DataInput
DataInputStream
DataOutputStream
InputStream
InputStreamReader
OutputStream
OutputStreamWriter
PrintStream
Reader
Writer
java.io
32
Example J2ME Profiles
Mobile Information Device Profile (MIDP)
GUI, multimedia and game functionality,
end-to-end security, and greater networked
connectivity
mobile phones and entry level PDAs
Foundation Profile
set of Java APIs that support resource-constrained devices
without a standards-based GUI system
Personal Profile
Full set of AWT APIs, including support for applets and Xlets
CDC + Foundation Profile + Personal Profile for high-end PDA
…
33
Mobile Phone Framework
34
MIDP Hardware
Memory (added to CLDC memory)
128 KB non-volatile for MIDP components
8 KB non-volatile for application persistent data
32 KB volatile for KVM
Display
screen 96x54
display depth 1-bit
pixel shape (aspect ratio) 1:1
35
MIDP Hardware
Input (one or more)
one-handed keyboard (ITU-T phone keypad)
two-handed keyboard (QWERTY keyboard)
or touch screen
Networking
two-way
wireless
possibly intermittent
limited bandwidth
36
MIDP Packages
java.io
java.lang
java.util
javax.microedition.io
javax.microedition.lcdui
javax.microedition.rms
javax.microedition.midlet
version 1.0
javax.microedition.lcdui.game
javax.microedition.media
javax.microedition.media.control
javax.microedition.pki
addition in version 2.0
37
MIDP Technology Stack
Your
MIDlet
Mobile
Information
Device
Profile
Yellow Pages, train
schedules and
ticketing, games…
UI, HTTP
networking...
J2ME core APIs
CLDC = KVM
+ J2ME Core
APIs
in this
example
KVM
DSP chip
(e.g., ARM)
Threads, no Floats…
32-bit RISC, 256K
ROM, 256K Flash, 64K
RAM
38
MIDlet
GUI based
Each MIDP has one instance of Display
• Display.getDisplay(this) to get the manager
• At any instance of time at most one Displayable
object can be shown on the display device and interact
with user
– display.setCurrent(<Displayable object>)
39
MIDlet
An MIDP application is
called a MIDlet
similar to the J2SE applet
A MIDlet moves from state
to state in the lifecycle, as
indicated
start – acquire resources and start
executing
pause – release resources and
become quiescent (wait)
destroy – release all resources,
destroy threads, and end all activity
Pause
pauseApp
startApp
Active
destroyApp
destroyApp
Destroyed
40
MIDP Visual Display
Each MIDP has one instance of Display
Display.getDisplay(this) to get the manager
At any instance of time at most one Displayable
object can be shown on the display device and
interact with user
• display.setCurrent(<Displayable object>)
41
MIDP Visual Display
Displayable
Canvas
• GameCanvas
Screen
• Alert, List, TextBox, Form
Form can contain multiple form items for
organization
Labels, Image Items, String Items, Text Fields, Date
Fields, Gauges, Choice Groups
42
MIDP: User Interaction
Displayable objects can declare commands
and declare a command listener:
addCommand(Command cmd)
addCommandListener()
Command(<label>, <type>,
<priority>)
Type: BACK, CANCEL, EXIT, HELP, ITEM,
OK, SCREEN, and STOP
43
HelloWorldMIDlet.java
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class HelloWorldMIDlet extends MIDlet
implements CommandListener {
private Command exitCommand;
private Display display;
private TextBox t;
public HelloWorldMIDlet() {
display = Display.getDisplay(this);
exitCommand = new Command("Exit", Command.EXIT, 2);
t = new TextBox(“CS434", "Hello World!", 256, 0);
t.addCommand(exitCommand);
t.setCommandListener(this);
}
public void startApp() { display.setCurrent(t); }
public void pauseApp() { }
public void destroyApp(boolean unconditional) { }
public void commandAction(Command c, Displayable s) {
if (c == exitCommand) {
destroyApp(false);
notifyDestroyed();
}
}
}
44
MIDP: Persistent State
Record store defined in javax.microedition.rms
Record store identified by name:
static String[] listRecordStores();
recordStore =
RecordStore.openRecordStore("scores", true);
recordId = addRecord(byte[] data, int offset,
int numBytes);
getRecord(int recordId);
45
Summary : J2ME
Scale down a popular programming environment to
ease learning
Use virtual machines to mask device heterogeneity
Use configuration/profiling to handle device
heterogeneity and avoid using lowest common
denominator
MIDLet to manage app life cycle
Displayable to visual display, commands and provides
command listener
Introduce persistent record store
46
Discussion on J2ME
What designs of J2ME do you like and hence
expect newer frameworks (e.g., IOS,
Android) may have too?
What features do you think are missing in
J2ME?
47
Outline
Admin and recap
Mobile/wireless development framework
GNURadio
TinyOS
J2ME
Android
http://developer.android.com/index.html
48
Android
A mobile OS, application
framework, and a set of applications
OS
• Customized Linux kernel 2.6 and
3.x (Android 4.0 onwards)
– E.g., default no X Windows,
not full set of GNU libs
Application development framework
• Based on Java (J2SE not J2ME)
• Dalvik Virtual Machine
49
Android Architecture
50
Poking Android OS
See
http://developer.android.com/tools/workflo
w/index.html
Android SDK Manager (android) to start a
simulator
Android debug bridge (adb) can connect to
an Android device and start a shell on the
device
Application Framework (Android):
Key Concepts
Activity
View
External resources
Service
Intercommunications
Communication
among apps:
- Intent
- broadcast
- data provider
App
App
52
Activity
A single, focused thing that the user can do.
Interaction with users: creating a window to
place UI views
full-screen windows, floating windows,
embedded inside of another activity
Android
Activity Life
cycle
54
View
A view component is a building block for user
interface components.
Widget Toolbox
TextView, EditText, Button, Form, TimePicker…
ListView
Layout
• Positions of controls
• LinearLayout, Relativelayout
http://developer.android.com/guide/tutorials/views/index.htm
View by XML
Layout of visual interface
Java Code
Initialize
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
}
Access
TextView myTextView =
(TextView)findViewById(R.id.myTextVie
main.xml
<?xml version=”1.0” encoding=”utf-8”?>
<LinearLayout
xmlns: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/myTextView”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”Hello World, HelloWorld”
/>
</LinearLayout>
User Interaction Event
onKeyDown. onKeyUp
onTrackBallEvent
onTouchEvent
registerButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {….}}
myEditText.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN)
if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
…
return true;
}
return false;
}});
}
Example: TipCal
58
Application Framework (Android):
Key Concepts
Activity and view
Visible screen for user interaction
External resources
59
External Resources
60
Application Framework (Android):
Key Concepts
Activity and view
Visible screen for user interaction
External resources
Service
61
Service: Working in Background
A basic function of Android Service:
A facility for an application to tell the system about something it
wants to be doing in the background (even when the user is not
directly interacting with the application).
The system to schedule work for the service, to be run until the
service or someone else explicitly stop it.
NO GUI, higher priority than inactive Activities
Note
A Service is not a separate process. The Service object itself
does not imply it is running in its own process; unless otherwise
specified, it runs in the same process as the application it is part
of.
A Service is not a thread. It is not a means itself to do work off
of the main thread (to avoid Application Not Responding errors).
Application and Component Glues
Intent
An intent is an abstract description of an
operation to be performed.
To invoke operations from your own or others
Can pass data back and forth between app.
Intent Filter
Register Activities, Services, and Broadcast
Receivers as being capable of performing an
action on a particular kind of data.
Intent Description
<Component name>
Action
Data
Category, e.g., LAUNCHER
64
Intent Usage
Pass to Context.startActivity() or
Activity.startActivityForResult() to launch an activity or get an
existing activity to do something new.
Pass to Context.startService() to initiate a service or deliver
new instructions to an ongoing service.
Pass to Context.bindService() to establish a connection
between the calling component and a target service. It can
optionally initiate the service if it's not already running.
Pass to any of the broadcast methods (such as
Context.sendBroadcast(), Context.sendOrderedBroadcast(), or
Context.sendStickyBroadcast()) are delivered to all interested
broadcast receivers. Many kinds of broadcasts originate in
system code.
65
Android: Broadcast Receiver
Sending a broadcast:
Context.sendBroadcast(Intent intent,
String receiverPermission)
Context.sendOrderedBroadcast()
Receiving broadcast:
Intent registerReceiver
(BroadcastReceiver receiver,
IntentFilter filter)
66
Intent Resolution: Explicit
Explicit intents: component identified
Intent myIntent = new Intent(IntentController.this,
TipCal.class);
startActivity(myIntent);
Make sure AndroidManifest.xml announces
activities to be started
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".IntentController"
android:label="Intent1">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".TipCal"></activity>
</application>
67
Intent Resolution: Implicit
Implicit intents
System matches an intent object to the intent
filters of others
http://developer.android.com/guide/topics/intents/intents-filters.html
68
Intent filter
action
category
data
69
Intent Example II: Implicit
String action = "android.intent.action.VIEW";
Uri data = Uri.parse("http://www.google.com");
Intent myIntent = new Intent(action, data);
startActivity(myIntent);
AndroidManifest.xml file for com.android.browser
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<scheme android:name="http" />
<scheme android:name="https" />
<scheme android:name="file" />
</intent-filter>
70
Intent Example II: Implicit
String action = "android.intent.action.DIAL";
String phno = "tel:4326400";
Uri data = Uri.parse(phno);
Intent dialIntent = new Intent(action, data);
startActivity(dialIntent);
A Design Template: Invoker
String action = “com.hotelapp.ACTION_BOOK";
String hotel = “hotel://name/“ + selectedHotel;
Uri data = Uri.parse(hotel);
Intent bookingIntent = new Intent(action, data);
startActivityForResults(bookingIntent, requestCode);
72
A Design Template: Provider
<activity android:name=".Booking" android:label=“Booking">
<intent-filter>
<action android:name=“com.hotelapp.ACTION_BOOK" />
<data android:scheme=“hotel" android:host=“name”/>
</intent-filter>
</activity>
For more complex data passing, please read
the tutorial
73
A Design Template: Provider
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent intent = getIntent(); // why am I called
String action = intent.getAction();
Uri data = intent.getdata();
String hotelName = data.getPath();
// do the booking
setResult(RESULT_OK);
finish();
}
74
Intent and Broadcast: Sender
String action = "edu.yale.cs434.RUN";
Intent cs434BroadcastIntent =
new Intent(action);
cs434BroadcastIntent.putExtra("message",
"Wake up.");
sendBroadcast(cs434BroadcastIntent);
Example: IntentLaunch
75
Intent and Broadcast: Receiver
<receiver android:name=".CS434BroadcastReceiver"
android:enabled="true">
<intent-filter>
<action android:name="edu.yale.cs434.RUN" />
</intent-filter>
</receiver>
76
Intent, Broadcast, Receiver, Notification
public class CS434BroadcastReceiver extends BroadcastReceiver {
public static final String CUSTOM_INTENT = "edu.yale.cs434.RUN";
// Display an alert that we've received a message.
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(CUSTOM_INTENT)) {
String message = (String)intent.getExtras().get("message");
CharSequence text = "Got intent " + CUSTOM_INTENT + " with " + message;
int duration = Toast.LENGTH_SHORT;
Toast mToast = Toast.makeText(context, text, duration);
mToast.show();
} // end of if
} // end of onReceive
}
77
Recap: Do not Block
ANRs (Application
not responding)
happen when
Main thread
(“event”/UI) does
not respond to
input in 5 sec
A broadcast
receiver does not
finish in 10 sec
5-10 sec is
absolute upper
bound
78
Recap: Do not Block
Numbers (Nexus One)
~5-25 ms – uncached flash reading a byte
~5-200+(!) ms – uncached flash writing tiny amount
100-200 ms – human perception of slow action
108/350/500/800 ms – ping over 3G. varies!
~1-6+ seconds – TCP setup + HTTP fetch of 6k over 3G
Rules
Notify users
Use background processing
Example: LaunchThread
Example: SimplyService
79
Background Processing using a Thread
Problem:
Background thread and UI thread are running
concurrently and may have race conditions if they
modify simultaneously
Solution: Android Handler
Use Handler to send and process Message and
Runnable objects associated with a
thread's MessageQueue.
80
Android Handler
Each Handler instance is associated with a
single thread and that thread's message
queue.
A handler is bound to the thread / message
queue of the thread that is creating it
from that point on, it will deliver messages and
runnables to that message queue and execute
them as they come out of the message queue.
81
Using Handler
There are two main uses for a Handler:
to schedule messages and runnables to be
executed as some point in the future; and
to enqueue an action to be performed on a
different thread than your own.
82
Handler
public class MyActivity extends Activity {
[...]
// Need handler for callbacks to the UI thread
final Handler mHandler = new Handler();
// Create runnable for posting
final Runnable mUpdateResults = new Runnable() {
public void run() {
updateResultsInUi();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
[...]
}
83
Handler
protected void startLongRunningOperation() {
// Fire off a thread to do some work that we shouldn't do directly in the UI thread
Thread t = new Thread() {
public void run() {
mResults = doSomethingExpensive();
mHandler.post(mUpdateResults);
}
};
t.start();
}
private void updateResultsInUi() {
// Back in the UI thread -- update our UI elements based on the data in mResults
[...]
}
}
84
Examples
See BackgroundTimer
See HandleMessage
85
Tools
AsyncTask
IntentService
86
Tools: AsyncTask
See GoogleSearch
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) { // on some background thread
int count = urls.length; long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) { // on UI thread!
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) { // on UI thread!
showDialog("Downloaded " + result + " bytes");
}
}
new DownloadFilesTask().execute(url1, url2, url3); // call from UI thread!
87
Does Background Solve All
Issues?
88
Example: Accessing Data in Cloud
A typical setting is that a device accesses
data in the cloud, e.g.,
background sync
Challenge: How do you keep data on a device
fresh?
89
Polling
Simple to implement
Device periodically asks server for new data
Appropriate for content that changes
constantly
Stock Quotes, News Headlines
90
Impact of Polling on Battery
Baseline: ~5-8 mA
Network: ~180-200 mA
Tx more expensive than Rx
Assume radio stays on for 10 sec.
Energy per poll: ~0.50 mAh
5 min frequency: ~144 mAh / day
Droid 2 total battery: 1400 mAh
Source: Android development team at Google
91
Solution: Push
Google Contacts, Calendar, Gmail, etc., use
push sync
A single persistent connection from device to
Google
Android Cloud to Device Messaging (C2DM)
to make it a public service
92
C2DM Overview
Uses existing connection for Google services
Your servers send lightweight “data”
messages to apps
Tell app new data available
Intent broadcast wakes up app
App supplies UI, e.g., Notification, if/as
necessary
93
C2DM Flow
Enabling cloud to device messaging
App (on device) registers with Google, gets
registration ID
App sends registration ID to its App Server
Per message
App Server sends (authenticated) message to
Google
Google sends message to device
Disabling cloud to device messaging
App can unregister ID, e.g., when user no longer
wants push
94
C2DM
95
Android Code: Registration to C2DM
// Use the Intent API to get a registration ID
// Registration ID is compartmentalized per app/device
Intent regIntent = new
Intent(“com.google.android.c2dm.intent.REGISTER”);
// Identify your app
regIntent.putExtra(“app”,
PendingIntent.getBroadcast(this, 0, new Intent(), 0);
// Identify role account server will use to send
regIntent.putExtra(“sender”, emailOfSender);
// Start the registration process
startService(regIntent);
96
Receiving Registration ID
// Registration ID received via an Intent
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (“…REGISTRATION”.equals(action)) {
handleRegistration(context, intent);
} }
private void handleRegistration(Context context,
Intent intent){
String id = intent.getExtra(“registration_id”);
if ((intent.getExtra(“error”) != null) {
// Registration failed. Try again later, with backoff.
} else if (id != null) {
// Send the registration ID to the app’s server.
// Be sure to do this in a separate thread.
} }
97
Receiving Registration ID
App receives the ID as an Intent
com.google.android.c2dm.intent.REGISTRATION
App should send this ID to its server
Service may issue new registration ID at any
time
App will receive REGISTRATION Intent
broadcast
App must update server with new ID
98
Android: Content Provider
Each provider can expose its data as a simple
table on a database model
Each content provider exposes a public URI
that uniquely identifies its data set:
android.provider.Contacts.Phones.CONTENT_URI
android.provider.Contacts.Photos.CONTENT_URI
android.provider.CallLog.Calls.CONTENT_URI
android.provider.Calendar.CONTENT_URI
99
Intent and Content Provider
private void pickContact() {
// Create an intent to "pick" a contact, as defined by the content provider URI
Intent intent = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT_REQUEST);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// If the request went well (OK) and the request was PICK_CONTACT_REQUEST
if (resultCode == Activity.RESULT_OK
&& requestCode == PICK_CONTACT_REQUEST) {
// Perform a query to the contact's content provider for the contact's name
Cursor cursor = getContentResolver().query(data.getData(),
new String[] {Contacts.DISPLAY_NAME}, null, null, null);
if (cursor.moveToFirst()) { // True if the cursor is not empty
int columnIndex = cursor.getColumnIndex(Contacts.DISPLAY_NAME);
String name = cursor.getString(columnIndex);
// Do something with the selected contact's name...
}
}
}
10
Windows .NET Compact Framework
Similar to J2ME
Scales down a popular programming environment to ease learning
the .NET CF is a subset of the full .NET framework with some additions
designed for resource constrained devices
1,400 classes for .NET CF vs. 8,000 for full
27 UI controls for .NET CF vs. 52 for full
1.5 MB for .NET CF vs. 30 MB for full
Uses versioning to avoid using lowest common denominator
pocket PC
pocket PC phone version
smart phone version
Uses virtual machines to mask device heterogeneity
programming languages compile to MSIL
• MSIL is JIT compiled on the device
• MSIL code is smaller than native executables
• MSIL allows your code to be processor independent
10
Android
Linux kernel as foundation
Java based framework (J2SE not J2ME)
Dalvik Virtual machine
Nice features
Touch screen, accelerometer, compass,
microphone, camera, GPS,
GSM, EDGE, and 3G networks, WiFi, Bluetooth,
Near field communications
Media, SQLite, WebKit, SSL
Location-based service, map (Google API)
10