Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
www.android.com Simone Livraghi Solution Architect [email protected] 2 ● ● ● ● ● ● Summary What is Android? Dalvik Application Fundamentals Application Components Market Links 3 What is Android? 4 What is Android? The Android SDK provides the tools and APIs necessary to begin developing applications on the Android platform using the Java programming language. Android is a software stack for mobile devices that includes an operating system, middleware and key applications 5 What is Android? Features ● ● ● ● ● ● ● ● ● ● Application framework Dalvik virtual machine Integrated browser Optimized graphics – hardware acceleration optional SQLite Media support GSM Telephony – hardware dependent Bluetooth, EDGE, 3G, and WiFi hardware dependent Camera, GPS, compass, and accelerometer hardware dependent Rich development environment 6 What is Android? 7 ● ● ● ● ● ● ● ● What is Android? System C library - BSD based Media Libraries - MPEG4, H.264, MP3, AAC, AMR, JPG, and PNG Surface Manager LibWebCore SGL - 3D Scene Graph Library 3D libraries - OpenGL ES 1.0 APIs FreeType SQLite 8 What is Android? Android relies on Linux version 2.6 for core system services such as security, memory management, process management, network stack, and driver model. The kernel also acts as an abstraction layer between the hardware and the rest of the software stack. http://android.git.kernel.org 9 Application Fundamentals 10 Application Fundamentals Android applications are written in the Java programming language. Each Android application lives in its own security sandbox: ● Android is a multi-user system in which each application is a different user. ● Each application a unique Linux user ID ● Each process has its own virtual machine – – – – – application's code runs in isolation from other ones Every application runs in its own Linux process Android starts the process when any of the application's components need to be executed Android shuts down the process when it's no longer needed Android shuts down the process when the system must recover memory 11 Dalvik 12 Dalvik 13 Dalvik - Memory The Dalvik virtual machine is a register-based virtual machine. It is optimized for low memory requirements, and is designed to allow multiple VM instances to run at once, relying on the underlying operating system for process isolation, memory management and threading support. ● Total system RAM: 64 MB. – – ● Available RAM after low-level startup: 40 MB. Available RAM after high-level services have started: 20 MB. Multiple independent mutually-suspicious processes – – Separate address spaces. Separate memory. 14 Dalvik – DEX Dalvik is often referred to as a Java Virtual Machine, but this is not strictly accurate, as the bytecode on which it operates is not Java bytecode. Instead, a tool named dx, included in the Android SDK, transforms the Java Class files of Java classes compiled by a regular Java compiler into another class file format (the .dex format). 15 Dalvik – DEX header string_ids type_ids ids proto_ids class_defs data field_ids method_ids “Hello World!!!” "Lcom/google/Blort;" ... int String Com.google.Blort ... void fn(int) double fn(Object, int) String fn() ... String.offset Integer.MAX_VALUE ... PrintStream.println(…) Collection.size() ... 16 Dalvik – DEX .jar .class heterogeneous constant pool data .dex header ids .class heterogeneous constant pool data ... class_defs data ... 17 Dalvik – DEX example public interface Zapper { } public String zap(String s, Object o); public class Blort implements Zapper { } public String zap(String s, Object o) { ...; } public class ZapUser { } public void useZap(Zapper z) { z.zap(...); } 18 Dalvik – DEX example (.jar) 19 Dalvik – DEX example (.dex) 20 ● Dalvik - DEX common system libraries – – – ● web browser app – – – ● (U) 21445320 — 100% (J) 10662048 — 50% (D) 10311972 — 48% (U) 470312 — 100% (J) 232065 — 49% (D) 209248 — 44% alarm clock app – – – (U) 119200 — 100% (J) 61658 — 52% (D) 53020 — 44% (U) uncompressed jar file (J) compressed jar file (D) uncompressed dex file 21 Dalvik - Memory Dalvik manages four Kinds Of Memory ● clean vs. dirty – – ● clean: mmap()ed and unwritten cirty: malloc()ed shared vs. private – – shared: used by many processes private: used by only one process 22 Dalvik - Memory Dalvik manages four Kinds Of Memory ● clean (shared or private) – – ● shared dirty – – ● common dex files (libraries) application-specific dex files library “live” dex structures shared copy-on-write heap (mostly not written) private dirty – – application “live” dex structures application heap 23 ● ● ● Dalvik – Garbage collector Separate process, separate heaps, separate Gcs. GCs must be independent. GC should respect the sharing. 24 Dalvik - CPU The CPU efficiency problem ● ● ● ● CPU speed: 250-500MHz Bus speed: 100MHz Data cache: 16-32K Available RAM for apps: 20 MB 25 Dalvik - CPU No JIT ● ● usually doesn’t matter lots of native code – – ● system provides libs for graphics, media JNI available hardware support common (graphics, audio) 26 Dalvik - CPU Install-Time Work ● Verification – dex structures aren’t “lying” ● ● – ● valid indices valid offsets code can’t misbehave Optimization – – – – – byte-swapping and padding (unnecessary on ARM) static linking “inlining” special native methods pruning empty methods adding auxiliary data 27 Application Components 28 ● ● ● ● ● Application Components The Android Manifest Activity Service Content provider Broadcast receiver 29 The Android Manifest 30 The Android Manifest Before the Android system can start an application component, the system must know that the component exists by reading the application's AndroidManifest.xml file. ● ● ● ● ● Identify any user permissions the application requires Declare the minimum API Level required by the application Declare hardware and software features used or required by the application API libraries the application needs to be linked against Declaring components – <activity>, <service>, <receiver>, <provider> 31 The Android Manifest <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.helloworld" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="14" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <activity android:label="@string/app_name" android:name=".ExampleActivity" > <intent-filter > <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> 32 Activity 33 Activity An Activity is an application component that provides a screen with which users can interact in order to do something. An application usually consists of multiple activities that are loosely bound to each other. An Activity should be declared in the manifest file in order for it to be accessible to the system. <activity android:label="@string/app_name" android:name=".ExampleActivity" > <intent-filter > <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> 34 Activity - Lifecycle When an activity transitions into and out of the different states described above, it is notified through various callback methods. ● ● ● ● ● ● ● OnCreate OnStart OnResume OnPause OnStop OnRestart OnDestroy 35 Activity - Lifecycle 36 Activity - Lifecycle You can start another activity by calling startActivity(), passing it an Intent that describes the activity you want to start. Intent intent = new Intent(this, SecondActivity.class); startActivity(intent); You can shut down an activity by calling its finish() method. You can also shut down a separate activity that you previously started by calling finishActivity(). finishActivity(ACTIVITY_CODE); 37 Activity - Lifecycle Sometimes, you might want to receive a result from the activity that you start. private void pickContact() { 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 (resultCode == Activity.RESULT_OK && requestCode == PICK_CONTACT_REQUEST) { } } Cursor cursor = getContentResolver().query(data.getData(), new String[] {Contacts.DISPLAY_NAME}, null, null, null); if (cursor.moveToFirst()) { int columnIndex = cursor.getColumnIndex(Contacts.DISPLAY_NAME); String name = cursor.getString(columnIndex); } Activity - Intent 38 An intent is an abstract description of an operation to be performed. An Intent object can contain: ● Component name Example: Activity Class – ● Action ACTION_EDIT, ACTION_VIEW, ACTION_PICK, etc. – ● ● Data Category – ● ● CATEGORY_HOME, CATEGORY_LAUNCHER, CATEGORY_PREFERENCE, etc. Extras Flags 39 Activity - Intent Intents can be divided into two groups: ● Explicit intents – designate the target component by its name Intent intent = new Intent(this, SecondActivity.class); startActivity(intent); ● Implicit intents – do not name a target Intent intent = new Intent(Intent.ACTION_SEND); intent.putExtra(Intent.EXTRA_EMAIL, recipientArray); startActivity(intent); 40 Activity - Intent To inform the system which implicit intents they can handle, activities, services, and broadcast receivers can have one or more intent filters. <activity android:name=".ExampleActivity" android:label="@string/app_name" > <intent-filter > <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".SecondActivity" > <intent-filter > <action android:name="android.intent.action.VIEW" /> <action android:name="android.intent.action.EDIT" /> <action android:name="android.intent.action.PICK" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="vnd.android.cursor.dir/vnd.example.mail" /> </intent-filter> <intent-filter > <action android:name="android.intent.action.SEND" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="vnd.android.cursor.item/vnd.example.mail" /> </intent-filter> </activity> 41 Activity - UI The user interface for an activity is provided by a hierarchy of views. The most common way to define a layout using views is with an XML layout file saved in your application resources. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:id="@+id/myTextView" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" android:textSize="38dp" /> </LinearLayout> 42 Activity - UI 43 Activity - UI You can set the layout as the UI for your activity with setContentView(), passing the resource ID for the layout. public class ExampleActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } } public final class R { public static final class attr { } public static final class drawable { public static final int ic_launcher=0x7f020000; } public static final class id { public static final int myTextView=0x7f050000; } public static final class layout { public static final int main=0x7f030000; } public static final class string { public static final int app_name=0x7f040001; public static final int hello=0x7f040000; } } 44 Activity - Fragment A Fragment represents a behavior or a portion of user interface in an Activity. You can combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities. Android introduced fragments in Android 3.0 (API level 11), primarily to support more dynamic and flexible UI designs on large screens, such as tablets. 45 Activity - Fragment 46 Activity - Fragment The application can embed two fragments in Activity A, when running on a tablet-sized device. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="match_parent"> <fragment android:name="com.example.news.ArticleListFragment" android:id="@+id/list" android:layout_weight="1" android:layout_width="0dp" android:layout_height="match_parent" /> <fragment android:name="com.example.news.ArticleReaderFragment" android:id="@+id/viewer" android:layout_weight="2" android:layout_width="0dp" android:layout_height="match_parent" /> </LinearLayout> 47 Activity - Fragment On a handset-sized screen, Activity A includes only the fragment for the list of articles, and when the user selects an article, it starts Activity B, which includes the second fragment to read the article. <?xml version="1.0" encoding="utf-8"?> <LinearLayout ...> <fragment android:name="com.example.news.ArticleListFragment" android:id="@+id/list" android:layout_weight="1" android:layout_width="0dp" android:layout_height="match_parent" /> </LinearLayout> <?xml version="1.0" encoding="utf-8"?> <LinearLayout ...> <fragment android:name="com.example.news.ArticleReaderFragment" android:id="@+id/viewer" android:layout_weight="2" android:layout_width="0dp" android:layout_height="match_parent" /> </LinearLayout> 48 Activity – Fragment lifecycle 49 Activity – Fragment lifecycle 50 Activity - Supporting Multiple Screens Terms and concepts ● Screen size – – ● Actual physical size, measured as the screen's diagonal. small, normal, large, and extra large Screen density – The quantity of pixels within a physical area of the screen; usually referred to as dpi (dots per inch). ● ● Orientation – The orientation of the screen from the user's point of view. ● ● landscape or portrait Resolution – ● low, medium, high, and extra high The total number of physical pixels on a screen. Density-independent pixel (dp) – A virtual pixel unit that you should use when defining UI layout, to express layout dimensions or position in a density-independent way. ● px = dp * (dpi / 160) 51 Activity - Supporting Multiple Screens Basic Guidelines ● Explicitly declare in the manifest which screen sizes your application supports – ● you should include the <supports-screens> element in your manifest file Provide different layouts for different screen sizes res/layout/my_layout.xml res/layout-small/my_layout.xml res/layout-large/my_layout.xml res/layout-xlarge/my_layout.xml res/layout-xlarge-land/my_layout.xml ● Provide different bitmap drawables for different screen densities res/drawable-mdpi/my_icon.png res/drawable-hdpi/my_icon.png res/drawable-xhdpi/my_icon.png 52 Activity - Supporting Multiple Screens Basic Guidelines ● Build your activity designs based on fragments – ● Use the action bar – ● You can think of a fragment as a modular section of an activity Ensure your design is flexible enough for the system to adjust the action bar layout Implement flexible layouts – A flexible layout design allows your application to adapt to variations in screen sizes. 53 Activity – Action Bar The Action Bar is an important UI component for Android apps on both tablets and handsets. 54 Service 55 Service A Service is an application component that can perform long-running operations in the background and does not provide a user interface. Another application component can start a service and it will continue to run in the background even if the user switches to another application. Like activities (and other components), you must declare all services in your application's manifest file. <manifest ... > ... <application ... > <service android:name=".ExampleService" /> ... </application> </manifest> 56 Service A service can essentially take two forms: ● Started – – ● A service is "started" when an application component (such as an activity) starts it by calling startService(). Once started, a service can run in the background indefinitely, even if the component that started it is destroyed. Bound – – – – A service is "bound" when an application component binds to it by calling bindService(). A bound service offers a client-server interface that allows components to interact with the service. A bound service runs only as long as another application component is bound to it. Multiple components can bind to the service at once. 57 Service 58 Service - AIDL AIDL (Android Interface Definition Language) allows you to define the programming interface that both the client and service agree upon in order to communicate with each other using interprocess communication (IPC). On Android, one process cannot normally access the memory of another process. So to talk, they need to decompose their objects into primitives that the operating system can understand, and marshall the objects across that boundary for you. 59 Service - AIDL You must define your AIDL interface in an .aidl file using the Java programming language syntax. interface IHelloService { Bundle sendRequest(in Bundle request); } If you have a class that you would like to send from one process to another through an IPC interface, you can do that. You must ensure that the code for your class is available to the other side of the IPC channel and your class must support the Parcelable interface. Parcel is not a general-purpose serialization mechanism. It is designed as a high-performance IPC transport. 60 Service - AIDL - Marshalling Marshalling (computer science) From Wikipedia, the free encyclopedia In computer science, marshalling (sometimes spelled marshaling, similar to serialization) is the process of transforming the memory representation of an object to a data format suitable for storage or transmission. It is typically used when data must be moved between different parts of a computer program or from one program to another. Marshalling is a process that is used to communicate to remote objects with an object (in this case a serialized object). It simplifies complex communication, using custom/complex objects to communicate - instead of primitives. The opposite, or reverse, of marshalling is called unmarshalling (or demarshalling, similar to deserialization). 61 ● ● ● ● ● ● ● Service - AIDL Include the .aidl file in the project src/ directory. Declare an instance of the IBinder interface (generated based on the AIDL). Implement ServiceConnection. Call Context.bindService(), passing in your ServiceConnection implementation. In your implementation of onServiceConnected(), you will receive an IBinder instance (called service). Call YourInterfaceName.Stub.asInterface((IBinder)service) to cast the returned parameter to YourInterface type. Call the methods that you defined on your interface. You should always trap DeadObjectException exceptions, which are thrown when the connection has broken; this will be the only exception thrown by remote methods. To disconnect, call Context.unbindService() with the instance of your interface. 62 Content Providers 63 Content Providers Content providers store and retrieve data and make it accessible to all applications. – The application's data are stored using the system SQLite library. They're the only way to share data across applications; there's no common storage area that all Android packages can access. – – The application's data are stored into the sandbox. Only the Content Provider could be shared. Each content provider exposes a public URI that uniquely identifies its data set. 64 Content Providers To let the Android system know about the content provider you've developed, declare it with a <provider> element in the application's AndroidManifest.xml file. <provider android:name=".TransportationProvider" android:authorities="com.example.transportationprovider" ... /> </provider> Android ships with a number of content providers for common data types – audio, video, images, personal contact information, etc. 65 Content Providers All content providers implement a common interface for querying the provider and returning results — as well as for adding, altering, and deleting data. It's an interface that clients use indirectly, most generally through ContentResolver objects. – You get a ContentResolver by calling getContentResolver() Content providers expose their data as a simple table on a database model. – Every record includes a numeric _ID field that uniquely identifies the record within the table. 66 Content Providers - ContentResolver public boolean onCreate() public final String getType (Uri url) public final Cursor query ( Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder ) public final Uri insert (Uri url, ContentValues values) public final int update (Uri uri, ContentValues values, String where, String[] selectionArgs) public final int delete (Uri url, String where, String[] selectionArgs) 67 Content Providers - URI 68 Content Providers - Query _ID NUMBER NUMBER_KEY LABEL NAME TYPE 13 (425) 555 6677 425 555 6677 Kirkland office Bully Pulpit TYPE_WORK 44 (212) 555-1234 212 555 1234 NY apartment Alan Vain TYPE_HOME 45 (212) 555-6657 212 555 6657 Downtown office Alan Vain TYPE_MOBILE 53 201.555.4433 Love Nest Rex Cars TYPE_HOME 201 555 4433 String[] projection = new String[] { People._ID, People._COUNT, People.NAME,People.NUMBER }; Cursor cursor = getContentResolver().query( People.CONTENT_URI, projection, null, // Selection null, // Selection arguments People.NAME + " ASC"); 69 Content Providers - Query _ID _COUNT NUMBER NAME 44 3 (212) 5551234 Alan Vain 13 3 (425) 555 6677 Bully Pulpit 53 3 201.555.4433 Rex Cars String[] projection = new String[] { People._ID, People._COUNT, People.NAME,People.NUMBER }; Cursor cursor = getContentResolver().query( People.CONTENT_URI, projection, null, // Selection null, // Selection arguments People.NAME + " ASC"); 70 Content Providers - Insert _ID NUMBER NUMBER_KEY LABEL NAME TYPE 13 (425) 555 6677 425 555 6677 Kirkland office Bully Pulpit TYPE_WORK 44 (212) 555-1234 212 555 1234 NY apartment Alan Vain TYPE_HOME 45 (212) 555-6657 212 555 6657 Downtown office Alan Vain TYPE_MOBILE 53 201.555.4433 Love Nest Rex Cars TYPE_HOME 201 555 4433 ContentValues contentValues = new ContentValues(); contentValues.put(People.NAME, "Simone Livraghi"); contentValues.put(People.LABEL, "Io sono L"); contentValues.put(People.TYPE, People.TYPE_MOBILE); contentValues.put(People.NUMBER, "(333) 3333333"); getContentResolver().insert(People.CONTENT_URI, contentValues); 71 Content Providers - Insert _ID NUMBER NUMBER_KEY LABEL NAME TYPE 13 (425) 555 6677 425 555 6677 Kirkland office Bully Pulpit TYPE_WORK 44 (212) 555-1234 212 555 1234 NY apartment Alan Vain TYPE_HOME 45 (212) 555-6657 212 555 6657 Downtown office Alan Vain TYPE_MOBILE 53 201.555.4433 201 555 4433 Love Nest Rex Cars TYPE_HOME 54 (333) 3333333 333 333 3333 Io sono L Simone Livraghi TYPE_MOBILE ContentValues contentValues = new ContentValues(); contentValues.put(People.NAME, "Simone Livraghi"); contentValues.put(People.LABEL, "Io sono L"); contentValues.put(People.TYPE, People.TYPE_MOBILE); contentValues.put(People.NUMBER, "(333) 3333333"); getContentResolver().insert(People.CONTENT_URI, contentValues); 72 Content Providers - Update _ID NUMBER NUMBER_KEY LABEL NAME TYPE 13 (425) 555 6677 425 555 6677 Kirkland office Bully Pulpit TYPE_WORK 44 (212) 555-1234 212 555 1234 NY apartment Alan Vain TYPE_HOME 45 (212) 555-6657 212 555 6657 Downtown office Alan Vain TYPE_MOBILE 53 201.555.4433 201 555 4433 Love Nest Rex Cars TYPE_HOME 54 (333) 3333333 333 333 3333 Io sono L Simone Livraghi TYPE_MOBILE ContentValues contentValues = new ContentValues(); contentValues.put(People.NAME, "Alan Vaini"); String selection = People.NAME + "='Alan Vain'"; getContentResolver().update( People.CONTENT_URI, null, // Projection selection, null, // Selection arguments People.NAME + " ASC"); 73 Content Providers - Update _ID NUMBER NUMBER_KEY LABEL NAME TYPE 13 (425) 555 6677 425 555 6677 Kirkland office Bully Pulpit TYPE_WORK 44 (212) 555-1234 212 555 1234 NY apartment Alan Vaini TYPE_HOME 45 (212) 555-6657 212 555 6657 Downtown office Alan Vaini TYPE_MOBILE 53 201.555.4433 201 555 4433 Love Nest Rex Cars TYPE_HOME 54 (333) 3333333 333 333 3333 Io sono L Simone Livraghi TYPE_MOBILE ContentValues contentValues = new ContentValues(); contentValues.put(People.NAME, "Alan Vaini"); String selection = People.NAME + "='Alan Vain'"; getContentResolver().update( People.CONTENT_URI, null, // Projection selection, null, // Selection arguments People.NAME + " ASC"); 74 Content Providers - Delete _ID NUMBER NUMBER_KEY LABEL NAME TYPE 13 (425) 555 6677 425 555 6677 Kirkland office Bully Pulpit TYPE_WORK 44 (212) 555-1234 212 555 1234 NY apartment Alan Vaini TYPE_HOME 45 (212) 555-6657 212 555 6657 Downtown office Alan Vaini TYPE_MOBILE 53 201.555.4433 201 555 4433 Love Nest Rex Cars TYPE_HOME 54 (333) 3333333 333 333 3333 Io sono L Simone Livraghi TYPE_MOBILE String selection = People._ID "=" + 44; getContentResolver().delete( People.CONTENT_URI, selection, null); // Selection arguments 75 Content Providers - Delete _ID NUMBER NUMBER_KEY LABEL NAME TYPE 13 (425) 555 6677 425 555 6677 Kirkland office Bully Pulpit TYPE_WORK 45 (212) 555-6657 212 555 6657 Downtown office Alan Vaini TYPE_MOBILE 53 201.555.4433 201 555 4433 Love Nest Rex Cars TYPE_HOME 54 (333) 3333333 333 333 3333 Io sono L Simone Livraghi TYPE_MOBILE String selection = People._ID "=" + 44; getContentResolver().delete( People.CONTENT_URI, selection, null); // Selection arguments 76 Broadcast Receiver 77 Broadcast Receiver To let the Android system know about the broadcast receiver you've developed, declare it with a <receiver> element in the application's AndroidManifest.xml file. <receiver android:enabled="true" android:name=".NetworkReceiver"> <intent-filter> <action android:name="android.net.wifi.WIFI_STATE_CHANGED" /> <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> </intent-filter> </receiver> 78 Broadcast Receiver - Lifecycle A BroadcastReceiver object is only valid for the duration of the call to onReceive(Context, Intent). public class NetworkReceiver extends BroadcastReceiver { } @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub } 79 Market http://market.android.com 80 Links http://www.android.com http://developer.android.com www.android.com Simone Livraghi Solution Architect [email protected]