Mobile Applications Grzegorz Budzyń Lecture 2: Android Applications
Plan History and background Application Fundamentals Application Components Activities Services Content Providers Broadcast Receivers Threads Manifest
Background Android is the software platform from Google and the Open Handset Alliance Android is a software environment built for mobile devices It is not a hardware platformbut a software one While components of the underlying OSare written in C or C++, user applications are built for Android in Java
History In July 2005, Google acquired Android, Inc., a small startup company based in Palo Alto, CA. 4 of Android's co-founders went to work at Google At Google, the team developed a mobile device platform powered by the Linux kernel
History Open Handset Alliance (Google, TI, Intel, Motorola, ) is an alliance of approximately 30 organizations committed to bringing a better and open mobile phone to market Android has been available as open source since October 2008
History Google opened the entire source code under an Apache License With the Apache License, vendors are free to add proprietary extensions without submitting those back to the open source community
History Android has seen a number of updates since its original release: Android 1.0 (API level1) -23 September 2008 Android 1.5 Cupcake(API level3) -30 April 2009 Android 2.0 Eclair(API level5) -26 October 2009 Android 2.2 Froyo(API level8) -20 May 2010 Android 2.3 Gingerbread(API level9) -6 December 2010 Android 3.0 Honeycomb(API level11 tablet only) -22 February 2011
History Android has seen a number of updates since its original release: Android 4.0-4.0.2 IceCreamSandwich(API level 14) -19 October 2011 Android 4.0.3-4.0.4 IceCreamSandwich(API level 15) -16 December 2011 Android 4.1 JellyBean(API level16) -27 June 2012 Android 4.2 JellyBean(API level17) -13 November 2012 Android 5.0 KeyLimePie(API level??) 2 Q 2013
Android -mainfeatures In the Android platform, there is no difference between the built-in applications and applications created with the SDK. This means that powerful applications can be written to tap into the resources available on the device
Android -mainfeatures Enables reuse and replacement of components DalvikVirtualMachineoptimized for mobile devices Integrated browser based on the open source WebKit engine Optimized graphics powered by a custom 2D graphics library; 3D graphics based on the OpenGL ES 1.0 specification (hardware acceleration optional) SQLite for structured data storage
Android -mainfeatures Media support for common audio, video, and still image formats (MPEG4, H.264, MP3, AAC, AMR, JPG, PNG, GIF) GSM Telephony (hardware dependent) Bluetooth, EDGE, 3G, and WiFi(hardware dependent) Camera, GPS, compass, and accelerometer (hardware dependent) Rich development environment including a device emulator, tools for debugging, memory and performance profiling, and a pluginfor the Eclipse IDE
Android -architecture
Android LinuxKernel Works as a HAL(Hardware Abstraction Layer) Device drivers Memory management Process management Networking
Android Libraries C/C++ libraries Interface through Java Surface manager Handling UI Windows 2D and 3D graphics Media codecs, SQLite, Browser engine
Android AndroidRuntime DalvikVM Dexfiles Compact and efficient than class files Limited memory and battery power Core Libraries Java 5 Std edition Collections, I/O etc
Android architecture-dvm Android includes a set of core libraries that provides most of the functionality available in the core libraries of the Java programming language Every Android application runs in its own process, with its own instance of the Dalvik virtual machine Dalvikhas been written so that a device can run multiple VMs efficiently
Android architecture-dvm The DalvikVM executes files in the DalvikExecutable (.dex) format which is optimized for minimal memory footprint The VM runs classes compiled by a Java language compiler that have been transformed into the.dex format The DalvikVM relies on the Linux kernel for underlying functionality such as threading and lowlevel memory management
Android ApplicationFramework API interface Activity manager manages application life cycle View System Content Providers Notification Menager
Android -architecture Underlying all applications is a set of services and systems, including: A set of Viewsthat can be used to build an application, including lists, grids, text boxes, buttons, and even an embeddable web browser Content Providersthat enable applications to access data from other applications (such as Contacts), or to share their own data A Resource Manager, providing access to non-code resources such as localized strings, graphics, and layout files A Notification Managerthat enables all applications to display custom alerts in the status bar An Activity Managerthat manages the lifecycle of applications and provides a common navigation backstack
Android Applications Built in and user apps Can replace built in apps
Android -architecture Android shipswith a set of core applications including an email client, SMS program, calendar, maps, browser, contacts, and others (all in JAVA) Developers have full access to the same framework APIs used by the core applications
Android -architecture The application architecture is designed to simplify the reuse of components; any application can publish its capabilities and any other application may then make use of those capabilities This same mechanism allows components to be replaced by the user
Android applicationfundamentals Android applications are written in the Java The compiled Java code along with any data and resource files required by the application is bundled into an Android package, an archive file marked by an.apk suffix The.apkfile isdownloadedby usersto their devices All the code in a single.apkfile is considered to be one application
Android applicationfundamentals In many ways, each Android application lives in its own world: Every application runs in its own Linux process Android starts the process when any of the application's code needs to be executed, and shuts down the process when it's no longer needed Each process has its own Java virtual machine (VM), so application code runs in isolationfrom the code of all other applications
Android applicationfundamentals In many ways, each Android application lives in its own world: Each application is assigned a unique Linux user ID Permissions are set so that the application's files are visible only to the application itself It's possible to arrange for two applications to share the same user ID, in which case they will be able to see each other's files
Android applicationcomponents A central feature of Android is that one application can make use of elements of other applications Theapplication in need simply starts up that piece of the other application when the need arises
Android applicationcomponents Unlikeapplications on most other systems, Android applications don't have a single entry pointfor everything in the application (no main() function) The applications have essential components that the system can instantiate and run as needed
Android applicationcomponents There are four types of application components: Activities Services Broadcast Receivers Content Providers
Activities
Applicationcomponents-Activities An activitypresents a visual user interface for one focused endeavor the user can undertake each activity is independent of the others Each one is implemented as a subclass of the Activity base class An application might consist of just one activity or it may contain several
Applicationcomponents-Activities Typically, one of the activities is marked as the first one that should be presented to the user when the application is launched Moving from one activity to another is accomplished by having the current activity start the next one
Application(Activity) Lifecycle Application run in their own processes (VM, PID) Processes are started and stopped as needed to run an application's components Processes may be killed to reclaim resources
ActivityStack Activities in the system are scheduled using an activity stack. When a new activity is started, it is placed on top of the stack to become the running activity The previous activity is pushed-down one level in the stack, and may come back to the foreground once the new activity finishes. If the user presses the Back Button the current activity is terminated and the next activity on the stack moves up to become active.
ActivityStack
LifeCycleCallbacks
LifeCycleStates Basically the activity is in three states: 1) Itisactiveorrunning 2) Itispaused 3) Itisstopped
LifeCycleStates Itisactiveorrunningwhenitisinthe foregroundofthescreen(atthetop ofthe activity stack). This is the activity that has focus and its graphical interface is responsive to the user s interactions.
LifeCycleStates Itispausedifithaslostfocusbut isstillvisible to theuser. Thatis, anotheractivitylieson top ofitandthatnewactivityeitheris transparent ordoesn'tcoverthefullscreen. A paused activity is alive(maintaining its state information and attachment to the window manager). Pausedactivitiescanbe killedby the system when available memory becomes extremelylow.
LifeCycleStates Itisstoppedifitiscompletelyobscuredby another activity. Continues to retains all its stateinformation. Itisno longervisibleto theuser( itswindowis hidden and its life cycle could be terminated atanypoint by thesystem iftheresources that it holds are needed elsewhere).
CompleteApplication slifetime An activity begins its lifecycle when entering theoncreate() state. If not interrupted or dismissed, the activity performs its job and finally terminates and releases its acquired resources when reaching theondestroy() event.
LifeCycleEvents Applications do not need to implement each of the transition methods, however there are mandatoryandrecommendedstatesto consider Mandatory: All activities must implement oncreate() to do the initial setup when the object is first instantiated. Recommended: Activities should implement onpause() to commit data changes in anticipation to stop interacting with the user.
LifeCycleMethods Method: OnCreate() Calledwhentheactivityisfirstcreated. Most ofyourapplication scodeiswrittenhere. Typicallyusedto definelistener sbehavior, initialize data structures, wire-up UI view elements(buttons, text boxes, lists) with static Java controls, etc. Itmayreceivea data Bundleobjectcontainingthe activity'spreviousstate(ifany). Followedby onstart()
Method: OnPause() LifeCycleMethods Called when the system is about to transfer control to anotheractivity. Givesyoua chanceto commitunsaveddata, and stop work that may unnecessarily burden the system. Thenextactivitywaitsuntilcompletionofthisstate. Followed either by onresume() if the activity returnsbackto theforeground, orby onstop() ifit becomesinvisibleto theuser. A pausedactivitycouldbe killedby thesystem.
Killable States LifeCycleMethods Activitieson killablestatescanbe terminatedby the system when memory resources become criticallylow. Methods: onpause(), onstop(), and ondestroy()arekillable. onpause() istheonlystatethatisguaranteedto be givena chanceto completebeforetheprocess iskilled. YoushoulduseonPause() to writeanypending persistentdata.
Services
Applicationcomponents-Services A servicedoesn't have a visual user interface, but rather runs in the background for an indefinite period of time Each service extends the Service base class For example, a service might play background music as the user attends to other matters, or it might fetch data over the network or calculate something and provide the result to activities that need it
Applicationcomponents-Services Run in the background Can continue even if Activity that started it dies Should be used if something needs to be done while the user is not interacting with application Otherwise, a thread is probably more applicable Should create a new thread in the service to do work in, since the service runs in the main thread
Applicationcomponents-Services Can be bound to an application In which case will terminate when all applications bound to it unbind Allows multiple applications to communicate with it via a common interface Needs to be declared in manifest file Like Activities, has a structured life cycle
Broadband Receivers
Applicationcomponents Broadband Receivers A broadcast receiveris a component that does nothing but receive and react to broadcast announcements Many broadcasts originate in system code for example, announcements that the timezonehas changed, that the battery is low, that a picture has been taken, or that the user changed a language preference
Content Providers
Applicationcomponents Content Providers A content providermakes a specific set of the application's data available to other applications Android ships with a number of content providers for common data types (audio, video, images, personal contact information, etc.)
Intents
Applicationcomponents-Intents Activities, services, and broadcast receivers are activated by asynchronous messages called intents An intent is an Intentobject that holds the content of the message For activities and services, it names the action being requested and specifies the URI of the data to act on, among other things
Applicationcomponents-Intents
Applicationcomponents-Intents
Threads
Threads Threads are the cornerstone of any multitasking operating system Threadscanbe thought of as mini-processes running within a main process The purpose of threadsisto enable at least the appearance of parallel execution paths within applications
Threads When an Android application is first started, the runtime system creates a single thread (mainthread) in which all application components will run by default The primary role of the main thread is to handle the user interface in terms of event handling and interaction with views in the user interface
Threads Any component within an application which performs a time consuming task using the main thread will cause the entire application to appear to lock up until the task is completed This can be avoided simply by launching the task to be performed in a separate thread
Threads The key rules of application development: never perform time consuming operations on the main thread of an application the code within a separate thread must never, under any circumstances, directlyupdate any aspect of the user interface Any changes to the user interface must always be performed from within the main thread
ThreadHandlers In the event that the code executing in a thread needs to interact with the user interface, it must do so by synchronizing with the main UI thread This is achieved by creating a handler within the main thread Handler receives messages from another thread and updates the user interface accordingly
Android Application Development
ApplicationDevelopment Required tools: Phone Eclipse ( http://www.eclipse.org/downloads/ ) Android Plugin(ADT) Android SDK ( http://developer.android.com/sdk/index.html )
ApplicationDevelopment Required operations: Installation of the SDK Instalaltion of desired packages(not required with ADT) Installation of USB drivers for debugging hardware (phone) Or CreationofAndroid VirtualDevice(for software emulation)
Application Development Process
BuildingandRunning ADB is a client server program that connects clients on developer machine to devices/emulators to facilitate development. An IDE like Eclipse handles this entire process.
Buildingand Runningdetails
Project Components src your source code gen auto-generated code (usually just R.java) Included libraries Resources Drawables(like.png images) Layouts Values (like strings) Manifest file
XML Used to define some of the resources Layouts (UI) Strings Manifest file Preferred way of creating UIs Separates the description of the layout from any actual code that controls it Can easily take a UI from one platform to another
R Class Auto-generated: shouldn t be editted Contains IDs of the project resources Enforces good software engineering Use findviewbyidand Resources object to get access to the resources Ex. Button b = (Button)findViewById(R.id.button1) Ex. getresources().getstring(r.string.hello));
Layout Eclipse has an UI creator Generates the XML semiautomatically Composed of View objects Can be specified for portrait and landscape mode Use same file name, so can make completely different UIs for the orientations without modifying any code IsdescribedinXML languageinthemanifest
Layout
Layout
In res/values strings.xml Strings Application wide available strings Promotes good software engineering UI components made in the UI editor should have text defined in strings.xml Strings are just one kind of Value -there are many others
Manifest Every application must have an AndroidManifest.xmlfile (with precisely that name) in its root directory The manifest presents essential information about the application to the Android system
Manifest The manifest does the following: It names the Java package for the application. The package name serves as a unique identifier forthe application It describes the components of the application the activities, services, broadcast receivers, and content providers that the application is composed of. It names the classes that implement each ofthe components and publishes their capabilities
Manifest The manifest does the following: It determines which processes will host application components It declares which permissions the application must have in order to access protected parts of theapi and interact with other applications It also declares the permissions that others are required to have in order to interact with the application's components
Manifest The manifest does the following: It declares the minimum level of the Android API that the application requires. It lists the libraries that the application must be linked against.
Manifest -example <?xml version= 1.0 encoding= utf-8?> <manifest xmlns:android= http://schemas.android.com/apk/res/android package= uk.ac.ic.doc android:versioncode= 1 android:versionname= 1.0 > <application android:icon= @drawable/icon android:label= @string/app_name > <activity android:name=.sampleactivity android:label= @string/activity_title_text_ref > <intent-filter> /*... */ </intent-filter> </activity> </application> <uses-sdk android:minsdkversion= 3 /> </manifest>
Thank you for your attention
References [1] developers.android.com [2] D. Shinde, C. Atherton, Android Application Development Tutorial [3] V. Matos, Lesson 3 Application s Life Cycle [4] http://grail.cba.csuohio.edu/~matos/notes/cis-493/lecturenotes/android-chapter03-life-cycle.pdf [5] http://lyle.smu.edu/~coyle/cse7392mobile/handouts/s01.the%20andr oidmanifest.pdf [6] http://mobileawards.ir/linkclick.aspx?fileticket=kgkiwcmd2gw=&tabid =845 [7] http://www.vogella.com/articles/androidintent/article.html [8] http://www.techotopia.com/index.php/a_basic_overview_of_android _Threads_and_Thread_handlers