Download presentation
Presentation is loading. Please wait.
Published byIsaac Owens Modified over 9 years ago
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 2
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's OpenCORE; 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 3
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 4
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 5
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 6
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 7
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.dex files, aiming at performance I improvements transparent to end users. 8
9
Android Architecture The framework allows developers to build cool apps 9
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 10
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. 11
12
Views ViewGroup – ways to group other views Layouts – invisible containers holding views and define properties 12
13
Android Architecture Core applications ship with android. 13
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 14
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 15
16
Application Components Intents and Intent Filters Activities Services Content Providers Broadcast Receivers App Widgets Processes and Threads 16
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. 17
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) 18
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 19
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. 20
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 21
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 22
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. 23
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. 24
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 25
26
An example Adapted from Janzen 26
27
A First Example: Advent Devotions 27
28
UML Class Diagram Generated by Android External Activity 28
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); 29
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); 30
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); 31
32
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 setContentView(View).” http://developer.android.com/reference/android/app/ Activity.html#ActivityLifecycle 32
33
Android Manifest.xml <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.simexusa.adventdevotions" android:versionCode="2" android:versionName="1.0"> <activity android:name=".AdventDevos" android:label="@string/app_name"> Specifies icon for launching app Specifies icon label for launching app Specifies activity to be launched at startup Each upload to PlayStore requires versionCode increment Security permissions requested from user on install SDK version required by app 33 http://developer.android.com/guide/topics/manifest/manifest-intro.html
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 and in html Note use of dimen (see values/dimens.xml) and color (see values/colors.xml) Also see strings.xml 34
35
main.xml <LinearLayout 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"> <TableLayout android:layout_width="wrap_content" android:id="@+id/TableLayout01" android:layout_height="wrap_content"> <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 android:text="Nov. 30" android:id="@+id/Button02" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="@dimen/button_width"> <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 android:text="Dec. 2" android:id="@+id/Button04" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="@dimen/button_width"> … 35
36
devo.xml <LinearLayout 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"> <TextView android: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 android: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"> <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"> <ScrollView android:id="@+id/ScrollView01" android:layout_height="fill_parent" android:layout_width="fill_parent"> <TextView android: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"> 36
37
dimens.xml 17sp 20sp 37
38
colors.xml #AAFFFF99 #FF000000 38
39
strings.xml Hello World, AdventDevos! Advent Devotions 39
40
Attributes and their Meaning 40
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 41
42
Android Application Lifecycle and Menus Adapted from Janzen Except as otherwise noted, the content of this presentation is licensed under the Creative Commons Attribution 2.5 License. 42
43
Application Lifecycle Look at Application Fundamentals http://developer.android.com/guide/topics/fundamentals.html 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 43
44
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 for foreground or visible processes. If user navigates back to activity, onCreate(Bundle) calledonCreate(Bundle) Empty process is hosting no components. Killed very quickly as memory becomes low. Background operations executed in BroadcastReceiver or Service to keep process around. 44 http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle
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 45
46
Active Lifetime Example Campus Maps Turn on/off GPS to save battery when UI not in focus @Override protected void onPause() { super.onPause(); //stop receiving GPS and Orientation data locationManager.removeUpdates(locationListener); } @Override protected void onResume() { super.onResume(); //restart receiving GPS and Orientation data locationManager.requestLocationUpdates(provider, 2000, 10, locationListener); } 46
47
Visible Lifetime Example Campus Maps Save state as app could get killed after onStop() @Override protected void onStop() { super.onStop(); savePreferences(); } @Override protected void onStart() { super.onStart(); restoreUIState(); } 47
48
Visible Lifetime Example Campus Maps Save state as app could get killed after onStop() private void savePreferences() { SharedPreferences cmSharedPreferences = getSharedPreferences(CMPREFS,Activity.MODE_PRIVATE); SharedPreferences.Editor editor = cmSharedPreferences.edit(); editor.putBoolean(VIRTUAL_MODE, inVirtualMode); editor.putInt(MAP_INDEX, curMapIndex); editor.commit(); } private void restoreUIState() { SharedPreferences cmSharedPreferences = getSharedPreferences(CMPREFS,Activity.MODE_PRIVATE); inVirtualMode = cmSharedPreferences.getBoolean(VIRTUAL_MODE, true); curMapIndex = cmSharedPreferences.getInt(MAP_INDEX, 0); } 48
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() 49
50
XML UI Configuration Layouts can specify UI elements (provided and custom) res/layout 50
51
Menus Icon Menu (up to 6 icons) Expanded Menu (from More on Icon Menu) Submenus 51
52
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
53
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 onStart() 53
54
Activity lifecycle Called after activity has been stopped, prior to it being restarted Followed by onStart() 54
55
Activity lifecycle Called when activity becomes visible to user Followed by onResume() if activity comes to the foreground or onStop() if becomes hidden 55
56
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 onPause() 56
57
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 OnResume() (activity returns back to front) or onStop() (becomes invisible) 57
58
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 onRestart() (activity coming back for interaction) or onDestroy() (going away) 58
59
Activity lifecycle Final call before being destroyed Activity finished (finish() called) Destroyed by system to save space Use isFinishing() to figure out which 59
60
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
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.