Professional Documents
Culture Documents
Dmitry Lukashev
What is the plan? History & Architecture overview Android building blocks Manifest, system services, NDK Activities & Fragments Layouts Debugging tools Publishing & money
Where to start
http://android-developers.blogspot.com/
Info
http://java.oracle.com
http://twitter.com/retomeier
http://commonsware.com/Android/
https://plus.google.com/108 967384991768947849
http://www.google.com/events/io/2011/
Training 2010
Java +Android
(basics) JVM, GC, Threads, SDK, NDK, Activity, Code style, etc.
Android UI
Layouts, ListView, Menu, Dialog, Widgets, Tips & tricks, etc.
Android in Action
Screen rotation, Memory analyze, AIDL, SAX, Debug, Wakelock, etc.
Part I
Part II
Part III
http://android.amberfog.com/?p=655
UI
http://developer.android.com/design/index.html
http://inspired-ui.com/ http://www.androidpatterns.com/ http://mobile-patterns.com/
http://www.androiduipatterns.com/
http://pttrns.com/ http://www.lovelyui.com/
Android
Architecture Overview & History Building Blocks Manifest System Services Saving Application State NDK Activities & Fragments Layouts UI thread Debugging tools Application publishing & Money
Android History
http://www.theverge.com/2011/12/7/2585779/android-history
Android History
Jul 2005 Google acquired Android Inc. (co-founded by Andy Rubin) Nov 2007 Google Android presentation and early look release
HTC Magic Sep 2008 Soft Keyboard Widgets Mar 2009 May 2009 Voice Search WVGA Sep 2009 Oct 2009 clair Dec 2009 Froyo
1.0
HTC G1
1.1
1.5
1.6
2.0
2.0.1
Jan 2010
May 2010
2.1
Nexus One
2.2
JIT, C2DM, Flash Tethering, V8
Cupcake
Donut
2.3
Gingerbread Nexus S Feb 2011 May 2011 Comparability display mode May 2011 Ice Cream Sandwich Oct 2011
3.0
Tablets
3.1
ADT ported to 2.3.4 Resizable widgets
3.2
4.0
New UI virtual buttons Android Beam Phone + Tablet Roboto
Honeycomb
Jellybean?
February 2012
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.
// Without reflection Foo foo = new Foo(); foo.hello(); // With reflection Class cls = Class.forName("Foo"); Object foo = cls.newInstance(); Method method = cls.getMethod("hello", null); method.invoke(foo, null);
Application Framework
NDK / JNI Activity Manager Package Manager Window Manager Content Providers View System
Telephony Manager
Notification Manager
Libraries
Surface Manager OpenGL | ES SGL Media Framework FreeType SSL SQLite WebKit libc
Android Runtime
Core Libraries Dalvik VM
Linux Kernel
Display Driver Camera Driver Flash Memory Driver Binder (IPC) Driver
Keypad Driver
WiFi Driver
Audio Drivers
Power Management
JVM
class files
Thread
VM
The pc register (program counter) JVM Stack Native methods stacks Heap Method Area
lass
Execution engine
Dalvik VM
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 coders door
.dex file
string_ids constant pool type_ids constant pool proto_ids constant pool field_ids constant pool method_ids constant pool Hello World Lcom/data/Data int String[ ] String fn() void fn(int) String.offset Integer.MAX_VALUE PrintStream.println() Collection.size()
.class file
heterogeneous constant pool other data
.class file
heterogeneous constant pool other data
other data
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
Garbage collection
Android
Architecture Overview & History Building Blocks Manifest System Services Saving Application State NDK Activities & Fragments Layouts UI thread Debugging tools Application publishing & Money
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
Android Application
Android Context
Application Context
Non UI Context startActivity(Intent) start /stopService(Intent) sendBroadcast(Intent) register / unregisterReciever() Application FS, Preferences, Resources getSystemService
Activity Context
Same as for Application, but specific to current Activity startActivityForResult(Intent) / finish() bindService(Intent) UI: setContentView(View), findViewById() User events handling (Keys, Touches, Trackball)
Android
Architecture Overview & History Building Blocks Manifest System Services Saving Application State NDK Activities & Fragments Layouts UI thread Debugging tools Application publishing & Money
AndroidManifest.xml (1)
<?xml version="1.0" encoding="utf-8"?> <manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.my.example" android:versionName="1.0 beta" android:versionCode="2"> <application android:name=".MyApplication" android:label="..." android:icon="...">
<activity android:name=".MyActivity">
<intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity> <service ... /> <receiver ... /> <provider ... /> </application> </manifest>
AndroidManifest.xml (2)
<activity android:name=".MyActivity" android:launchMode="singleTask" android:theme="@style/Theme.MyDialog" /> <service android:name=".MyService" android:process="new"/> <receiver android:name=".MyReceiver" > <intent-filter> <action android:name= "android.intent.action.PACKAGE_REMOVED" />
AndroidManifest.xml (3)
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="..." package="com.my.example" android:versionName="1.0 beta" android:versionCode="2"> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.BLUETOOTH" /> <uses-sdk
android:minSdkVersion="3"
android:targetSdkVersion="4"/> <supports-screens android:largeScreens="true" android:normalScreens="true"
android:smallScreens="true"
android:resizeable="true" android:anyDensity="true" /> <application ...> ... </application>
</manifest>
AndroidManifest.xml (4)
</manifest>
Android
Architecture Overview & History Building Blocks Manifest System Services Saving Application State NDK Activities & Fragments Layouts UI thread Debugging tools Application publishing & Money
Description
Controls on-screen windows and their parameters Inflates layout resources Controls power management Status bar notifications Handling network connections Handling Wi-Fi network status Handling phone calls states Controls location (GPS) updates Controls sensor
Android
Architecture Overview & History Building Blocks Manifest System Services Saving Application State NDK Activities & Fragments Layouts UI thread Debugging tools Application publishing & Money
To read:
mPreferences.getType(String key, T defValue);
To write:
SharedPreferences.Editor editor = mPreferences.edit(); editor.putType(String key, T value); editor.commit();
SharedPreferences.OnSharedPreferenceChangeListener
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
Android
Architecture Overview & History Building Blocks Manifest System Services Saving Application State NDK Activities & Fragments Layouts UI thread Debugging tools Application publishing & Money
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
Android
Architecture Overview & History Building Blocks Manifest System Services Saving Application State NDK Activities & Fragments Layouts UI thread Debugging tools Application publishing & Money
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)
Task
Activity
Activity
Task
Activity
Activity ContentProvider Service Process .apk package
ContentProvider
Process Service Process .apk package
Android Process
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
HOME
Activity 1 (2) Intent flags FLAG_ACTIVITY_NEW_TASK FLAG_ACTIVITY_CLEAR_TOP FLAG_ACTIVITY_RESET_TASK_IF_NEEDED FLAG_ACTIVITY_SINGLE_TOP <activity> attributes taskAffinity launchMode allowTaskReparenting clearTaskOnLaunch alwaysRetainTaskState finishOnTaskLaunch
BACK
GMap Activity
Task
New Task
HOME
HOME
BACK
Activity 2
NEW_TASK
BACK
Activity 3 affinity=com.gtug.task2
Activity 1
Task
Task
taskAffinity=com.gtug.task1
taskAffinity=com.gtug.task2
Task reparenting
android:allowTaskReparenting=["true" | "false"]
Activity 1
Task
taskAffinity=com.gtug.task1
Activity 2 allowTaskReparenting=true affinity=com.gtug.task2 Activity 2
Activity 1
Task taskAffinity=com.gtug.task1
Task taskAffinity=com.gtug.task2
293:com.gtug.test123123/10025}
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
standard singleTop
singleInstance singleTask
Activity 3
Activity 2 Activity 1 Activity 1 Activity 2 Activity 1
Activity 3
Activity 2 Activity 1
standard
Task
Task
Task
Task
run Activity1
onNewIntent()
singleTop
Task
Task
Activity 3
Activity 2 Activity 1 Activity 1
singleTask
Task
Task
Activity1 is singleTask
singleInstance
Activity 2
Activity 1
Task1
Task2
Activity1 is singleInstance
onPostCreate ()
Start
onCreate()
onStart() onResume()
onPostResume()
foreground
foreground
onDestroy()
Stop
Fragments
Android
Architecture Overview & History Building Blocks Manifest System Services Saving Application State NDK Activities & Fragments Layouts UI thread Debugging tools Application publishing & Money
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
Layouts
Attributes ID
android:id="@+id/my_button android:id=@id/empty android:icon="@*android:drawable/ic_menu_clear_playlist
setContentView(R.layout.main_layout); findViewById(R.id.my_button);
Layout Parameters
layout_something layout parameter Every ViewGroup class implements a nested class that extends ViewGroup.LayoutParams layout_width and layout_height are LinearLayout required for all view groups
View v = findViewById(R.id.ImageView01); LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams)v.getLayoutParams(); lp.weight = 2f; v.setLayoutParams(lp); View
RelativeLayout. LayoutParams
RelativeLayout
LinearLayout. LayoutParams
View
LinearLayout. LayoutParams
View
LinearLayout. LayoutParams
View
RelativeLayout. LayoutParams
View
RelativeLayout. LayoutParams
20px
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:background="#FFFFFF" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:id="@+id/TextView01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="mytext" android:layout_marginLeft="20px" android:paddingTop="10px" android:textColor="#FF000000" /> </LinearLayout>
10px wrap_content
fill_parent
FrameLayout
<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content"> <Button android:text="@+id/Button01" android:id="@+id/Button01" android:layout_width="200px" android:layout_height="200px" /> <Button android:text="@+id/Button02" android:id="@+id/Button02" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </FrameLayout>
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
TableLayout
TableLayout positions its children into rows and columns stretchColumns zero-based index of the columns to stretch
<?xml version="1.0" encoding="utf-8"?> <TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:stretchColumns="1"> <TableRow> <TextView android:text=gtug1" android:padding=5dp" /> <TextView android:text=gtug2" android:gravity="right" android:padding=5dp" /> </TableRow> <TableRow> </TableRow> </TableLayout>
RelativeLayout (1) RelativeLayout lets child views specify their position relative to the parent view or to each other (specified by ID)
<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>
<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
better way
RelativeLayout (2)
LinearLayout
RelativeLayout
GridLayout (cont.)
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:alignmentMode="alignBounds" android:columnCount="4" android:columnOrderPreserved="false" android:useDefaultMargins="true" > <TextView android:layout_columnSpan="4" android:layout_gravity="center_horizontal" android:text="Email setup" android:textSize="32dip" /> <TextView android:layout_columnSpan="4" android:layout_gravity="left" android:text="You can configure email in just a few steps:" android:textSize="16dip" /> <TextView android:layout_gravity="right" android:text="Email address:" /> <EditText android:ems="10" /> <TextView android:layout_column="0" android:layout_gravity="right" android:text="Password:" /> <EditText android:ems="8" /> <Space android:layout_column="0" android:layout_columnSpan="3" android:layout_gravity="fill" android:layout_row="4" /> <Button android:layout_column="3" android:layout_row="5" android:text="Next" /> </GridLayout>
Android
Architecture Overview & History Building Blocks Manifest System Services Saving Application State NDK Activities & Fragments Layouts UI thread Debugging tools Application publishing & Money
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
CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views
Activity.runOnUiThread(Runnable) View.post(Runnable) View.postDelayed(Runnable, long) Handler AsyncTask UI: onPreExecute() WR: doInBackground() WR: publishProgress() UI: onProgressUpdate() UI: onPostExecute() android.app.IntentService
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
Qualifiers
Since 3.2
Screen configuration Qualifier values sw<N>dp smallestWidth Description 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. Specifies a minimum available width in dp units at which the resources should be useddefined by the <N> value. Specifies a minimum screen height in dp units at which the resources should be useddefined by the <N> value.
sw600dp sw720dp
w<N>dp
h720dp h1024dp
Android
Architecture Overview & History Building Blocks Manifest System Services Saving Application State NDK Activities & Fragments Layouts UI thread Debugging tools Application publishing & Money
Debugging tools
Android Debug Bridge (ADB) Dalvik Debug Monitor Server (DDMS) Traceview logcat ADT plug-in DevTools SpareParts AXMLPrinter2
ADB
Monkey
Stress-test your application: generate pseudo-random streams of user events such as clicks, touches, or gestures, as well as a number of system-level events
$ adb shell monkey -p your.package.name -v 500
You can write your own script and execute thru telnet
press DPAD_CENTER sleep 4000 tap 290 40 sleep 1000 tap 290 40 sleep 500
logcat
The priority is one of the following character values, ordered from lowest to highest priority: V Verbose (lowest priority) D Debug I Info W Warning E Error F Fatal S Silent (highest priority, on which nothing is ever printed)
DDMS
Threads info VM Heap info Allocation Tracker System info Emulator control Screen capture File Explorer
Demo
Using adb:
adb shell am profile com.gtug.project start /sdcard/filename adb shell am profile com.gtug.project stop
Impact performance!
Android
Architecture Overview & History Building Blocks Manifest System Services Saving Application State NDK Activities & Fragments Layouts UI thread Debugging tools Application publishing & Money
Contacts
Dmitry Lukashev
http://ru.linkedin.com/in/dmitrylukashev dmitry.lukashev@gmail.com
Blog - http://android.amberfog.com/
Thank You!
Questions?