Mobile Programming Lecture 2

Slides:



Advertisements
Similar presentations
Android Application Development A Tutorial Driven Course.
Advertisements

Google Android Introduction to Mobile Computing. Android is part of the build a better phone process Open Handset Alliance produces Android Comprises.
Application Fundamentals Android Development. Announcements Posting in D2L Tutorials.
What is Android?.
Android architecture overview
Android Platform Overview (1)
Android Application Model (3)
Android 02: Activities David Meredith
All About Android Introduction to Android 1. Creating a New App “These aren’t the droids we’re looking for.” Obi-wan Kenobi 1. Bring up Eclipse. 2. Click.
Application Fundamentals. See: developer.android.com/guide/developing/building/index.html.
Mobile Application Development
More on User Interface Android Applications. Layouts Linear Layout Relative Layout Table Layout Grid View Tab Layout List View.
Mobile Programming Pertemuan 6 Presented by Mulyono Poltek NSC Surabaya.
Asst.Prof.Dr.Ahmet Ünveren SPRING Computer Engineering Department Asst.Prof.Dr.Ahmet Ünveren SPRING Computer Engineering Department.
@2011 Mihail L. Sichitiu1 Android Introduction Application Fundamentals.
Emerging Platform#4: Android Bina Ramamurthy.  Android is an Operating system.  Android is an emerging platform for mobile devices.  Initially developed.
Android Middleware Bo Pang
Chien-Chung Shen Manifest and Activity Chien-Chung Shen
@2011 Mihail L. Sichitiu1 Android Introduction Platform Overview.
Copyright© Jeffrey Jongko, Ateneo de Manila University Android.
This work is licensed under the Creative Commons Attribution 4.0 International License. To view a copy of this license, visit
CS378 - Mobile Computing Intents.
16 Services and Broadcast Receivers CSNB544 Mobile Application Development Thanks to Utexas Austin.
ANDROID 응용 프로그래밍 과정 – 목차 - 안드로이드란 - 안드로이드가 만들어지게 된배경 - 안드로이드의 철학 - 안드로이드 환경설정 ( SDK download, eclipse plug-in 설정, 간단한 프로그램 실행 ) - 안드로이드 동작원리 - 안드로이드 핵심.
10/10/2015 E.R.Edwards 10/10/2015 Staffordshire University School of Computing Introduction to Android Overview of Android System Android Components Component.
Overview of Android Application Development
CS378 - Mobile Computing Intents. Allow us to use applications and components that are part of Android System – start activities – start services – deliver.
ANDROID L. Grewe Components  Java Standard Development Kit (JDK) (download) (latest version)  AndroidStudio.
ANDROID BY:-AANCHAL MEHTA MNW-880-2K11. Introduction to Android Open software platform for mobile development A complete stack – OS, Middleware, Applications.
Created By. Jainik B Patel Prashant A Goswami Gujarat Vidyapith Computer Department Ahmedabad.
DKU-MUST Mobile ICT Education Center 10. Activity and Intent.
Lecture 2: Android Concepts
1 Android Workshop Platform Overview. 2 What is Android?  Android is a software stack for mobile devices that includes an operating system, middleware.
By Adam Reimel. Outline Introduction Platform Architecture Future Conclusion.
Services. What is a Service? A Service is not a separate process. A Service is not a thread. A Service itself is actually very simple, providing two main.
CS371m - Mobile Computing Intents 1. Allow us to use applications and components that are already part of Android System – start activities – start services.
Android Mobile Application Development
Android Application -Architecture.
Lecture 2: Android Concepts
Android 01: Fundamentals
Mobile Application Development BSCS-7 Lecture # 2
Android Application Development 1 6 May 2018
Visit for more Learning Resources
Activity and Fragment.
Lecture 2 Zablon Ochomo Android Programming Lecture 2 Zablon Ochomo
Instructor: Mazhar Hussain
Architecture of Android
ANDROID AN OPEN HANDSET ALLIANCE PROJECT
Android Runtime – Dalvik VM
Activities, Fragments, and Events
MAD.
Activities and Intents
Anatomy of an Android App and the App Lifecycle
Android Mobile Application Development
Software Engineering in Mobile Computing
The Android Activity Lifecycle
CMPE419 Mobile Application Development
Application Fundamentals
Application Development A Tutorial Driven Course
Activities and Intents
HNDIT2417 Mobile Application Development
Android Introduction Platform Mihail L. Sichitiu.
Android Platform, Android App Basic Components
Emerging Platform#3 Android & Programming an App
SE4S701 Mobile Application Development
Application Fundamentals
Lecture 2: Android Concepts
CMPE419 Mobile Application Development
Android Development Tools
Activities, Fragments, and Intents
Presentation transcript:

Mobile Programming Lecture 2 By: Eliav Menachi

Resources http://developer.android.com/guide/topics/fundamentals.html

Linux Kernel Android relies on Linux version 2.6 The kernel acts as an abstraction layer between the hardware and the rest of the software stack Provides services such as security, memory management, process management, network stack, driver model..

Libraries Set of C/C++ libraries Surface Manager - manages access to the display subsystem and seamlessly composites 2D and 3D graphic layers from multiple applications System C library - a BSD-derived implementation of the standard C system library (libc) Media Libraries - based on PacketVideo's OpenCORE; 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 LibWebCore - web browser engine SGL - 2D graphics engine 3D libraries - based on OpenGL ES 1.0 APIs FreeType - bitmap and vector font rendering SQLite - relational database engine

Android Runtime Core libraries of the Java programming language (most of it) Every Android application runs in its own process Every process has its own instance of the Dalvik VM Dalvik can run multiple VMs efficiently .java files are compiled into .dex files Optimized for minimal memory footprint The Dalvik VM relies on the Linux kernel for underlying functionality such as threading and low-level memory management

Application Framework Views: including lists, grids, text boxes, buttons, and even an embeddable web browser Content Providers: enable applications to access data from other applications, or to share their own data Resource Manager: providing access to non-code resources such as localized strings, graphics, and layout files Notification Manager: enables display of custom alerts in the status bar Activity Manager: manages the lifecycle of applications

Application Fundamentals Java programming language The compiled Java code — along with any data and resource files required by the application — is bundled by the aapt tool into an Android package Android package - an archive file marked by an .apk suffix All the code in a single .apk file is considered to be one application Aapt: Android Asset Packaging Tool - This tool allows you to view, create, and update Zip-compatible archives (zip, jar, apk). It can also compile resources into binary assets.

Android application Every application runs in its own Linux process Android starts the process when any of the application's code needs to be executed Android shuts down the process when it's no longer needed and system resources are required by other applications Each process has its own Java virtual machine (VM) Each application is assigned a unique Linux user ID Permissions are set so that the application's files are visible only that user (there are ways to export them to other applications as well)

Application Components One application can make use of elements of other applications Android applications don't have a single entry point for everything in the application (no main() function, for example) Rather, they have essential components that the system can instantiate and run as needed.

Application Components There are four types of components Activities Services Broadcast receivers Content providers

Activity Presents a visual user interface Each activity is independent of the others Each activity is implemented as a subclass of the Activity base class 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

Services Runs in the background Each service extends the Service base class It's possible to connect (bind) to an ongoing service (and start the service if it's not already running) While connected, you can communicate with the service through an interface that the service exposes Like activities services run in the main thread of the application process Services often spawn another thread for time-consuming tasks

Broadcast receivers Component that receive and react to broadcast announcements Broadcasts originate from the system: i.e. battery is low, picture has been taken, user changed a language preference Broadcasts originate from Applications :i.e. to let other applications know that some data has been downloaded to the device and is available for them to use… Broadcast receivers do not display a user interface Broadcast receivers may start an activity in response to the information they receive Broadcast receivers may use the Notification Manager to alert the user Notifications can be: flashing the backlight, vibrating the device, playing a sound, and so on

Content providers A content provider makes a specific set of the application's data available to other applications The data can be stored in the file system, in an SQLite database, or in any other manner ... The content provider extends the ContentProvider base class to implement a standard set of methods However, applications do not call these methods directly. Rather they use a ContentResolver object and call its methods instead A ContentResolver can talk to any content provider

Activating components Content providers are activated when they're targeted by a request from a ContentResolver. The other three components — activities, services, and broadcast receivers — are activated by asynchronous messages called intents.

Intents An object that holds a message content For activities and services: names the action being requested URI of the data to act on For broadcast receivers names the action being announced

The manifest file Applications declare their components in a manifest file Bundled into the Android package Used for: declaring the application's components naming any libraries the application needs identifying any permissions the application expects to be granted

Manifest example <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android=“…." package=“…“ android:versionCode="1“ android:versionName="1.0"> <application android:icon=“…“ aandroid:label=“…"> <activity android:name=".Name 1“ android:label=“…"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".Name 2“ android:label=“…"> </application> <uses-sdk android:minSdkVersion="3" /> </manifest> The name attribute of the <activity> element names the Activity subclass that implements the activity. The icon and label attributes point to resource files containing an icon and label that can be displayed to users to represent the activity. The other components are declared in a similar way — <service> elements for services, <receiver> elements for broadcast receivers, and <provider> elements for content providers. Activities, services, and content providers that are not declared in the manifest are not visible to the system and are consequently never run. However, broadcast receivers can either be declared in the manifest, or they can be created dynamically in code (as BroadcastReceiver objects) and registered with the system by calling Context.registerReceiver().

Activating Activity An activity is launched by passing an Intent object to: Context.startActivity Activity.startActivityForResult (expects a result back from the activity) The responding activity can look at the initial intent that caused it to be launched: getIntent While executing Android pass additional intents onNewIntent lunched activity returns data to the initiator activity by: onActivityResult

Starting Activity Example Intent intent = new Intent(this,Activity.class); startActivity(intent);

Starting Service A service is started (or new instructions are given to an ongoing service) by passing an Intent object to Context.startService Android calls the service's onStart() method and passes it the Intent object. Similarly, an intent can be passed to Context.bindService() to establish an ongoing connection between the calling component and a target service. The service receives the Intent object in an onBind() call. (If the service is not already running, bindService() can optionally start it.)

Sending Broadcast An application can initiate a broadcast by passing an Intent object to methods like: Context.sendBroadcast() Context.sendOrderedBroadcast() Context.sendStickyBroadcast() Android delivers the intent to all interested broadcast receivers by calling their onReceive() methods

Shutting down components Content provider is active only while it's responding to a request from a ContentResolver. Broadcast receiver is active only while it's responding to a broadcast message. So there's no need to explicitly shut down these components. Android has methods to shut down activities and services in an orderly way: Activity can be shut down by calling its finish() method. One activity can shut down another activity (one it started with startActivityForResult()) by calling finishActivity(). Service can be stopped by calling: stopSelf Context.stopService Android shut down components: when they are no longer being used when Android must reclaim memory for more active components

Activities and Tasks Task - group of related activities, arranged in a stack The root activity in the stack is the one that began the task The activity at the top of the stack is one that's currently running When the user presses the BACK key, the current activity is popped from the stack, and the previous one resumes as the running activity Values for the task as a whole are set in the root activity

Activity stack The stack contains objects If a task has more than one instance of the same Activity subclass open, the stack has a separate entry for each instance Activities in the stack are never rearranged, only pushed and popped

General Behavior Suppose, for instance, that the current task has four activities in its stack — three under the current activity. The user presses the HOME key, goes to the application launcher, and selects a new application (actually, a new task). The current task goes into the background and the root activity for the new task is displayed. Then, after a short period, the user goes back to the home screen and again selects the previous application (the previous task). That task, with all four activities in the stack, comes forward. When the user presses the BACK key, the screen does not display the activity the user just left (the root activity of the previous task). Rather, the activity on the top of the stack is removed and the previous activity in the same task is displayed. The behavior just described is the default behavior for activities and tasks. But there are ways to modify almost all aspects of it. The association of activities with tasks, and the behavior of an activity within a task, is controlled by the interaction between flags set in the Intent object that started the activity and attributes set in the activity's <activity> element in the manifest. Both requester and respondent have a say in what happens.

Clearing the stack If the user leaves a task for a long time, the system clears the task of all activities except the root activity When the user returns to the task again, it's as the user left it, except that only the initial activity is present. The idea is that, after a time, users will likely have abandoned what they were doing before and are returning to the task to begin something new There are some activity attributes that can be used to control this behavior and modify it: alwaysRetainTaskState - The task retains all activities in its stack even after a long period. clearTaskOnLaunch - the stack is cleared down to the root activity whenever the user leaves the task and returns to it. finishOnTaskLaunch - This attribute is like clearTaskOnLaunch, but it operates on a single activity, not an entire task. And it can cause any activity to go away, including the root activity. If the user leaves and then returns to the task, it no longer is present.

Starting tasks An activity is set up as the entry point for a task by giving it an intent filter with: "android.intent.action.MAIN" as the specified action "android.intent.category.LAUNCHER" as the specified category A filter of this kind causes an icon and label for the activity to be displayed in the application launcher, giving users a way both to launch the task and to return to it at any time after it has been launched Imagine, for example, what could happen if the filter is missing: An intent launches a "singleTask" activity, initiating a new task, and the user spends some time working in that task. The user then presses the HOME key. The task is now ordered behind and obscured by the home screen. And, because it is not represented in the application launcher, the user has no way to return to it.

Processes and Threads The first application's components starts a Linux process for it with a single thread Additional components can run in other processes Additional threads can spawn for any process Imagine, for example, what could happen if the filter is missing: An intent launches a "singleTask" activity, initiating a new task, and the user spends some time working in that task. The user then presses the HOME key. The task is now ordered behind and obscured by the home screen. And, because it is not represented in the application launcher, the user has no way to return to it.

Processes Component process is controlled by the manifest file The component elements have a process attribute These attributes set: each component runs in its own process some components share a process components of different applications run in the same process The application element can set a default value that applies to all components

Processes 2 All components are instantiated in the main thread of the specified process All methods runs in the main thread of the process No component should perform long or blocking operations (such as networking operations or computation loops) Blocking operations will block any other components in the process Long operations can be spawned to separate threads

Processes 3 Android may decide to shut down a process at any point Application components running in the process are consequently destroyed The decision whether to terminate a process depends on the state of the process components A process is restarted for those components when there's again work for them to do

Threads Thread do background work The thread that hosts an activity should not also host time- consuming operations Anything that may not be completed quickly should be assigned to a different thread Threads are created in code using standard Java Thread objects Android provides a number of convenience classes for managing threads: Looper for running a message loop within a thread Handler for processing messages HandlerThread for setting up a thread with a message loop

Activity Lifecycle An activity has essentially three states: Active: when it is in the foreground of the screen Paused: lost focus but still visible to the user Stopped: completely obscured by another activity Paused: That is, another activity lies on top of it and that activity either is transparent or doesn't cover the full screen, so some of the paused activity can show through. A paused activity is completely alive (it maintains all state and member information and remains attached to the window manager), but can be killed by the system in extreme low memory situations. stopped It still retains all state and member information. However, it is no longer visible to the user so its window is hidden and it will often be killed by the system when memory is needed elsewhere.

Activity Lifecycle If an activity is paused or stopped, the system can drop it from memory either by asking it to finish (finish()), or simply killing its process When it is displayed again to the user, it must be completely restarted and restored to its previous state. As an activity transitions from state to state, it is notified of the change by calls to the following protected methods: void onCreate(Bundle savedInstanceState( void onStart() void onRestart() void onResume() void onPause() void onStop() void onDestroy()

Visible lifetime The visible lifetime of an activity happens between a call to onStart() until a corresponding call to onStop(). During this time, the user can see the activity on-screen, though it may not be in the foreground and interacting with the user. Between these two methods, you can maintain resources that are needed to show the activity to the user. For example, you can register a BroadcastReceiver in onStart() to monitor for changes that impact your UI, and unregister it in onStop() when the user can no longer see what you are displaying. The onStart() and onStop() methods can be called multiple times, as the activity alternates between being visible and hidden to the user.

foreground lifetime The foreground lifetime of an activity happens between a call to onResume() until a corresponding call to onPause(). During this time, the activity is in front of all other activities on screen and is interacting with the user. An activity can frequently transition between the resumed and paused states — for example, onPause() is called when the device goes to sleep or when a new activity is started, onResume() is called when an activity result or a new intent is delivered. Therefore, the code in these two methods should be fairly lightweight.

Lifecycle Activity Methods Next Killable? Description Method onStart() No Called when the activity is first created. onCreate() onResume() or onStop() Called when the activity is becoming visible to the user. onRestart() onPause() Called when the activity will start interacting with the user. onResume() Yes Called when the system is about to start resuming a previous activity. onRestart() or onDestroy() Called when the activity is no longer visible to the user onStop() nothing The final call you receive before your activity is destroyed. onDestroy()

Saving Persistent State There are generally two kinds of persistent state: shared document - like data (SQLite) internal state – like user preferences getPreferences(int): used for retrieving and modifying a set of name/value pairs associated with the activity getSharedPreferences(int): used for retrieving and modifying a set of name/value pairs shared across multiple application components

Preferences example Retrieving info: Writing info: SharedPreferences ref = getSharedPreferences(TAG, MODE_PRIVATE); String lastActivity = ref.getString(LAST_ACTIVITY, "Ex2"); Writing info: SharedPreferences.Editor ed = ref.edit(); ed.putString(LAST_ACTIVITY, "Activity3"); ed.commit();