1 / 60

Android App Basics

Android App Basics. Slides from developer.android.com and adopted from Janzen. Android Architecture. Android built on Linux 2.6 kernel What is a kernel? Provides security, memory management, process management, network stack, and driver model

lev
Download Presentation

Android App Basics

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Android App Basics Slides from developer.android.com and adopted from Janzen

  2. Android Architecture • Android built on Linux 2.6 kernel • What is a kernel? • Provides security, memory management, process management, network stack, and driver model • Abstraction layer between hardware and the software stack

  3. Android Architecture • A set of C/C++ libraries exposed to developers through the application framework • System C library - a BSD-derived implementation of the standard C system library (libc), tuned for embedded Linux-based devices • Media Libraries - based on PacketVideo'sOpenCORE; the libraries support playback and recording of many popular audio and video formats, as well as static image files, including MPEG4, H.264, MP3, AAC, AMR, JPG, and PNG

  4. Android Architecture • A set of C/C++ libraries exposed to developers through the application framework • Surface Manager - manages access to the display subsystem and seamlessly composites 2D and 3D graphic layers from multiple applications • FreeType - bitmap and vector font rendering

  5. Android Architecture • A set of C/C++ libraries exposed to developers through the application framework • LibWebCore - a modern web browser engine which powers both the Android browser and an embeddable web view • SGL - the underlying 2D graphics engine

  6. Android Architecture • A set of C/C++ libraries exposed to developers through the application framework • 3D libraries - an implementation based on OpenGL ES 1.0 APIs; the libraries use either hardware 3D acceleration (where available) or the included, highly optimized 3D software rasterizer • SQLite- a powerful and lightweight relational database engine available to all applications

  7. Android Architecture • Runtime libraries provide most of the functionality in the core Java libraries • Each app has a process and an instance of Dalvik VM • Uses Dalvik Executable (.dex) format – low memory footprint • VM is register based runs compiled Java classes • The linux kernel provides Dalvik with needed functionality

  8. Android Architecture • Named for Dalvik in Iceland, a fishing village where ancestors of Dan Bornstein lived. • Dalvik is discontinued process virtual machine as of Android version 4.4 (KitKat) • The successor of Dalvik is Android Runtime (ART), which uses the same bytecode and .dexfiles, aiming at performance I improvements transparent to end users.

  9. Android Architecture The framework allows developers to build cool apps

  10. Android Architecture • Set of services and systems • Views to build apps: lists, grids, text boxes, buttons, browser • Content providers enable apps to share data between each other • Resource manager for access to non-code resources such as localized strings, graphics, and layout files • A Notification manager that enables all applications to display custom alerts in the status bar • Activity manager manages lifecycle of apps and provides a common navigation backstack

  11. Views • Basic block for a UI component, occupying a rectangle on the screen • It draws and handles events • Widgets – interactive UI components • Buttons, text fields, spinners, date picker, map,etc.

  12. Views • ViewGroup – ways to group other views • Layouts – invisible containers holding views and define properties

  13. Android Architecture Core applications ship with android.

  14. Resources • Value • Strings, colors, dimensions, arrays (strings, integers, typed), bool, ID, • Drawable – something drawn to the screen • Bitmaps, NinePatch (stretchable) images • PNG is preferred, JPG, and GIF supported • Layout • Layouts define the look of your activity, can specify in XML or with code, XML often easier • Animations • Property – modify object’s property values over time • Tween – rotate, move, stretch, and fade a view • Frame – to display a sequence of images • Color State List – change color based on state • Example: button is pressed, focused, or neither, define color for each • Menu – defines app menu (options, context, submenu, …) that can be inflated • Style – defines the format and look of a UI for view or activity

  15. Application Fundamentals • Written in Java, using Android SDK to compile into an Android Package • Each app lives in its own security sandbox (principle of least privilege: only access to what it needs) • Android OS is multi-user with each app a user • Each app gets a user ID • Can be shared between apps (also share same process and VM) • Each process has own VM – runs in isolation • Each app has its own process – started for any component • Can request permission to access device data (SMS, camera…) • Granted at install time

  16. Application Components Intents and Intent Filters Activities Services Content Providers Broadcast Receivers App Widgets Processes and Threads

  17. Intents and Intent Filters • Intents and Intent Filters • An Intent is a messaging object you can use to request an action from another app component. Intents (an asynchronous message) are used to start components (except content providers) • Content providers are activated when targeted by a request from a ContentResolver. Call query() on a ContentResolver to query a content Provider • Start Activity - An Activity represents a single screen in an app. You can start a new instance of an Activity by passing an Intent to startActivity(). • Start Service - A Service is a component that performs operations in the background without a user interface. You can start a service to perform a one-time operation (such as download a file) by passing an Intent to startService(). • Deliver Broadcast - A broadcast is a message that any app can receive. The system delivers various broadcasts for system events, such as when the system boots up or the device starts charging. You can deliver a broadcast to other apps by passing an Intent to sendBroadcast(), sendOrderedBroadcast(), or sendStickyBroadcast(). • An Intent filter specifies the types of intents that an activity, service, or broadcast receiver can respond to. An intent filter declares the capabilities of its parent component.

  18. Activities • Activities • A single screen with a user interface • Example – text message screen, inbox, compose email, etc. • They are independent • An app may have more than one • Typically, one activity in an application is specified as the "main" activity, which is presented to the user when launching the application for the first time. • Can be started by other applications (if allowed)

  19. Activities • Activities • Fragments - 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. • Loaders – They make it easy to asynchronously load data in an activity or fragment. They are available to every Activity and Fragment. Monitor the source of their data and deliver new results when the content changes • Tasks and Back Stack - A task is a collection of activities that users interact with when performing a certain job. The activities are arranged in a stack (the "back stack"), in the order in which each activity is opened. When the user presses the Back button, the current activity is popped from the top of the stack (the activity is destroyed) and the previous activity resumes (the previous state of its UI is restored). Activities in the stack are never rearranged, only pushed and popped from the stack

  20. Services • Services • Runs in the background for long-running operations or remote processes • Has no user interface • Example – play music, fetch data • An activity can start a service, or bind to a service for interaction.

  21. Content Providers • Content Providers • Manages a shared set of application data • Stored in the file system, an SQLite database, on the web, any other persistent location you have access to • Other apps can query or modify data (if allowed) • Example: contact information • Can also be used for private app data

  22. Broadcast Receivers • Broadcast Receivers • Responds to system-wide broadcasts • Generally originate from system, i.e. low battery, screen off, picture taken. • Apps can also broadcast, i.e. data ready for use • No user interface but may create a status bar notification • Generally a gateway to other components and light weight • i.e. start a service to perform work based on an event • Any application can start another application’s component • Will start a process for the component’s app, not run in yours • Means no single entry point (i.e main()) • You can’t start it, need to have system deliver a message with your intent to start a component • Makes it much easier to add functionality to your app

  23. App Widgets • App Widgets are miniature application views that can be embedded in other applications (such as the Home screen) and receive periodic updates. These views are referred to as Widgets in the user interface, and you can publish one with an App Widget provider.

  24. Processes and Threads When an application component starts and the application does not have any other components running, the Android system starts a new Linux process for the application with a single thread of execution. By default, all components of the same application run in the same process and thread (called the "main" thread). If an application component starts and there already exists a process for that application (because another component from the application exists), then the component is started within that process and uses the same thread of execution. You can arrange for different components in your application to run in separate processes, and you can create additional threads for any process.

  25. Manifest • Each app has an AndroidManifest.xml file • Declare all the components in this file • In root of app project directory • Identify user permissions required by app (ie internet access, rw contacts,…) • Declare minimum API level required • Declare hardware and software features used or required • i.e camera, bluetooth services, camera, multitouch screen • API libraries needed by app for linking • And more

  26. An example Adapted from Janzen

  27. A First Example: Advent Devotions

  28. UML Class Diagram External Activity Generated by Android

  29. Two Activities in Advent Devotions • AdventDevos displays the calendar of dates • Devo displays a single devotion Intent myIntent = new Intent(AdventDevos.this, Devo.class); myIntent.putExtra("ButtonNum", "" + index); startActivity(myIntent);

  30. Two Activities in Advent Devotions • AdventDevos displays the calendar of dates • Devo displays a single devotion Bundle extras = getIntent().getExtras(); String value = extras.getString("ButtonNum"); Integer buttonNum = Integer.valueOf(value);

  31. Launching an Intent you didn’t write • Devos has button to URL • Browser launched Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.biblegateway.com/passage/?search="+ passage +"&version=NIV")); startActivity(i);

  32. Android Activity http://developer.android.com/reference/android/app/ Activity.html#ActivityLifecycle “An activity is a single, focused thing that the user can do. Almost all activities interact with the user, so the Activity class takes care of creating a window for you in which you can place your UI with setContentView(View).”

  33. Android Manifest.xml • http://developer.android.com/guide/topics/manifest/manifest-intro.html <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.simexusa.adventdevotions" android:versionCode="2" android:versionName="1.0"> <application android:icon="@drawable/star"android:label="@string/app_name"android:debuggable="false"> <activity android:name=".AdventDevos" 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=".Devo"/> </application> <uses-sdkandroid:minSdkVersion=“19" /> <uses-permission android:name="android.permission.INTERNET" /> </manifest> Each upload to PlayStorerequires versionCode increment Specifies icon for launching app Specifies icon label for launching app Specifies activity to be launched at startup SDK version required by app Security permissions requested from user on install

  34. Layouts and Resources • See main.xml and devo.xml • Activity associates with layout xml file using setContentView(R.layout.main); or setContentView(R.layout.devo); in onCreate() • Note TableLayout and TableRow similar to <table> and <tr> in html • Note use of dimen (see values/dimens.xml) and color (see values/colors.xml) • Also see strings.xml

  35. main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical"android:layout_width="fill_parent" android:layout_height="fill_parent"android:background="@color/background"> <TableLayoutandroid:layout_width="wrap_content" android:id="@+id/TableLayout01"android:layout_height="wrap_content"> <TableRowandroid:paddingTop="8px"> <Button android:text="Nov. 29"android:id="@+id/Button01" android:layout_width="wrap_content"android:layout_height="wrap_content" android:textSize="@dimen/button_width"></Button> <Button android:text="Nov. 30"android:id="@+id/Button02" android:layout_width="wrap_content"android:layout_height="wrap_content" android:textSize="@dimen/button_width"></Button> <Button android:text="Dec. 1"android:id="@+id/Button03" android:layout_width="wrap_content"android:layout_height="wrap_content" android:textSize="@dimen/button_width"></Button> <Button android:text="Dec. 2"android:id="@+id/Button04" android:layout_width="wrap_content"android:layout_height="wrap_content" android:textSize="@dimen/button_width"></Button> </TableRow> …

  36. devo.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical"android:layout_width="fill_parent" android:layout_height="fill_parent"android:gravity="center_horizontal" android:background="@color/background"> <TextViewandroid:text="Date"android:id="@+id/Date" android:layout_width="wrap_content"android:layout_height="wrap_content" android:gravity="center_horizontal"android:textStyle="italic" android:textSize="@dimen/reference_width"android:typeface="serif" android:textColor="@color/text"></TextView> <TextViewandroid:text="Title"android:id="@+id/Title" android:layout_width="wrap_content"android:layout_height="wrap_content" android:gravity="center_horizontal"android:textStyle="bold" android:textSize="@dimen/reference_width"android:typeface="serif" android:textColor="@color/text"></TextView> <Button android:text="Read Scripture"android:id="@+id/ButtonScripture" android:layout_width="wrap_content"android:layout_height="wrap_content" android:gravity="center_horizontal"android:textSize="@dimen/reference_width"></Button> <ScrollViewandroid:id="@+id/ScrollView01" android:layout_height="fill_parent"android:layout_width="fill_parent"> <TextViewandroid:text="Body"android:id="@+id/Body" android:layout_width="wrap_content"android:layout_height="wrap_content" android:gravity="left"android:textSize="@dimen/reference_width" android:typeface="serif"android:textColor="@color/text"></TextView> </ScrollView> </LinearLayout>

  37. dimens.xml <?xml version="1.0" encoding="utf-8"?> <resources> <dimen name="button_width">17sp</dimen> <dimen name="reference_width">20sp</dimen> </resources>

  38. colors.xml <?xml version="1.0" encoding="utf-8"?> <resources> <color name="background">#AAFFFF99</color> <color name="text">#FF000000</color> </resources>

  39. strings.xml <?xml version="1.0" encoding="utf-8"?> <resources> <string name="hello">Hello World, AdventDevos!</string> <string name="app_name">Advent Devotions</string> </resources>

  40. Attributes and their Meaning

  41. Resources • All Apps have resources (non-code) • Images, audio, animations, menus, styles, colors, layouts… • Can update app characteristics without modifying code • Can have device dependent resources • Different hardware capabilities • Can have user dependent resources • Languages, preferences, etc • Each resource has unique integer ID • Use a qualifier to decide which set of resources to use • Portrait vs landscape

  42. Android Application Lifecycleand Menus Adapted from Janzen Except as otherwise noted, the content of this presentation is licensed under the Creative Commons Attribution 2.5 License.

  43. Application Lifecycle • Look at Application Fundamentals http://developer.android.com/guide/topics/fundamentals.html • Active lifetime • has focus, accepting UI events • onResume to onPause • Visible lifetime • Visible, but does not have focus • onStart to onStop • Full lifetime • onCreate to onDestroy

  44. Process Lifecycle http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle • Processes keep around for as long as possible, will kill less important processes • Foreground activityat top of screen user interacting with - most important. • Only killed if out of memory • Visible activityis visible to user but not in foreground, is extremely important • Only killed if required to keep the foreground activity running. • Background activityis not visible (paused) so not critical, • System may kill to reclaim memory for foreground or visible processes. • If user navigates back to activity, onCreate(Bundle) called • Empty process is hosting no components. • Killed very quickly as memory becomes low. • Background operations executed in BroadcastReceiver or Service to keep process around.

  45. Active Lifetime Example • Campus Maps App • Shows user location on campus map image • http://market.android.com/search?q=pname:com.simexusa.campusmaps_full

  46. Active Lifetime Example • Campus Maps • Turn on/off GPS to save battery when UI not in focus @Override protectedvoidonPause() { super.onPause(); //stop receiving GPS and Orientation data locationManager.removeUpdates(locationListener); } @Override protectedvoidonResume() { super.onResume(); //restart receiving GPS and Orientation data locationManager.requestLocationUpdates(provider, 2000, 10, locationListener); }

  47. Visible Lifetime Example • Campus Maps • Save state as app could get killed after onStop() @Override protectedvoidonStop() { super.onStop(); savePreferences(); } @Override protectedvoidonStart() { super.onStart(); restoreUIState(); }

  48. Visible Lifetime Example • Campus Maps • Save state as app could get killed after onStop() privatevoidsavePreferences() { SharedPreferencescmSharedPreferences = getSharedPreferences(CMPREFS,Activity.MODE_PRIVATE); SharedPreferences.Editor editor = cmSharedPreferences.edit(); editor.putBoolean(VIRTUAL_MODE, inVirtualMode); editor.putInt(MAP_INDEX, curMapIndex); editor.commit(); } privatevoidrestoreUIState() { SharedPreferencescmSharedPreferences = getSharedPreferences(CMPREFS,Activity.MODE_PRIVATE); inVirtualMode = cmSharedPreferences.getBoolean(VIRTUAL_MODE, true); curMapIndex = cmSharedPreferences.getInt(MAP_INDEX, 0); }

  49. UI Elements • View • Control • ViewGroup • Layout • Widget (Compound Control) • Many expected Views • Button, CheckBox, RadioButton • TextView, EditText, ListView • Can be customized by extending and overriding onDraw()

  50. XML UI Configuration • Layouts can specify UI elements (provided and custom) • res/layout

More Related