Android App Basics Slides from developer android com
Android App Basics Slides from developer. android. com and adopted from Janzen
Android Architecture � Android � What built on Linux 2. 6 kernel is a kernel? � Provides security, memory management, process management, network stack, and driver model � Abstraction layer between hardware and the software stack 2
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 Linuxbased devices � Media Libraries - based on Packet. Video's Open. CORE; the libraries support playback and recording of many popular audio and video formats, as well as static image files, including MPEG 4, H. 264, MP 3, AAC, AMR, JPG, and PNG � 3
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 2 D and 3 D graphic layers from multiple applications � Free. Type - bitmap and vector font rendering 4
Android Architecture �A set of C/C++ libraries exposed to developers through the application framework � Lib. Web. Core - a modern web browser engine which powers both the Android browser and an embeddable web view � SGL - the underlying 2 D graphics engine 5
Android Architecture �A set of C/C++ libraries exposed to developers through the application framework 3 D libraries - an implementation based on Open. GL ES 1. 0 APIs; the libraries use either hardware 3 D acceleration (where available) or the included, highly optimized 3 D software rasterizer � SQLite - a powerful and lightweight relational database engine available to all applications � 6
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 7
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 (Kit. Kat) � The successor of Dalvik is Android Runtime (ART), which uses the same bytecode and. dex files, aiming at performance improvements transparent to end users. I 8
Android Architecture � The framework allows developers to build cool apps 9
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 10
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. 11
Views � View. Group – ways to group other views � Layouts – invisible containers holding views and define properties 12
Android Architecture � Core applications ship with android. 13
Resources � Value � � Strings, colors, dimensions, arrays (strings, integers, typed), bool, ID, Drawable – something drawn to the screen � Bitmaps, Nine. Patch (stretchable) images � � Layout � � � 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 � � Layouts define the look of your activity, can specify in XML or with code, XML often easier Animations � � PNG is preferred, JPG, and GIF supported 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 14
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 15
Application Components � Intents and Intent Filters � Activities � Services � Content Providers � Broadcast Receivers � App Widgets � Processes and Threads 16
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 Content. Resolver. Call query() on a Content. Resolver 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 start. Activity(). � 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 onetime operation (such as download a file) by passing an Intent to start. Service(). � 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 send. Broadcast(), send. Ordered. Broadcast(), or send. Sticky. Broadcast(). � � 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. 17
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) 18
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 � 19
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. 20
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 21
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. � Any start a service to perform work based on an event 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 22
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. 23
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. 24
Manifest � Each app has an Android. Manifest. 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 25
An example Adapted from Janzen 26
A First Example: Advent Devotions 27
UML Class Diagram External Activity Generated by Android 28
Two Activities in Advent Devotions � Advent. Devos displays the calendar of dates � Devo displays a single devotion Intent my. Intent = new Intent(Advent. Devos. this, Devo. class) my. Intent. put. Extra("Button. Num", "" + index); start. Activity(my. Intent); 29
Two Activities in Advent Devotions � Advent. Devos displays the calendar of dates � Devo displays a single devotion Bundle extras = get. Intent(). get. Extras(); String value = extras. get. String("Button. Num") Integer button. Num = Integer. value. Of(value); 30
Launching an Intent you didn’t write � Devos has button to � Browser launched URL Intent i = new Intent(Intent. ACTION_VIEW, Uri. parse("http: //www. biblegateway. com/passage/? search=" passage +"&version=NIV")); start. Activity(i); 31
Android Activity � “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 set. Content. View(View). ” http: //developer. android. com/reference/android/app/ Activity. html#Activity. Lifecycle 32
Android Manifest. xml http: //developer. android. com/guide/topics/manifest-intro. html <? xml version="1. 0" encoding="utf-8"? > Each upload to Play. Store requires version. Code increm <manifest xmlns: android="http: //schemas. android. com/apk/res/android" package="com. simexusa. adventdevotions" android: version. Code="2" Specifies icon for launching app android: version. Name="1. 0"> <application android: icon="@drawable/star" android: label="@string/app_name" android: debu <activity android: name=". Advent. Devos" android: label="@string/app_name"> Specifies icon label for launching app <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-sdk android: min. Sdk. Version=“ 19" /> Specifies activity to be launched at startup <uses-permission android: name="android. permission. INTERNET" /> </manifest> 33 SDK version required by app Security permissions requested from user on install
Layouts and Resources � See main. xml and devo. xml � Activity associates with layout xml file using set. Content. View(R. layout. main); or set. Content. View(R. layout. devo); in on. Create() � Note Table. Layout and Table. Row 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 34
main. xml <? xml version="1. 0" encoding="utf-8"? > <Linear. Layout xmlns: 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"> <Table. Layout android: layout_width="wrap_content" android: id="@+id/Table. Layout 01" android: layout_height="wrap_content"> <Table. Row android: padding. Top="8 px"> <Button android: text="Nov. 29" android: id="@+id/Button 01" android: layout_width="wrap_content" android: layout_height="wrap_content" android: text. Size="@dimen/button_width"></Button> <Button android: text="Nov. 30" android: id="@+id/Button 02" android: layout_width="wrap_content" android: layout_height="wrap_content" android: text. Size="@dimen/button_width"></Button> <Button android: text="Dec. 1" android: id="@+id/Button 03" android: layout_width="wrap_content" android: layout_height="wrap_content" android: text. Size="@dimen/button_width"></Button> <Button android: text="Dec. 2" android: id="@+id/Button 04" android: layout_width="wrap_content" android: layout_height="wrap_content" android: text. Size="@dimen/button_width"></Button> </Table. Row> … 35
devo. xml <? xml version="1. 0" encoding="utf-8"? > <Linear. Layout xmlns: 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"> <Text. View android: text="Date" android: id="@+id/Date" android: layout_width="wrap_content" android: layout_height="wrap_content" android: gravity="center_horizontal" android: text. Style="italic" android: text. Size="@dimen/reference_width" android: typeface="serif" android: text. Color="@color/text"></Text. View> <Text. View android: text="Title" android: id="@+id/Title" android: layout_width="wrap_content" android: layout_height="wrap_content" android: gravity="center_horizontal" android: text. Style="bold" android: text. Size="@dimen/reference_width" android: typeface="serif" android: text. Color="@color/text"></Text. View> <Button android: text="Read Scripture" android: id="@+id/Button. Scripture" android: layout_width="wrap_content" android: layout_height="wrap_content" android: gravity="center_horizontal" android: text. Size="@dimen/reference_width"></Button> <Scroll. View android: id="@+id/Scroll. View 01" android: layout_height="fill_parent" android: layout_width="fill_parent"> <Text. View android: text="Body" android: id="@+id/Body" android: layout_width="wrap_content" android: layout_height="wrap_content" android: gravity="left" android: text. Size="@dimen/reference_width" android: typeface="serif" android: text. Color="@color/text"></Text. View> </Scroll. View> </Linear. Layout> 36
dimens. xml <? xml version="1. 0" encoding="utf-8"? > <resources> <dimen name="button_width">17 sp</dimen> <dimen name="reference_width">20 sp</dimen> </resources> 37
colors. xml <? xml version="1. 0" encoding="utf-8"? > <resources> <color name="background">#AAFFFF 99</color> <color name="text">#FF 000000</color> </resources> 38
strings. xml <? xml version="1. 0" encoding="utf-8"? > <resources> <string name="hello">Hello World, Advent. Devos!</string> <string name="app_name">Advent Devotions</string> </resources> 39
Attributes and their Meaning 40
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 � Can hardware capabilities 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 41
Android Application Lifecycle and Menus Adapted from Janzen 42 Except as otherwise noted, the content of this presentation is licensed under the Creative Commons Attribution 2. 5 License.
Application Lifecycle �Look at Application Fundamentals http: //developer. android. com/guide/topics/fundamentals. html �Active lifetime � has focus, accepting UI events � on. Resume to on. Pause �Visible lifetime � Visible, but does not have focus � on. Start to on. Stop �Full lifetime � on. Create to on. Destroy 43
Process Lifecycle � Processes keep around for as long as possible, will kill less important processes � Foreground activity at top of screen user interacting with most important. � Only killed if out of memory � Visible activity is visible to user but not in foreground, is extremely important � Only killed if required to keep the foreground activity running. � Background activity is not visible (paused) so not critical, System may kill to reclaim memory foreground or visible processes. � If user navigates back to activity, on. Create(Bundle) called � � Empty process is hosting no components. Killed very quickly as memory becomes low. � Background operations executed in Broadcast. Receiver or Service to keep process around. � http: //developer. android. com/reference/android/app/Activity. html#Activity. Lif ecycle 44
Active Lifetime Example � Campus � Shows � Maps App user location on campus map image http: //market. android. com/search? q=pname: com. simexusa. campusmaps_full 45
Active Lifetime Example � Campus � Turn Maps on/off GPS to save battery when UI not in focus @Override protected void on. Pause() { super. on. Pause(); //stop receiving GPS and Orientation data location. Manager. remove. Updates(location. Listener); } @Override protected void on. Resume() { super. on. Resume(); //restart receiving GPS and Orientation data location. Manager. request. Location. Updates(provider, 2000, 10, location. Listener); } 46
Visible Lifetime Example � Campus � Save Maps state as app could get killed after on. Stop() @Override protected void on. Stop() { super. on. Stop(); save. Preferences(); } @Override protected void on. Start() { super. on. Start(); restore. UIState(); } 47
Visible Lifetime Example � Campus � Save Maps state as app could get killed after on. Stop() private void save. Preferences() { Shared. Preferences cm. Shared. Preferences = get. Shared. Preferences(CMPREFS, Activity. MODE_PRIVATE); Shared. Preferences. Editor editor = cm. Shared. Preferences. edit(); editor. put. Boolean(VIRTUAL_MODE, in. Virtual. Mode); editor. put. Int(MAP_INDEX, cur. Map. Index); editor. commit(); } private void restore. UIState() { Shared. Preferences cm. Shared. Preferences = get. Shared. Preferences(CMPREFS, Activity. MODE_PRIVATE); in. Virtual. Mode = cm. Shared. Preferences. get. Boolean(VIRTUAL_MODE, true); cur. Map. Index = cm. Shared. Preferences. get. Int(MAP_INDEX, 0); } 48
UI Elements � View � Control � View. Group � Layout � Widget � Many (Compound Control) expected Views � Button, Check. Box, Radio. Button � Text. View, Edit. Text, List. View � Can be customized by extending and overriding on. Draw() 49
XML UI Configuration � Layouts can specify UI elements (provided and custom) � res/layout 50
Menus � Icon Menu (up to 6 icons) � Expanded Menu (from More on Icon Menu) � Submenus 51
Activity lifecycle � Active or running Top of stack � In foreground of screen � � Paused � Visible but lost focus � Stopped Obscured by another activity � No longer visible, but keeps state � � Dead � If paused or stopped can be killed or asked to finish � Must be restarted 52
Activity lifecycle � Called when fist created � Static setup � Create views, bind data, … � Provides Bundle containing activity’s previously frozen state, if there was one � Always followed by on. Start() 53
Activity lifecycle � Called after activity has been stopped, prior to it being restarted � Followed by on. Start() 54
Activity lifecycle � Called when activity becomes visible to user � Followed by on. Resume() if activity comes to the foreground or on. Stop() if becomes hidden 55
Activity lifecycle � Called when activity will start interacting with user � Activity now on top of activity stack, with user input going to it. � Followed by on. Pause() 56
Activity lifecycle � Called when system about to start resuming a previous activity. � Use to commit unsaved changes to persistent data, stop animations, and anything else consuming CPU � Needs to be very quick since next activity will not resume until done � Followed by On. Resume() (activity returns back to front) or on. Stop() (becomes invisible) 57
Activity lifecycle � Called when the activity is no longer visible � Another activity covering it � New activity started � Existing activity moved to front � This one being destroyed � Followed by on. Restart() (activity coming back for interaction) or on. Destroy() (going away) 58
Activity lifecycle � Final call before being destroyed � Activity finished (finish() called) � Destroyed by system to save space � Use is. Finishing() to figure out which 59
App ideas for Project � Ringer in Vibrate mode based on Calendar notifications � Roll Taker using the Camera � Sync events on multiple different Calendars � Developing useful widgets � Shopping app with nice features (camera, barcode support) � Deal Monitoring app � Weather reporter � International student app (TAMUCC or just CS) � Paint mixer � Islander game, lane based attack, islander theme (tiki) � Humans and Zombies 60
- Slides: 60