Android Component Model

44
7/31/2019 Android Component Model http://slidepdf.com/reader/full/android-component-model 1/44 Android Application Model Component Model for Mobile Applications Dominik Gruntz University of Applied Sciences Northwestern Switzerland, Brugg-Windisch 8925

Transcript of Android Component Model

Page 1: Android Component Model

7/31/2019 Android Component Model

http://slidepdf.com/reader/full/android-component-model 1/44

Android Application ModelComponent Model for Mobile Applications

Dominik Gruntz

University of Applied Sciences Northwestern Switzerland, Brugg-Windisch8925

Page 2: Android Component Model

7/31/2019 Android Component Model

http://slidepdf.com/reader/full/android-component-model 2/44

2

IntroductionAndroid Experience> Android Core Libraries (together with Noser)

> Android Projects – HikeTracker [swisstopo] – SyncML Addressbook Synchronizer

[Swisscom]

Component Software Experience> Responsible for the Java

Chapter of the Book on

"Component Software"

Page 3: Android Component Model

7/31/2019 Android Component Model

http://slidepdf.com/reader/full/android-component-model 3/44

3

AGENDAAndroid Components> Activities

– Intents & Filters – Task / Application – Lifecycle

– Processes and Threads> Services> Content Providers

Page 4: Android Component Model

7/31/2019 Android Component Model

http://slidepdf.com/reader/full/android-component-model 4/44

4

Android Software Stack> Java

> C/C++

> Kernel

Page 5: Android Component Model

7/31/2019 Android Component Model

http://slidepdf.com/reader/full/android-component-model 5/44

5

Android ComponentsActivity [User Interaction]> UI component typically corresponding to a screen

– E.g. Contacts: 3 activities: View contacts, Send message, Edit contactService [Service Provider]> Background process without UI (e.g. mp3 player)

– Messages can be sent from and to a serviceContent Provider [Data Provider]> Enables applications to share data

– E.g. Contacts are provided to all applicationsBroadcast Receiver [System Event Listener]> Responds to external events, can wake up your process

– Phone rings, network activity established, time controlled

Page 6: Android Component Model

7/31/2019 Android Component Model

http://slidepdf.com/reader/full/android-component-model 6/44

6

ActivityActivity is usually a single screen> Implemented as a single class extending Activity

> Displays user interface controls (views)> Reacts on user input / events

An application typically consists of

several activities> Each screen is typically implemented by

one activity> Moving to the next screen means

starting a new activity> An activity may return a result to

the previous activity

Page 7: Android Component Model

7/31/2019 Android Component Model

http://slidepdf.com/reader/full/android-component-model 7/44

7

IntentsIntent> Intents are used to move from activity to activity

> Intent describes what the application wants to do> Consists of

– Action to be performed (MAIN / VIEW / EDIT / PICK / DELETE / …) – Categories

– Data to act on (URI) – Extras (primitives / primitives[] / Strings / Serializable) – Flags Intent intent = new Intent(Intent.ACTION_VIEW);

intent.setData(Uri.parse("http://www.fhnw.ch"));

Intent intent = new Intent(Intent.ACTION_EDIT);intent.setData(Uri.parse("content://contacts/people/1"));

Page 8: Android Component Model

7/31/2019 Android Component Model

http://slidepdf.com/reader/full/android-component-model 8/44

8

IntentsIntent Invocation> Launch new activity (without receiving a result)

> Launch new activity and expect result

– When activity exits, onActivityResult method is called with givenrequestCode (int > 0)onActivityResult(int requestCode, int resultCode, Intent result)

startActivity(intent);

startActivityForResult(intent, requestCode)

Page 9: Android Component Model

7/31/2019 Android Component Model

http://slidepdf.com/reader/full/android-component-model 9/44

9

IntentsIntent Specification> Intents define the interface between components

> Intent repository on www.openintents.org

Page 10: Android Component Model

7/31/2019 Android Component Model

http://slidepdf.com/reader/full/android-component-model 10/44

10

Intents and Intent FiltersIntent Filters> Description of what intents an activity can handle

> Activities publish their intent filters in a manifest file

> Upon invocation of startActivity(intent) thesystem looks at the intent filters of allinstalled applications

<intent-filter android:priority="0"><action android:name="android.intent.action.VIEW"/><category android:name="android.intent.category.DEFAULT"/><category android:name="android.intent.category.BROWSABLE"/><data android:scheme="geo"/>

</intent-filter>

Page 11: Android Component Model

7/31/2019 Android Component Model

http://slidepdf.com/reader/full/android-component-model 11/44

11

Android Component ModelComponent Software> Activities can reuse functionality from other

components simply by making a requestin form of an Intent

> Activities can be replaced at any timeby a new Activity with an equivalentIntent Filter

Intent i = new Intent("com.google.android.radar.SHOW_RADAR");

i.putExtra("latitude", 47.6f);i.putExtra("longitude", 8.23f);startActivity(i);

Page 12: Android Component Model

7/31/2019 Android Component Model

http://slidepdf.com/reader/full/android-component-model 12/44

12

Android Component ModelAndroid Market: Software Libraries> Radar

> HighScore List> Text-To-Speech Library> Log Collector

– Includes standalone app

Page 13: Android Component Model

7/31/2019 Android Component Model

http://slidepdf.com/reader/full/android-component-model 13/44

13

Android Component ModelPackaging: APK File (Android Package)> Collection of components

> Components share a set of resources – Preferences, Database, File space

> Components share a Linux process – By default, one process per APK

> APKs are isolated – Communication via Intents or AIDL

> Every component has a managed lifecycle

APK

Process

Activity Activity

Content Provider

Service

Page 14: Android Component Model

7/31/2019 Android Component Model

http://slidepdf.com/reader/full/android-component-model 14/44

14

Task / Application / ProcessTask (what users know as applications)> Collection of related activities

> Capable of spanning multiple processes> Associated with its own UI history stack

APK

Process

Activity Activity

Content Provider

Service

APK

Process

Activity Activity

Content Provider

Service

Page 15: Android Component Model

7/31/2019 Android Component Model

http://slidepdf.com/reader/full/android-component-model 15/44

15

Task / Application / ProcessTasks> Processes are started & stopped as needed

> Processes may be killed to reclaim resources> Upon Invocation of another activity, the view state can be saved

> Comparable with EJB's stateful session beans (SFSB)> Each Android component has a managed lifecycle

Home Inbox Details Browse MapsInbox Details

Page 16: Android Component Model

7/31/2019 Android Component Model

http://slidepdf.com/reader/full/android-component-model 16/44

16

Activity Life CycleActive / Running> Activity is in foreground

> Activity has focus

Paused> Still visible, partially overlaid

> Focus lost

Stopped> Activity is not visible

Destroyed> Activity was terminated or killed

New

Running

PausedStopped

Destroyed

onCreate()onStart()[onRestoreInstanceState()]

onResume()onSaveInstanceState()onPause()

onRestart()onStart()onResume()

onStop()

onDestroy()

<<kill>>

<<kill>>

onResume()

onPause()onStop()onDestroy()

Page 17: Android Component Model

7/31/2019 Android Component Model

http://slidepdf.com/reader/full/android-component-model 17/44

17

Activity Life Cycle (1/2)onCreate> Called when activity is first created (with null parameter)

or when activity was killed (called with a bundle)> Initialization of viewsonRestart> Called when activity was stopped only

onStart> Activity becomes visible to user, animations could be startedonRestoreInstanceState> Restore view state

onResume> New activity is visible, TOS, camera might be used here

Page 18: Android Component Model

7/31/2019 Android Component Model

http://slidepdf.com/reader/full/android-component-model 18/44

18

Activity Life Cycle (2/2)onSaveInstanceState> Save UI state of a complex dialog

=> onCreate=> onRestoreInstanceState

> If application is explicitly finished, this method is not called> Called before or after onPauseonPause> Activity no longer TOS but still visible> New activity is not started until onPause returnsonStop

> Activity no longer visibleonDestroy> Release resources; it is not guaranteed that this method is called

Page 19: Android Component Model

7/31/2019 Android Component Model

http://slidepdf.com/reader/full/android-component-model 19/44

19

Activity Life Cycle Samples (1/2)Open Child Activity> onCreate(null) -> onStart -> onResume() -> [Open Child Activity]

> onSaveInstanceState() -> onPause() -> onStop() -> [Close Child Activity]> onRestart() -> onStart() -> onResume()Transparent View> onCreate(null) -> onStart -> onResume() -> [Open Transparent View]

> onSaveInstanceState() -> onPause() -> [Close Transparent View]> onResume()Turn Display> onCreate(null) -> onStart -> onResume() -> [Turn Display]> onSaveInstanceState() -> onPause() -> onStop() -> onDestroy()

-> onCreate() -> onStart() -> onRestoreInstanceState() -> onResume()

Page 20: Android Component Model

7/31/2019 Android Component Model

http://slidepdf.com/reader/full/android-component-model 20/44

20

Activity Life Cycle Samples (2/2)Home> onCreate(null) -> onStart -> onResume() -> [Home Button]

> onSaveInstanceState() -> onPause() -> onStop() -> [Start App]> onRestart() -> onStart() -> onResume()Phone Call Interrupt> onCreate(null) -> onStart -> onResume() -> [Phone Call]

> onSaveInstanceState() -> onPause() -> onStop() -> [Hang Up or press Back]> onRestart() -> onStart() -> onResume()

Page 21: Android Component Model

7/31/2019 Android Component Model

http://slidepdf.com/reader/full/android-component-model 21/44

21

Process / Thread

Threading Overview> Each process has one thread (by default)

=> Single Threaded ModelThreads and Loopers> Each thread has a Looper to handle a message queue> Events from all components are interleaved into the looper/Queue

APK Process Thread Looper

MessageQueueHandler

1 1 11

1

1

1*

Page 22: Android Component Model

7/31/2019 Android Component Model

http://slidepdf.com/reader/full/android-component-model 22/44

22

Process / Thread

ActivityThread> Manages the main thread in an application process

> Calls Looper.loop

Looper.loop

while(true){

Message m=queue.next();// may blockif(m!=null){

m.target.dispatch- Message(m);

m.recycle();}

}

APK

Process

Activity

Activity

IntentRecvr

Thread

Looper

Message

Queue

LocalService Calls

UI Events

System Events

Page 23: Android Component Model

7/31/2019 Android Component Model

http://slidepdf.com/reader/full/android-component-model 23/44

23

Process / Thread

Location Update in HikeTracker (onLocationChanged)

Page 24: Android Component Model

7/31/2019 Android Component Model

http://slidepdf.com/reader/full/android-component-model 24/44

24

Process / Thread

Activity Result call-back (onActivityResult)

Page 25: Android Component Model

7/31/2019 Android Component Model

http://slidepdf.com/reader/full/android-component-model 25/44

25

Process / Thread

Inactive Activities> If an activity does not consume events,

the system assumes that the activityhas a problem> AndroidNotResponding is shown

– No reaction to UI event within 5Sec

– No reaction to BroadcastEvent within 10Sec

Page 26: Android Component Model

7/31/2019 Android Component Model

http://slidepdf.com/reader/full/android-component-model 26/44

26

Dealing with Threads

checkRoot

> Compares current threadwith thread which createdthe view

button.setOnClickListener(new OnClickListener() {@Override

public void onClick(View v) {new Thread() {

@Override public void run() {

input1.setText("" + counter1++);}

}.start();}

});

Page 27: Android Component Model

7/31/2019 Android Component Model

http://slidepdf.com/reader/full/android-component-model 27/44

27

Dealing with Threads

Activity.runOnUiThread(Runnable)> Runs the specified action on the UI thread, i.e. the action is posted into the event

queue of the UI thread

Handler> Associated with a thread and its message queue

> Used to add messages in the message queue – sendMessage postRunnable – sendMessageAtFrontOfQueue postAtFrontOfQueue – sendMessageAtTime postAtTime

– sendMessageDelayed postDelayed> Used to handle the request (called by associated thread)

Page 28: Android Component Model

7/31/2019 Android Component Model

http://slidepdf.com/reader/full/android-component-model 28/44

28

Android Process & Security

Security Model> Each application runs in its own process

– Has its own unique Linux User ID – Each application has access to its own data

> Other resources are only available by defined interfaces – Services [exposes functionality] – Content Provider [exposes data]

USER PID PPID VSIZE RSS WCHAN PC NAMEroot 23 1 69508 18668 c008be9c afe0b874 S zygoteradio 87 23 100940 16320 ffffffff afe0c824 S com.android.phone

app_2 92 23 101792 17900 ffffffff afe0c824 S android.process.acoreapp_14 120 23 93772 11444 ffffffff afe0c824 S com.google.process.gappsapp_8 158 23 100088 11860 ffffffff afe0c824 S com.android.mmsapp_21 160 23 99740 13064 ffffffff afe0c824 S ch.fhnw.imvs.helloapp_0 175 23 90580 11116 ffffffff afe0c824 S com.android.alarmclockapp_3 183 23 94784 12080 ffffffff afe0c824 S android.process.media

Page 29: Android Component Model

7/31/2019 Android Component Model

http://slidepdf.com/reader/full/android-component-model 29/44

29

Android Processes

public class P1/P2 extends Activity {...

public void onStart(){super.onStart();Properties p = System.getProperties();System.out.println("getProperties().id = " +

System.identityHashCode(p));System.out.println("getProperties().size() = " + p.size());

if(p.get("Android") == null){ p.put("Android", 0); }else { p.put("Android", ((Integer)p.get("Android"))+1); }

System.out.println("P1/2: onStart " + p.get("Android"));

System.out.println("getProperties().size() = " + p.size());}

}

Page 30: Android Component Model

7/31/2019 Android Component Model

http://slidepdf.com/reader/full/android-component-model 30/44

30

Processes: Output

Output of Activity P1

Output of Activity P2

INFO/System.out(12470): getProperties().id = 1073834816

INFO/System.out(12470): getProperties().size() = 37INFO/System.out(12470): P1: onStart 0INFO/System.out(12470): getProperties().size() = 38

INFO/System.out(12504): getProperties().id = 1073834816INFO/System.out(12504): getProperties().size() = 37INFO/System.out(12504): P2: onStart 0INFO/System.out(12504): getProperties().size() = 38

Page 31: Android Component Model

7/31/2019 Android Component Model

http://slidepdf.com/reader/full/android-component-model 31/44

31

Android Processes

Zygote> Upon startup Zygote process is created which partially initializes a VM instance

– Core system libraries dex-files are loaded (mmap) – Dalvik VM is initialized and shared heap (which contains

objects used by all processes) is created> Upon start of an activity the Zygote process is forked

– Application specific dex files are loaded (mmap) – Application specific heap (and VM structures)

are initialized=> Core system libraries are shared! Zygote

SystemLibraries

Home

APKCode

Maps

APKCode

Page 32: Android Component Model

7/31/2019 Android Component Model

http://slidepdf.com/reader/full/android-component-model 32/44

32

Service

Characteristics> Execution of long running tasks and business logic outside an activity

– E.g. a background task that has to download data periodically> Services can explicitly be started and stopped> Communication with service

– In-process if service runs in same APK

– Inter-Process Communication across APKs (AIDL)

Page 33: Android Component Model

7/31/2019 Android Component Model

http://slidepdf.com/reader/full/android-component-model 33/44

33

Service

Explicit control> startService(intent)

– onCreate -> onStart> stopService(intent)

– onDestroy

Implicit control> bindService(intent, conn, flags)

– onCreate -> onBind> unbindService(conn)

– onUnbind

Page 34: Android Component Model

7/31/2019 Android Component Model

http://slidepdf.com/reader/full/android-component-model 34/44

34

Service Inter Process Communication

Binder> Bridges Kernel and Process space

> Proxy and Stub classes are generated from AIDL definitions

AIDL data types> Primitive types, String, CharSequence

> List, Map> AIDL generated interfaces> Parcelable classes

AIDL extensions> in, out, inout on parametres> oneway for asynchronous invocations

Page 35: Android Component Model

7/31/2019 Android Component Model

http://slidepdf.com/reader/full/android-component-model 35/44

35

Service Sample: AIDL Interface

interface ICounterService {long getCurrentValue();void setCounterListener(in ICounterListener l);

}

interface ICounterListener {void valueChanged(long value);

}

ICounterService

ICounterService.Stub

Binder

ICounterService.Stub.Proxy

CounterBinder

IBinder

Page 36: Android Component Model

7/31/2019 Android Component Model

http://slidepdf.com/reader/full/android-component-model 36/44

36

Service Sample: Manifest

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"

package="ch.fhnw.imvs.counter"

android:versionCode="1" android:versionName="1.0">

<application><service android:name=".CounterService" >

<intent-filter><action

android:name="ch.fhnw.imvs.counter.ICounterService"/></intent-filter>

</service></application>

</manifest>

Page 37: Android Component Model

7/31/2019 Android Component Model

http://slidepdf.com/reader/full/android-component-model 37/44

37

Service Sample: Invocation

Bind Service

Unbind Service

Intent start = new Intent("ch.fhnw.imvs.counter.ICounterService");

conn = new ServiceConnection() { public void onServiceConnected(ComponentName name, IBinder b) {ICounterService service = ICounterService.Stub.asInterface(b);service.setCounterListener(new ICounterListener.Stub() {

public void valueChanged(final long value) { … }});

}});

bindService(start, conn, Context.BIND_AUTO_CREATE);

unbindService(donn);

Page 38: Android Component Model

7/31/2019 Android Component Model

http://slidepdf.com/reader/full/android-component-model 38/44

38

Content Provider

Content Provider> The only way to share data between Android Packages

> Implements a standard set of methods to provide access to data> Any form of storage can be used

– SQLite DB – Files

– Remote Store

APK

Process

Activity Activity

Content Provider

APK

Process

Activity

Page 39: Android Component Model

7/31/2019 Android Component Model

http://slidepdf.com/reader/full/android-component-model 39/44

39

Content Provider

Content Provider Interface

abstract class ContentProvider { public Cursor query (Uri uri, String[] projection,

String selection, String[] selectionArgs,String sortOrder);

public Uri insert (Uri uri, ContentValues values) public int delete (Uri uri, String selection,

String[] selectionArgs);

String getType (Uri uri);

public int update (ContentURI uri,

ContentValues values, String selection,String[] selectionArgs)}

Page 40: Android Component Model

7/31/2019 Android Component Model

http://slidepdf.com/reader/full/android-component-model 40/44

40

Content Provider

Access to Data Providers> Comparable to a DB Access (Cursor)

> Identification via URI – content://contacts/phones

String[] projections = new String[]{"number", "name", "_id", "photo"};

Cursor cur = managedQuery(new ContentURI("content://contacts/phones"),

projections, null, "name ASC");

Page 41: Android Component Model

7/31/2019 Android Component Model

http://slidepdf.com/reader/full/android-component-model 41/44

41

Content Provider Sample

public class Provider extends android.content.ContentProvider { public static final android.net.Uri CONTENT_URI =

Uri.parse("content://ch.fhnw.imvs.fibonacci/numbers");

public static final String ID = BaseColumns._ID; public static final String VALUE = "value";

public boolean onCreate() { return true; }

public Cursor query(Uri uri, String[] projection,String selection, String[] selectionArgs, String sortOrder){

MatrixCursor c =new MatrixCursor(new String[]{ID,VALUE},10);for(int i=0; i<10; i++)

c.addRow(new Object[]{i, getNumber(i)});return c;

}

Page 42: Android Component Model

7/31/2019 Android Component Model

http://slidepdf.com/reader/full/android-component-model 42/44

42

Content Provider Sample Client

private void listFibonacciNumbers(){String[] projection = new String[]{BaseColumns._ID, "value"};Cursor cur = this.managedQuery(

Uri.parse("content://ch.fhnw.imvs.fibonacci/numbers"), projection, null, null, null);

cur.moveToFirst();do {

log.append(String.format("fib(%s) = %s",cur.getString(0), cur.getString(1)));

log.append("/n");} while (cur.moveToNext());

}

Page 43: Android Component Model

7/31/2019 Android Component Model

http://slidepdf.com/reader/full/android-component-model 43/44

43

Android Application Model: Summary

Scalability> Model well suited for mobile devices

– Optimized memory usage – Linux-based Security Model

Component Model

> Interesting programming model> Existing activities may be reused / extended

Page 44: Android Component Model

7/31/2019 Android Component Model

http://slidepdf.com/reader/full/android-component-model 44/44

Dominik GruntzUniversity of Applied Sciences [email protected]

Steinackerstrasse 55210 Windisch / Switzerland