Android
Android
Mark Veltzer
CTO, Hinbit
[email protected]
Who am I?
Introduction
We will cover:
Android overview
Smart phones
Android versions
Android features
Android Overview
Smart phones
Applications, applications
Nokia - Symbian
Apple IPhone
Sales Q4 2010
Android versions
System-wide:
UI polish for:
Performance improvements
New Features
UI framework
AppWidget framework
Media framework
Platform Highlights:
http://developer.android.com/sdk/android-1.5highlights.html
Accessibility
Text-to-speech engine
Gestures
Accessibility
Messaging
Camera
Browser
Calendar
Media Framework
Bluetooth
Platform Highlights:
http://developer.android.com/sdk/android-2.0highlights.html
Exchange Support
Improved Performance
Media Framework
Platform Highlights:
http://developer.android.com/sdk/android-2.2highlights.html
Downloads management
SIP Stack
Platform Highlight:
http://developer.android.com/sdk/android-2.3highlights.html
Redesigned keyboard
Activity fragments
Resigned UI widgets
Richer notification
Enterprise features
UI refinements
Performance optimizations
Platform Highlights:
http://developer.android.com/sdk/android-3.1highlights.html
Platform Highlights:
http://developer.android.com/sdk/android3.2.html#highlights
NDK (user space C/C++ support) is also improving and expanding with each new
version. New codecs are supported, new openGL features, new version of bionic
(important for every native coder) and more.
New versions are much less backwards compatible for native code writers than for
Java application writers.
This partly stems from the fact that C and C++ are worse at backwards compatibility.
Partly because the Android platform cares more about compatibility at the Java layer
(which the majority of it's application coders need) and less about compatibility for
native coders (who are a minority).
Native code writers may choose a version for other reasons. For instance: some C+
+ exception handling for user space was added in version 2.0.
Sometimes native coders would switch versions because some kernel feature is
required and since changing kernel means changing Android version the native
layer switches too.
You may be forced to use #ifdef or other tricks in your code to support multiple
Android versions.
Open Source.
Android features
Application Framework
Graphic libraries
SQLite Database
GSM Telephony
Android Framework
We will cover...
Android framework
Security.
Networking.
Memory management.
Process management.
Driver model.
Wraps the kernel API (this is needed since the kernel API is quite hard to deal
with).
Bionic: a super fast and small BSD libc library optimized for embedded use.
SQLite database
Media codecs
Lots more
Android runtime
Dalvik
Dalvik - cont
Dalvik - cont
Application framework
Application Layer
An Android Application
Is an .apk file
An android market is thousands of apk files made by a
multitude of Android app developers.
Usually generated automatically for you by development
environments. Eclipse+ADT which puts it usually in the bin
folder of your project.
Comprised of 3 things:
We will cover...
Eclipse Plug-ins
Just select the Android repository and install support for the
versions of the Android platforms that you need.
Go drink some coffee.
You can install as many different emulated Android platforms
as you like. These are called AVD (Android Virtual Device).
After installing selected platforms you need to define some
virtual devices.
Each virtual device is based on an Android platform + a few
definitions.
After you have a virtual device just select it and click start to
run it. You will get a phone. It takes some time. Be patient.
You also have to tell ADT where your SDK is at (some
versions of ADT also require that you restart Eclipse after you
do that...).
The emulator
On Linux you don't need drivers but you may need to tweak
permissions of the USB device
http://developer.android.com/guide/developing/device.html#setting-up
Allow debugging.
SDK tools
IDE
The Emulator
Cache configuration.
Code profiling.
Configure timezone.
ADB (cont)
ADB: capabilities
Drop into a shell (adb shell). This is a low capability shell but is enough
to explore the file system and do basic debugging. You can also go into
SQLite databases using the sqlite3 command.
Much more.
ADB: uses
DDMS
DDMS provides a File Explorer tab that allows you to view, copy, and
delete files on the device.
The Threads tab in DDMS shows you the currently running threads for
a selected process.
You can also see logcat (logs) from DDMS.
In the Devices tab, select the process that you want to see the
heap information for.
Click the Update Heap button to enable heap information for the
process.
In the Heap tab, click Cause GC to invoke garbage collection,
which enables the collection of heap data. When the operation
completes, you will see a group of object types and the memory
that has been allocated for each type.
Click on an object type in the list to see a bar graph that shows the
number of objects allocated for a particular memory size in bytes.
In the Devices tab, select the process that you want to see
the heap information for.
Click the Update Heap button to enable heap information
for the process.
In the Heap tab, click Cause GC to invoke garbage
collection, which enables the collection of heap data.
When the operation completes, you will see a group of
object types and the memory that has been allocated for
each type.
Click on an object type in the list to see a bar graph that
shows the number of objects allocated for a particular
memory size in bytes.
DDMS: Profiling
DDMS: Misc
We will cover...
A word of warning...
Toolchain issues.
A word of warning
Github and other, much more strange, services are based on it.
It is a good idea to use git for low level Android development and
the Linux kernel.
You may need it if you want to submit patches to the Android
system or kernel.
Toolchain - definition
Toolchain - notes
A couple of options:
Is 2.6 based.
Go for coffee
cd android-kernel
make menuconfig
make
In oder for the build to work you have to have lots of tools that are needed by the long
build process.
These include: git-core gnupg flex bison gperf build-essential zip curl zlib1g-dev libc6-dev
lib32ncurses5-dev ia32-libs x11proto-core-dev libx11-dev lib32readline5-dev lib32z-dev
libgl1-mesa-dev g++-multilib mingw32 tofrodos
If any of the tools are missing then the long build will fail in the middle (ergh!).
mkdir ~/bin
PATH=~/bin:$PATH
mkdir WORKING_DIRECTORY
cd WORKING_DIRECTORY
repo sync
Get coffee
source build/envsetup.sh
make/make -j4
Flashing a device
Application fundamentals
Application Fundamentals
Application Fundamentals Overview
Main Types
Activities
Services
Broadcast Receiver
Content Provider
Intents
Context
Application Lifecycle
Components Lifecycle
Application Fundamentals
Application Fundamentals Overview
Main Types
Activities
Services
Broadcast Receiver
Content Provider
Intents
Context
Application Lifecycle
Components Lifecycle
Application Fundamentals
Overview
Android Applications are written in the Java
Programming Language
The compiled code along with the resources files are
bundled into Android package (.apk file)
All code in one android package is considered as one
application
Application Fundamentals
Overview
Application Fundamentals
Application Fundamentals Overview
Main Types
Activities
Services
Broadcast Receiver
Content Provider
Intents
Context
Application Lifecycle
Components Lifecycle
Main Types
Android application have four primary building
blocks components:
Activities
Services
Broadcast Receivers
Content Providers
Main Types
Broadcast receivers:
Components that listen to events
Content Providers:
Component that make application data available for
other applications
Intent:
Asynchronous messaging system
Activities, services and broadcast receivers are
triggered by intents
Application Fundamentals
Application Fundamentals Overview
Main Types
Activities
Services
Broadcast Receiver
Content Provider
Intents
Context
Application Lifecycle
Components Lifecycle
Activities
Activities:
A visual user interface component that interact with
the user
Activity is the window or the view or the form
that the user is working on
Application can have more then one activity, and
although usually they work together to form
application cohesive user interface, each activity is
independent from the other.
Activities
One of the activities typically marked as the
main activity (the first one that should be
presented to the user)
note that android application doesn't have a main
method, instead we have activities that can be
launched, one of the will be launched by default.
Activity extends the android.app.Activity class
Application Fundamentals
Application Fundamentals Overview
Main Types
Activities
Services
Broadcast Receiver
Content Provider
Intents
Context
Application Lifecycle
Components Lifecycle
Services
A service that doesn't have visual user interface
runs in the background for indefinite period of time
Service extends the android.app.Service class
Application Fundamentals
Application Fundamentals Overview
Main Types
Activities
Services
Broadcast Receiver
Content Provider
Intents
Context
Application Lifecycle
Components Lifecycle
Broadcast Receiver
A component that the receives and react to
broadcast announcements from other
applications or from android system services
For instance, android system can announce (raise
event) about low-battery or phone call started, or
user changed preferences and more
Receiver extends the
android.content.BroadcastReceiver class.
Application Fundamentals
Application Fundamentals Overview
Main Types
Activities
Services
Broadcast Receiver
Content Provider
Intents
Context
Application Lifecycle
Components Lifecycle
Content Provider
A component that make specific set of data
from one application available for other
applications
A content provider uses a URI to identify the
provider
for instance: content://contacts/people
Content Provider extends the
android.content.ContentProvider class
When component want to activate content provider it
use a ContentResolver
Application Fundamentals
Application Fundamentals Overview
Main Types
Activities
Services
Broadcast Receiver
Content Provider
Intents
Context
Application Lifecycle
Components Lifecycle
Intents
To Activate Activity, Service of Broadcast
Receiver in android, we use the Intent Object.
Intent is an object that extends the
android.content.Intent class
Intent holds the message information regarding what
is it that we would like to activate
Intents are asynchronous mechanism
If one activity would like to start a service, or to
display a different activity to the user,
Intents
Intents cont.
The created intent is passed to methods from the
Context class (explained in the next slide).
Intent extends the android.content.Intent class.
Application Fundamentals
Application Fundamentals Overview
Main Types
Activities
Services
Broadcast Receiver
Content Provider
Intents
Context
Application Lifecycle
Components Lifecycle
Context
Both Activity and Service extends the
android.content.Context class.
The Context class is implemented by the Android
system.
It allow access to application specific resources and
classes.
It allow sending intents to activities, services and
broadcast receivers
Application Fundamentals
Application Fundamentals Overview
Main Types
Activities
Services
Broadcast Receiver
Content Provider
Intents
Context
Application Lifecycle
Components Lifecycle
Application Lifecycle
Android application doesn't have a main()
method
The system can instantiate one of the main four
components
For instance, when the user open the launch the
application, one of the activities is instantiate
Application Lifecycle
Between, they can be activated or deactivated,
become visible or invisible, start and stop etc
lifecycle of components in android is reflected in
the component API, we have lifecycle methods
for the components
Application Fundamentals
Application Fundamentals Overview
Main Types
Activities
Services
Broadcast Receiver
Content Provider
Intents
Context
Application Lifecycle
Components Lifecycle
Components Lifecycle
Components Lifecycle Activity Lifecycle
Components Lifecycle Service Lifecycle
Components Lifecycle Broadcast Receiver
Lifecycle
LifeCycle Methods
Components Lifecycle content providers
Components Lifecycle
Activity Lifecycle:
Activity have 3 states
Active or running, when the activity is in the
foreground (and in focus)
Paused, if it lost focus another activity is on top of
it, but part of it can still be seen
Stopped, no longer visible to the user
Components Lifecycle
Activity Lifecycle:
The transition between these states is reflected in the
lifecycle methods
onCreate and onDestory, entire lifetime of the activity
All initialization and destroy of references are created
in these methods
onStart and onStop (onRestart), visible lifetime of the
activity, between these methods the user can see the
activity
onResume and onPause, foreground lifetime of the
activity, between these methods the activity is in-front
of all other activities, and the user can interact with it
Components Lifecycle
Activity Lifecycle:
The following
diagram explain it
Components Lifecycle
Service Lifecycle:
Service also have lifecycle methods
onCreate & onDestory, entire lifetime of the service.
onStart, service is running
service doesn't have a corresponding onStop method
Components Lifecycle
Service Lifecycle:
Components Lifecycle
Broadcast Receiver Lifecycle:
Broadcast receiver has on one lifecycle method
onReceive, when broadcast messaged arrive to the
receiver android calls onReceive with the intent
information
Components Lifecycle
LifeCycle Methods:
Important, when you implement lifecycle method,
don't forget to call super.on<Method> first!
Components Lifecycle
content providers:
Content providers are activated when they're
targeted by a request from a ContentResolver
Will be discussed in later chapters
Key Points
Activity, UI related
Service, background process
Each as a life-cycle reflected in the class
methods.
Intent, start activity or service
Bionic
Bionic (cont)
Bionic (cont)
Bionic (cont)
Bionic - architectures
Bionic - pthread
You may use exceptions in pure C++ code but in some cases if
you call C code exceptions will be lost.
cutils
Android kernel
Binder
Binder - layers
Binder - design
ashmem - design
open(/dev/ashmem)
ASHMEM_SET/GET_NAME
ASHMEM_SET/GET_SIZE
ASHMEM_SET/GET_PROT_MASK
ASHMEM_PIN/UNPIN
ASHMEM_GET_PIN_STATUS
ASHMEM_PURGE_ALL_CACHES
ashmem cutils
Example:
fd = ashmem_create_region("my_shm_region", size);
if(fd < 0)
return -1;
data = mmap(NULL, size, PROT_READ | PROT_WRITE,
MAP_SHARED, fd, 0);
if(data == MAP_FAILED)
goto out;
pmem - design
open(/dev/pmem_{camera|adsp})
Ioctl it:
PMEM_GET_PHYS
PMEM_MAP
PMEM_UNMAP
PMEM_GET_SIZE
PMEM_ALLOCATE
PMEM_CONNECT
PMEM_GET_TOTAL_SIZE
PMEM_CACHE_FLUSH
logger design
The source is at
$ANDROID_KERNEL/drivers/staging/android/logger.{c,h}
The code supports 4 logging buffers, named "main",
"events", "radio", and "system" for different types of
events.
#include <linux/wakelock.h>
wake_lock_init(struct wakelock *lock, int type,
const char *name);
void wake_lock(struct wake_lock *lock);
void wake_lock_timeout(struct wake_lock *lock,
long timeout);
void wake_unlock(struct wake_lock *lock);
PowerManager pm = (PowerManager)
getSystemService(Context.POWER_SERVICE)
;
PowerManager.WakeLock
wl=pm.newWakeLock(PowerManager.SCREE
N_DIM_WAKE_LOCK, "My Tag");
wl.acquire();
..screen will stay on during this section..
wl.release();
Lowmemorykiller
alarm
$ANDROID_KERNEL/drivers/staging/android/time
d_{gpio,output}.{c,h}
Allows user space to access GPIO registers.
Sort of uncomplicated driver in user space
solution.
Controversy also surrounds this API because it
gives too much power to user space.
The timed version ensures that the register value
returns to it's original state after a certain time has
passed and is considered safer to use.
ram_console
/dev/pts devpts
/proc proc
/sys sys
/dev/cpuctl cgroup
/sdcard vfat
SD card storage.
Preferences system.
Cache.
Content providers.
This is also why some basic applications cannot be removed (so that
users don't loose their contacts/photos/videos by mistake).
SD card access
SD card access
The cache
SD card.
Content providers.
Android init
Android initialization
ueventd
Configuration is in $ROOT/ueventd.rc
Advanced
JNI
Java Native Interface
Advanced JNI
Copyright 2003-2004 InterBit LTD.
Chapter Contents
JNI Recap
Local & Global References
Memory Management & GC
Threads
Handling Exceptions
Encoding & Internationalization
Ten JNI Best Practices
Advanced JNI
202
JNI Recap
JNI allows Java code to operate with
applications and libraries written in
other languages, such as C, C++, and
assembly.
Advanced JNI
203
JNI Recap
Advanced JNI
204
205
Java Type
Native Type
Size in bits
boolean
jboolean
8, unsigned
byte
jbyte
char
jchar
16, unsigned
short
jshort
16
int
jint
32
long
jlong
64
float
jfloat
32
double
jdouble
64
void
void
n/a
Advanced JNI
206
Advanced JNI
207
Example:
public
public native
native String
String
loopPrint(String
loopPrint(String name,int
name,int num)
num)
JNIEXPORT
JNIEXPORT jstring
jstring JNICALL
JNICALL
Java_MyClass_loopPrint(JNIEnv*,jobject
Java_MyClass_loopPrint(JNIEnv*,jobject
,jstring,
,jstring, jint)
jint)
Advanced JNI
208
Chapter Contents
JNI Recap
Local & Global References
Threads
Handling Exceptions
209
Local references
Global references
Weak global references
Advanced JNI
210
Local References
Advanced JNI
211
//this
//this is
is wrong
wrong
{{
stringClass
stringClass == (*env)->findClass(env,
(*env)->findClass(env, java/lang/String);
java/lang/String);
if
if (stringClass
(stringClass ==
== NULL)
NULL)
{{
return
return NULL;
NULL;
}}
}}
cid
cid == (*env)->GetMethodID(env,
(*env)->GetMethodID(env, stringClass
stringClass ...
...
Advanced JNI
212
jcharArray
jcharArray elemArr
elemArr == (*env)NewCharArray(env,
(*env)NewCharArray(env, len);
len);
result
result == (*env)->NewObject
(*env)->NewObject (env,
(env, stringClass,
stringClass, cid,
cid, elemArr);
elemArr);
(*env)->DeleteLocalRef(env,
(*env)->DeleteLocalRef(env, elemArr);
elemArr);
Advanced JNI
213
Global References
Advanced JNI
214
//this
//this is
is OK
OK now
now
{{
jclass
jclass localRefClass
localRefClass == (*env)->findClass(env,
(*env)->findClass(env, java/lang/String);
java/lang/String);
stringClass
stringClass == (*env)->NewGlobalRef(env,
(*env)->NewGlobalRef(env, localRefClass);
localRefClass);
(*env)->DeleteLocalRef(env,
(*env)->DeleteLocalRef(env, localRefClass);
localRefClass);
if(stringClass==NULL){
if(stringClass==NULL){
return
return NULL;
NULL;
//free
//free local
local reference
reference
Creates a global
reference
}}
}}
cid
cid == (*env)->GetMethodID(env,
(*env)->GetMethodID(env, stringClass
stringClass ...
...
Advanced JNI
215
Advanced JNI
216
//free
//free local
local reference
reference
}}
cid
cid == (*env)->GetMethodID(env,
(*env)->GetMethodID(env, stringClass
stringClass ...
...
Creates a weak
global reference
Advanced JNI
217
Chapter Contents
JNI Recap
Local & Global References
Threads
Handling Exceptions
218
Memory Management
Advanced JNI
219
Memory Management
220
Lifetime functions
221
EnsureLocalCapcaity - Example
Suppose we need to create objects in a loop:
if((*env)->EnsureLocalCapacity
if((*env)->EnsureLocalCapacity (env,
(env, len))
len)) << 0){
0){
//this
//this is
is an
an OutOfMemory
OutOfMemory situation
situation
}}
for
for (i=0;i<len;i++){
(i=0;i<len;i++){
jstring
jstring jstr
jstr == (*env)->GetObjectArrayElement(env,arr,
(*env)->GetObjectArrayElement(env,arr, i);
i);
//DeleteLocalRef
//DeleteLocalRef is
is not
not necessary
necessary here
here
}}
Advanced JNI
222
223
EnsureLocalCapcaity - Example
Suppose we need to create objects in loop:
#define
#define NUMBER_OF_REFERENCES
NUMBER_OF_REFERENCES 30
30
...
...
for(i=o;i<len;i++){
for(i=o;i<len;i++){
if
if ((*env)->PushLocalFrame
((*env)->PushLocalFrame (env,
(env, NUMBER_OF_REFERENCES)
NUMBER_OF_REFERENCES) << 0){
0){
//out
//out of
of memory
memory
}}
jstr
jstr == (*env)->GetObjectArrayElement
(*env)->GetObjectArrayElement (env,
(env, arr,
arr, i);
i);
...work
...work with
with jstr
jstr
(*env)->PopLocalFrame(env,
(*env)->PopLocalFrame(env, NULL);
NULL);
}}
Advanced JNI
224
Advanced JNI
225
Advanced JNI
226
Advanced JNI
227
}}
}}
jstr
jstr == (*env)->GetObjectField(env,
(*env)->GetObjectField(env, obj,
obj, field_id);
field_id);
...
...
228
Chapter Contents
JNI Recap
Local & Global References
Threads
Handling Exceptions
229
JNI &Threads
Advanced JNI
230
Thread Constrains
Advanced JNI
231
synchronized(obj){
synchronized(obj){
..protected
..protected code
code goes
goes here
here
}}
232
233
void
void JNU_MonitorWait
JNU_MonitorWait (JNIEnv
(JNIEnv *env,
*env, jobject
jobject object,
object, jlong
jlong timeout){
timeout){
(*env)->CallVoidMethod(env,object,
(*env)->CallVoidMethod(env,object, MID_Object_wait,
MID_Object_wait, timeout);
timeout);
}}
234
Thread Models
Advanced JNI
235
Thread Models
Advanced JNI
236
Chapter Contents
JNI Recap
Local & Global References
Threads
Handling Exceptions
237
Exceptions Handling
Advanced JNI
238
Exceptions Handling
A pending exception raised through JNI does
not immediately disrupt the native method
execution.
Notice This behavior is different from
exceptions behavior in Java immediate
transfer of the flow control to the catch block.
Advanced JNI
239
Exceptions Handling
240
//error
//error occurred
occurred
}}
Advanced JNI
241
Use ExceptionOccurred
(*env)->CallVoidMethod(env,
(*env)->CallVoidMethod(env, obj,
obj, mid);
mid);
exc
exc == (*env)->ExceptionOccurred(env);
(*env)->ExceptionOccurred(env);
if
if (exc)
(exc) {{
jclass
jclass newExcCls;
newExcCls;
(*env)->ExceptionDescribe(env);
(*env)->ExceptionDescribe(env);
(*env)->ExceptionClear(env);
(*env)->ExceptionClear(env);
newExcCls
newExcCls == (*env)->FindClass(env,"java/lang/IllegalArgumentException");
(*env)->FindClass(env,"java/lang/IllegalArgumentException");
if
if (newExcCls
(newExcCls ==
== 0)
0) {{
return;
return;
}}
(*env)->ThrowNew(env,
(*env)->ThrowNew(env, newExcCls,
newExcCls, "thrown
"thrown from
from CC code");
code");
}}
Advanced JNI
242
Exceptions Handling
When the native code catches and handles an
exception, it can either:
243
Exceptions Handling
Functions for checking exceptions:
ExceptionCheck(env) returns JNI_TRUE when
there is a pending exception (or JNI_FALSE).
ExceptionOccured(env) Returns a reference to
jboolean
== (*env)->ExceptionCheck(env);
jboolean
hasException
(*env)->ExceptionCheck(env);
thehasException
exception
objec.t
jthrowable
jthrowable exc
exc == (*env)->ExceptionOccurred(env);
(*env)->ExceptionOccurred(env);
*hasException
*hasException == exc
exc !=
!= NULL;
NULL;
(*env)->DeleteLocalRef(env,
(*env)->DeleteLocalRef(env, exc);
exc);
//local
//local reference
reference management
management
Advanced JNI
244
Chapter Contents
JNI Recap
Local & Global References
Threads
Handling Exceptions
245
246
Advanced JNI
id of the String
247
char
char ** JNU_GetStringNativeChars
JNU_GetStringNativeChars (JNIEnv
(JNIEnv ** env,
env, jstring
jstring jstr)
jstr)
{{
jbyteArray bytes = 0;
jbyteArray bytes = 0;
char
char ** result
result == 0;
0;
bytes
bytes == (*env)->CallObjectMethod(env,
(*env)->CallObjectMethod(env, jstr,
jstr, MID_String_getBytes);
MID_String_getBytes);
jint
jint len
len == (*env)->GetArrayLength(env,
(*env)->GetArrayLength(env, bytes);
bytes);
result
result == (char*)malloc(len+1);
(char*)malloc(len+1);
(*env)->GetByteArrayRegion(env,bytes,0,len,(jbyte*)result);
(*env)->GetByteArrayRegion(env,bytes,0,len,(jbyte*)result);
result[len]
result[len] == 0;
0; /*Null
/*Null termination*/
termination*/
return
return result;
result;
}}
Advanced JNI
248
Advanced JNI
249
Advanced JNI
250
251
Chapter Contents
JNI Recap
Local & Global References
Threads
Handling Exceptions
252
Advanced JNI
253
Advanced JNI
254
Advanced JNI
255
Advanced JNI
256
257
Advanced JNI
258
Advanced JNI
259
Advanced JNI
260
Advanced JNI
261
Advanced JNI
262
Key Points
JNI enables a JVM-independent
integration of Java and native code.
Exception handling.
Multiple threads.
Memory management.
Encoding issues.
Advanced JNI
263