android: quick dive - amberfogvk.amberfog.com/devfest/android_quick_dive.pdf · • transform class...

Post on 15-May-2020

1 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Russia, 16-18 November 2012

Android: Quick dive

Dmitry Lukashev

Android Engineer

Agenda

• History & Architecture overview

• Android building blocks

• Manifest, system services, NDK

• Activities & Fragments

• Layouts

• Debugging tools

• Publishing & money

2

Where to start

• http://d.android.com/ – developers portal

• http://tools.android.com/ – tools project

• http://s.android.com/ – source page

• http://b.android.com/ – bugz

• http://r.android.com/ – source patches reviews

• http://a.android.com/ – ADK

• http://android-developers.blogspot.com/

3

Where to start (cont.)

4

Development

• Eclipse, IntelliJ Idea, Netbeans, Notepad, etc.

• Emulator + x86

6

Various screen configurations available from

emulator

7

Android Trainings

http://developer.android.com/training/index.html

• Activity lifecycle

• Supporting multiple languages

• Supporting different screens and platform versions

• Fragments

• Custom views

• Effective navigation

• LruCache, DiskLruCache

• ViewPager

• And more…

8

ADB

• Install/Uninstall apps, port forwarding, scripting, files

management

• Shell

• adb shell ls /system/bin

• adb kill-server

DDMS

• Threads info

• VM Heap info

• Allocation Tracker

• System info

• Emulator control

• Screen capture

• File Explorer

10

Sep 2008

1.0 Mar 2009

1.1 1.5

May 2009

1.6

Sep 2009

2.0

Oct 2009

2.0.1

Dec 2009

2.1

Jan 2010

2.2

May 2010

Cupcake Donut

Éclair

Froyo

• Jul 2005 – Google acquired Android Inc. (co-founded by

Andy Rubin)

• Nov 2007 – Google Android presentation and ―early look‖

release

"Astro" and "Bender"

Soft Keyboard Widgets

Voice Search WVGA

Accounts Multi-touch

Live wallpapers

HTC G1

HTC Magic

Nexus One JIT, C2DM, Flash Tethering, V8

Android History (cont.)

13

2.3

Dec 2010

Gingerbread

UI, NFC, SIP, VP8, gyroscope

Nexus S

3.0

Feb 2011

Honeycomb

Tablets

3.1

ADT – ported to 2.3.4 Resizable widgets

May 2011

3.2

May 2011

Comparability display mode

4.0

Oct 2011

Ice Cream Sandwich

New UI virtual buttons Android Beam Phone + Tablet

Roboto

Galaxy Nexus

Android History (cont.)

14

4.2

Project Butter Extended Notifications

Google Now

Nov 2012

4.1

Jul 2012

RenderScript -> GPU Lock screen widgets

Daydream External displays

Key Lime Pie?

Nexus 4 Nexus 10

Nexus 7

Android History (cont.)

15

November 2012

Android Fragmentation

16

Java Reflection

• Originally used to inspect classes, interfaces, fields and methods at

runtime, without knowing the names of them at compile time. It can be

used for observing and/or modifying program execution at runtime

• Classes: Class, Method, Field, Constructor, etc.

method.invoke(foo, null);

17

Android support libraries

• v4

• V13 (includes v4)

• Support nested Fragments (v4 rev. 11)

• NotificationCompat (v4 rev. 10)

• NavUtils (v4 rev. 9) – up navigation functionality

18

Android Architecture Overview

Linux Kernel

Display Driver

Keypad Driver

Camera Driver

WiFi Driver

Flash Memory Driver

Audio Drivers

Binder (IPC) Driver

Power Management

Libraries

Surface Manager Media Framework

OpenGL | ES FreeType

SQLite

WebKit

SGL SSL libc

Android Runtime

Core Libraries

Dalvik VM

Application Framework

Activity Manager

Package Manager

Window Manager

Telephony Manager

Content Providers

Notification Manager

View System

Location Manager

Resource Manager

Applications

Home Contacts Phone Browser …

ND

K /

JN

I

19

Dalvik VM

• Was written by Dan Bornstein

• Transform class files into DEX

• It is VM…

– integrated with Linux

– uses shared memory, mmap

– for OS without swap space

– while powered by a battery

– zygote

• The Dalvik VM is register-based: fewer

instructions, code units, instructions

• Verification & optimization at installation

time Give me your huddled bytecodes

yearning to run free. And I lift

the light beside the coder’s door

20

JIT (since Android 2.2)

• Translates byte code to optimized native code at run time

• Part of the open source

• Trace JIT vs Method JIT

• Trace JIT – Minimizing memory usage critical for mobile devices

(100K)

– Important to deliver performance boost quickly

– Trace request is built during interpretation

– Compiled traces chained together in translation cache

– Per process translation cache

• Leave open the possibility of supplementing with method-based JIT

21

Android Application Building Blocks

• Activity – Presents UI

– Each Activity is independent screen

– Activity: setContentView(View)

• Service – Used for background operations

• BroadcastReceiver – Receive and process broadcast system or user events

• ContentProvider – Share application data with others

– Data can be stored in FS, DB or even in memory

– Communicate via ContentResolver

• Intent – Used to activate Activities, Services & BroadcastReceivers

– Sticky Intents - persists the values associated with their last broadcast

+LocalBroadcastManager

22

AndroidManifest.xml

23

AndroidManifest.xml (cont.)

24

AndroidManifest.xml (cont.)

25

</manifest>

AndroidManifest.xml (cont.)

26

Security

• Permissions

• android:sharedUserId

• android:exported=false by default since 4.2

• Read more here

https://developers.google.com/events/io/session

s/gooio2012/107/

27

Activities and Tasks

• An Activity is a ―molecule‖ – a discrete chunk of

functionality

• A Task is a collection of Activities (own UI history

stack, capable of spanning multiple processes) –

is what the user experiences as an "application"

• A Process is a standard Linux process (one VM

per process)

28

Activities and Tasks (cont.)

.apk package .apk package

Process

Service

Process

ContentProvider

Service

Process

Activity Activity Task

Activity

Activity

ContentProvider

Task

29

Android Process

• Android process == Linux process

• adb shell ps -t

• By default: 1 process per APK, 1 thread per process

• Remains running until killed by the system

• The component elements — <activity>, <service>, <receiver>, and <provider> — each have a process attribute that can specify a process where that component should run

• Private process – new thread, same VM

30

Activities and Tasks (cont.)

Task

Start Activity (e.g. LAUNCHER)

Activity 1 (1)

GMap Activity

Activity 1 (2)

BACK

HOME

FLAG_ACTIVITY_NEW_TASK FLAG_ACTIVITY_CLEAR_TOP FLAG_ACTIVITY_RESET_TASK_IF_NEEDED FLAG_ACTIVITY_SINGLE_TOP

Intent flags

taskAffinity launchMode allowTaskReparenting clearTaskOnLaunch alwaysRetainTaskState finishOnTaskLaunch

<activity> attributes

31

New Task

Task

Activity 1

Activity 2 BACK

HOME

taskAffinity=com.gtug.task1

startActivity( );

NEW_TASK

Task

Activity 3 affinity=com.gtug.task2

BACK

HOME

taskAffinity=com.gtug.task2

32

View Activity/Task/Process details

• adb shell dumpsys >> dump.txt

Activities in Current Activity Manager State:

* TaskRecord{43ddd1e8 #10 A com.test.xxx} clearOnBackground=false numActivities=1 rootWasReset=false affinity=com.test.xxx intent={flg=0x10000000 cmp=com.test.TestUI/.Activity1} realActivity=com.test.TestUI/.Activity1 lastActiveTime=15088595 (inactive for 5s)

* Hist #4: HistoryRecord{43ddd000 com.test.TestUI/.Activity1} packageName=com.test.TestUI processName=com.gtug.test123123

launchedFromUid=10025 app=ProcessRecord{43d5a1a8 293:com.gtug.test123123/10025} Intent { flg=0x10000000 cmp=com.test.TestUI/.Activity1 } frontOfTask=true task=TaskRecord{43ddd1e8 #10 A com.test.xxx}

taskAffinity=com.test.xxx realActivity=com.test.TestUI/.Activity1 base=/data/app/com.test.TestUI.apk/data/app/com.test.TestUI.apk data=/data/data/com.test.TestUI labelRes=0x7f040001 icon=0x7f020000 theme=0x0 stateNotNeeded=false componentSpecified=true isHomeActivity=false configuration={ scale=1.0 imsi=310/260 loc=en_US touch=3 keys=2/1/2 nav=3/1 orien=1 layout=18} launchFailed=false haveState=false icicle=null state=RESUMED stopped=false delayedResume=false finishing=false keysPaused=false inHistory=true persistent=false launchMode=0 fullscreen=true visible=true frozenBeforeDestroy=false thumbnailNeeded=false idle=true

33

Activity Graph of Life

Start

Stop

onCreate() onStart()

onResume()

onRestart()

onDestroy()

onPause()

onStop()

Kill process

Running

partly visible

foreground

no longer visible

foreground

onPostCreate ()

onPostResume()

34

Fragments

35

36

Dealing with UI-thread

• Main application thread

• Responsible for drawing and received UI callbacks

• Long operations on UI thread cause ANR

• State of UI elements should be changed only on UI

thread

• ListView adapters should be filled on UI thread

• Run AsyncTask on UI thread

• Use Strict Mode (2.3+)

37

Dealing with UI-thread

• Activity.runOnUiThread(Runnable)

• View.post(Runnable)

• View.postDelayed(Runnable, long)

• Handler

• AsyncTask (API > 12 – keeps order)

– UI: onPreExecute()

– WR: doInBackground()

– WR: publishProgress() – UI: onProgressUpdate()

– UI: onPostExecute()

• android.app.IntentService

38

Android User Interface

• UI is build using View and ViewGroup

• View is base for widgets

• ViewGroup is base for layouts

• setContentView() – attach the view hierarchy tree to the

screen for rendering

• Drawing is two pass process:

– measuring pass

– layout pass ViewGroup

ViewGroup View View

View View View

39

Layouts

• Declare layouts in two ways:

– Declare UI elements in XML

– Instantiate layout elements at runtime

• Attributes

• ID

– android:id="@+id/my_button―

– android:id=―@id/empty―

• setContentView(R.layout.main_layout);

findViewById(R.id.my_button);

40

Layout Parameters

• layout_something – layout parameter

• Every ViewGroup class implements a nested class that

extends ViewGroup.LayoutParams

• layout_width and layout_height are

required for all view groups

LinearLayout

RelativeLayout View View LinearLayout. LayoutParams

LinearLayout. LayoutParams

View RelativeLayout. LayoutParams

View RelativeLayout. LayoutParams

View RelativeLayout. LayoutParams

LinearLayout. LayoutParams

41

Common Layout Objects

• FrameLayout

• LinearLayout

• TableLayout

• RelativeLayout

• GridLayout (API 14)

42

FrameLayout

</FrameLayout>

43

LinearLayout

• Orientation: vertical, horizontal

• Weight attribute – ―importance‖ value of a view. Default

weight is zero.

0 0 weight = 1

wrap_content for all views

0 1 1

0 1 1

0 1 2

wrap_content for all views

wrap_content, 0dp, 0dp

wrap_content, 0dp, 0dp

0 1 2

wrap_content for all views 44

TableLayout

• TableLayout positions its children into rows and columns

• stretchColumns – zero-based index of the columns to

stretch

/TableRow> </TableLayout>

45

RelativeLayout

• RelativeLayout lets child views specify their position

relative to the parent view or to each other (specified by

ID)

<LinearLayout

xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="fill_parent"

android:layout_height="?android:attr/listPreferredItemHeight"

android:padding="6dp">

<ImageView … />

<LinearLayout

android:orientation="vertical" …>

<TextView … />

<TextView … />

</LinearLayout>

</LinearLayout>

way 1

<RelativeLayout ... >

<ImageView

android:id="@+id/icon“ …

android:layout_alignParentTop="true"

android:layout_alignParentBottom="true" … />

<TextView

android:id="@+id/secondLine" ….

android:layout_toRightOf="@id/icon"

android:layout_alignParentBottom="true"

android:layout_alignParentRight="true" …/>

<TextView

android:layout_toRightOf="@id/icon"

android:layout_alignParentRight="true"

android:layout_alignParentTop="true"

android:layout_above="@id/secondLine"

android:layout_alignWithParentIfMissing="true' … />

</RelativeLayout>

better way 46

RelativeLayout (cont.)

LinearLayout RelativeLayout 47

GridLayout (API 14)

48

Devices and Displays

49

50

Supporting Multiple Screens

• Screen size: small, normal, large, xlarge

• Screen density: low, medium, high, extra high

• Orientation: landscape, portrait

• Resolution

• Density-independent pixel (dp)

px = dp * (dpi / 160)

xlarge screens are at least 960dp x 720dp large screens are at least 640dp x 480dp normal screens are at least 470dp x 320dp small screens are at least 426dp x 320dp

51

Qualifiers

52

Since 3.2

Screen configuration Qualifier values Description

smallestWidth

sw<N>dp sw600dp sw720dp

You can use this qualifier to ensure that, regardless of the screen's current orientation, your application's has at least <N> dps of width available for it UI.

Available screen width

w<N>dp w720dp w1024dp

Specifies a minimum available width in dp units at which the resources should be used—defined by the <N> value.

Available screen height

h<N>dp h720dp h1024dp

Specifies a minimum screen height in dp units at which the resources should be used—defined by the <N> value.

53

Screen Sizes and Densities

54

October 2012

Nexus 7

Nexus 10

add a 144*144px icon in the drawable-xxhdpi

or drawable-480dpi folder

Do not duplicate layouts

55

ADT21

56

Android System Services

Object getApplicationContext().getSystemService(String serviceName)

serviceName value

(contsants in Context)

Service Class name Description

WINDOW_SERVICE WindowManager Controls on-screen windows and

their parameters

LAYOUT_INFLATER_SERVI

CE

LayoutInflater Inflates layout resources

POWER_SERVICE PowerManager Controls power management

NOTIFICATION_SERVICE NotificationManager Status bar notifications

CONNECTIVITY_SERVICE ConnectivityManager Handling network connections

WIFI_SERVICE WifiManager Handling Wi-Fi network status

TELEPHONY_SERVICE TelephonyManager Handling phone calls states

LOCATION_SERVICE LocationManager Controls location (GPS) updates

SENSOR_SERVICE SensorManager Controls sensor

… … … 57

Notifications

58

• Big content view

• Priority

• Actions

• BigPictureStyle

• InboxStyle

Saving State of Android Application

• Shared Preferences are stored in the application private data space and can be shared only inside this Application, but between launches and versions

• Instance of SharedPreferences class should be obtained:

• To read:

• To write:

• SharedPreferences.OnSharedPreferenceChangeListener

59

Backup Application Data (android.app.backup – 2.2)

• Perform backup arbitrary data to remote “cloud” storage • Easily perform backup of SharedPreferences and files • Restore the data saved to remote storage • Controlled by Android Backup Manager

– Extend class BackupAgent and override onBackup() & onRestore() OR – Extend BackupAgentHelper to backup/restore SharedPreferences and

files from internal storage – Add your agent to AndroidManifest.xml

• BackupManager.dataChanged()/requestRestore() • New bmgr tool for testing

http://developer.android.com/guide/developing/tools/bmgr.html • Full guide with examples:

http://developer.android.com/guide/topics/data/backup.html

60

Android NDK (Native Development Kit)

• Provides ability and tools to embed components that make use of native code in Android applications

• Supports only restricted set of native libraries:

– libc (C library) headers

– libm (math library) headers

– JNI interface headers

– libz (Zlib compression) headers

– liblog (Android logging) header

– OpenGL ES 1.1 (since 1.6) and OpenGL ES 2.0 (3D graphics libraries, since 2.0) headers

– libjnigraphics (Pixel buffer access) header (since 2.2)

– A Minimal set of headers for C++ support

• NativeActivity (since 2.3)

• For Windows Cygwin 1.7 (or higher) is needed

61

GCM

• No limits

• Payloads up to 4K

• Multicasting

• Metrics

• Library

62

Debugging tools

• Android Debug Bridge (ADB)

• Dalvik Debug Monitor Server (DDMS) -> Monitor

• Traceview

• logcat

• Lint

• Tracer for OpenGL ES

• DevTools

• SpareParts

• AXMLPrinter2

• dex2jar + jd

• MAT

• Monkey

• Design preview http://code.google.com/p/android-ui-utils/

• UI Automator Viewer

63

Use Lint

64

Performance Analysis: Traceview

65

Test UI (API 16+, ADT 21)

• uiautomatorviewer - A GUI tool to scan and

analyze the UI components of an Android

application.

• uiautomator - A Java library containing APIs to

create customized functional UI tests, and an

execution engine to automate and run the tests.

66

Publishing and $$$?

• Idea

• Design

• Sell

• In-App purchase

• Subscription

• Ads

https://play.google.com/

http://www.admob.com/

68

Contacts

Dmitry Lukashev

http://ru.linkedin.com/in/dmitrylukashev

Blog - http://android.amberfog.com/

69

Russia, 16-18 November 2012

Thank You! Questions?

top related