Presentation is loading. Please wait.

Presentation is loading. Please wait.

Mobile Programming Lecture 2

Similar presentations


Presentation on theme: "Mobile Programming Lecture 2"— Presentation transcript:

1 Mobile Programming Lecture 2
By: Eliav Menachi

2 Resources

3

4 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..

5 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

6 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

7 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

8 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.

9 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)

10 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.

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

12 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

13 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

14 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

15 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

16 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.

17 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

18 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

19 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().

20 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

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

22 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.)

23 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

24 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

25 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

26 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

27 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.

28 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.

29 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.

30 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.

31 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

32 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

33 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

34 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

35 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.

36 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()

37

38 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.

39 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.

40 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()

41 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

42 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();


Download ppt "Mobile Programming Lecture 2"

Similar presentations


Ads by Google