basics 4

53
BASICS Smartphone Programming (CPE 490/590) Michael T. Shrove

Upload: michael-shrove

Post on 17-Aug-2015

26 views

Category:

Documents


0 download

TRANSCRIPT

BASICSSmartphone Programming (CPE 490/590)

Michael T. Shrove

ANDROID

Fundamentals

• Android application are written in Java• Android SDK tools compile the code in an .apk file• Resources• Data• Code

• APK file are what android powered device use

Android App Security• Once installed all apps live in their own “sandbox”• The Android operating system is a multi-user Linux

system in which each app is a different user.• By default, the system assigns each app a unique Linux

user ID. The system sets permissions for all the files in an app so that only the user ID assigned to that app can access them.

• Each process has its own virtual machine (VM), so an app's code runs in isolation from other apps.

• By default, every app runs in its own Linux process.

Android App Security++• In this way, the Android system implements the principle

of least privilege. That is, each app, by default, has access only to the components that it requires to do its work and no more.• However, there are ways for an app to share data with other apps

and for an app to access system services:

• An app can request permission to access device data such as the user's contacts, SMS messages, the mountable storage (SD card), camera, Bluetooth, and more.

• All app permissions must be granted by the user at install time.

App Components

App

Activities

Content Providers

Services

Broadcast Receivers

• App components are the essential building blocks of an Android app.

• Each component is a different point through which the system can enter your app.

• Not all components are actual entry points for the user and some depend on each other, but each one exists as its own entity and plays a specific role

• Each one is a unique building block that helps define your app's overall behavior.

Activities• An activity represents a single screen

with a user interface. • For example, an email app might have one

activity that shows a list of new emails, another activity to compose an email, and another activity for reading emails.

• Although the activities work together to form a cohesive user experience in the email app, each one is independent of the others.

• As such, a different app can start any one of these activities (if the email app allows it).

• For example, a camera app can start the activity in the email app that composes new mail, in order for the user to share a picture.

• An activity is implemented as a subclass of Activity

App

Activities

Content Providers

Services

Broadcast Receivers

Services• A service is a component that runs in the

background to perform long-running operations or to perform work for remote processes.

• A service does not provide a user interface. • For example, a service might play

music in the background while the user is in a different app, or it might fetch data over the network without blocking user interaction with an activity.

• Another component, such as an activity, can start the service and let it run or bind to it in order to interact with it.

• A service is implemented as a subclass of Service

App

Activities

Content Providers

Services

Broadcast Receivers

Content Providers• A content provider manages a shared set

of app data. • SQLite database, Web, Persistent storage location

your app can access.

• Through the content provider, other apps can query or even modify the data.

• For example, the Android system provides a content provider that manages the user's contact information.

• Content providers are also useful for reading and writing data that is private to your app and not shared.

• For example, the Note Pad sample app uses a content provider to save notes.

• A content provider is implemented as a subclass of ContentProvider and must implement a standard set of APIs that enable other apps to perform transactions.

App

Activities

Content Providers

Services

Broadcast Receivers

Broadcast Receivers• A broadcast receiver is a component that

responds to system-wide broadcast announcements.

• Many broadcasts originate from the system.• For example, a broadcast announcing that the screen

has turned off, the battery is low, or a picture was captured.

• Apps can also initiate broadcasts.• For example, to let other apps know that some data has

been downloaded to the device and is available for them to use.

• Although broadcast receivers don't display a user interface, they may create a status bar notification to alert the user when a broadcast event occurs.

• More commonly, though, a broadcast receiver is just a "gateway" to other components and is intended to do a very minimal amount of work.

• For instance, it might initiate a service to perform some work based on the event.

• A broadcast receiver is implemented as a subclass of BroadcastReceiver and each broadcast is delivered as an Intent object.

App

Activities

Content Providers

Services

Broadcast Receivers

Intents• Three of the four component types—activities, services,

and broadcast receivers—are activated by an asynchronous message called an intent.

• An intent is created with an Intent object, which defines a message to activate either a specific component or a specific type of component—an intent can be either explicit or implicit, respectively.

• The other component type, content provider, is not activated by intents. Rather, it is activated when targeted by a request from a ContentResolver.

Methods for Starting Components• There are separate methods for activating each type of

component:• You can start an activity (or give it something new to do) by

passing an Intent to startActivity() or startActivityForResult() (when you want the activity to return a result).

• You can start a service (or give new instructions to an ongoing service) by passing an Intent to startService(). Or you can bind to the service by passing an Intent to bindService().

• You can initiate a broadcast by passing an Intent to methods like sendBroadcast(), sendOrderedBroadcast(), or sendStickyBroadcast().

• You can perform a query to a content provider by calling query() on a ContentResolver.

Manifest File• Before the Android system can start an app component,

the system must know that the component exists by reading the app's AndroidManifest.xml file (the "manifest" file).

• Your app must declare all its components in this file, which must be at the root of the app project directory.

• The manifest does a number of things in addition to declaring the app's components, such as:• User Permissions• Minimum API Level required by the app• Declare hardware and software features used or required by the

app• API libraries the app needs to be linked against

Intent Filters• 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 — what an activity or service can do and what types of broadcasts a receiver can handle. It opens the component to receiving intents of the advertised type, while filtering out those that are not meaningful for the component.

App Requirements• There are a variety of devices powered by Android and

not all of them provide the same features and capabilities. • In order to prevent your app from being installed on

devices that lack features needed by your app, it's important that you clearly define a profile for the types of devices your app supports by declaring device and software requirements in your manifest file.

App Resources• An Android app is composed of more than just code• It requires resources that are separate from the source

code.• images,• audio files• anything relating to the visual presentation of the app.

• For every resource that you include in your Android project, the SDK build tools define a unique integer ID, which you can use to reference the resource from your app code or from other resources defined in XML.

• res/layout/activity2.xml ------> R.id.Activity2

Activities

What is an Activity?• An Activity is an application component that provides a

screen with which users can interact in order to do something, such as dial the phone, take a photo, send an email, or view a map.

• Each activity is given a window in which to draw its user interface. The window typically fills the screen, but may be smaller than the screen and float on top of other windows.

• Apps usual consist of multiple Activities

Activity Lifecycle

Managing the Activity Lifecycle

App

• Managing the lifecycle of your activities by implementing callback methods is crucial to developing a strong and flexible application.

• An activity can exist in essentially three states:• Resumed, Paused,

Stopped

Lifecycle States• Resumed

• The activity is in the foreground of the screen and has user focus. (This state is also sometimes referred to as "running".)

• Paused• Another activity is in the foreground and has focus, but this one is

still visible. That is, another activity is visible on top of this one and that activity is partially transparent or doesn't cover the entire screen.

• Stopped• The activity is completely obscured by another activity (the activity is

now in the "background"). A stopped activity is also still alive (the Activity object is retained in memory, it maintains all state and member information, but is not attached to the window manager). However, it is no longer visible to the user and it can be killed by the system when memory is needed elsewhere.

Implementing the lifecycle callbacks• When an activity transitions into and out of the different

states described above, it is notified through various callback methods.

• All of the callback methods are hooks that you can override to do appropriate work when the state of your activity changes.

• Activity must have onCreate() callback by default.

Lifecycle Callback

StatesName Description

onCreate Called when the activity is first created.

onRestart Called after the activity has been stopped, just prior to it being started again. Always followed by onStart()

onStart Called just before the activity becomes visible to the user. Followed by onResume() if the activity comes to the foreground, or onStop() if it becomes hidden.

onResume Called just before the activity starts interacting with the user. At this point the activity is at the top of the activity stack, with user input going to it. Always followed by onPause().

onPause Called when the system is about to start resuming another activity. Followed either by onResume() if the activity returns back to the front, or by onStop() if it becomes invisible to the user.

onStop Called when the activity is no longer visible to the user. Followed either by onRestart() if the activity is coming back to interact with the user, or by onDestroy() if this activity is going away.

onDestroy Called before the activity is destroyed. This is the final call that the activity will receive.

Activity and the UI• The Activity class takes care of creating a window for you

in which you can place your UI with setContentView().• In code, an activity is a Java class, that extends the

Activity base class.• The activity class loads its UI components using the XML

file defined in your res/layout folder.• Every activity you have in your app, must be declared in

your AndroidManifest.xml file.

Starting Activities• The startActivity( ) method invokes another activity but

does not return a result to the current activity.

Activity #1 Activity #2Intent

Starting Activities• Sometimes, you might want to receive a result from the

activity that you start. In that case, start the activity by calling startActivityForResult() (instead of startActivity())

Activity #1 Activity #2

Intent

Data

Sending Results back• In your SecondActivity set the data which you want to

return back to FirstActivity. If you don't want to return back, don't set any.

• If you don't want to return data:

Receiving the results• If you want to receive the results after Activity2 sends it

back using an Intent, you implement the onActivityResult() method.

Activity Example• Creating a new activity• Adding Lifecycle Callbacks• Starting an Activity• Starting an Activity for Results

IOS

App Architecture

App

Model

ViewController

Model-View-Controller (MVC)• The Model-View-Controller (MVC)

design pattern assigns objects in an application one of three roles: model, view, or controller.

• The pattern defines not only the roles objects play in the application, it defines the way objects communicate with each other.

• Each of the three types of objects is separated from the others by abstract boundaries and communicates with objects of the other types across those boundaries.

MVC• MVC is central to a good design for a Cocoa application. • The benefits of adopting this pattern are numerous.

• Many objects in these applications tend to be more reusable, and their interfaces tend to be better defined.

• Applications having an MVC design are also more easily extensible than other applications.

• Moreover, many Cocoa technologies and architectures are based on MVC and require that your custom objects play one of the MVC roles.

Model Objects• Model objects encapsulate the data specific to an

application and define the logic and computation that manipulate and process that data. • For example, a model object might represent a character in a game

or a contact in an address book.

• A model object can have to-one and to-many relationships with other model objects, and so sometimes the model layer of an application effectively is one or more object graphs.

• Much of the data that is part of the persistent state of the application (whether that persistent state is stored in files or databases) should reside in the model objects after the data is loaded into the application.

Model Objects• Ideally, a model object should have no explicit connection

to the view objects that present its data and allow users to edit that data—it should not be concerned with user-interface and presentation issues.

• Communication: User actions in the view layer that create or modify data are communicated through a controller object and result in the creation or updating of a model object.

• When a model object changes (for example, new data is received over a network connection), it notifies a controller object, which updates the appropriate view objects.

MVC

View Objects• A view object is an object in an application that users can see.• A view object knows how to draw itself and can respond to user

actions. • A major purpose of view objects is to display data from the

application’s model objects and to enable the editing of that data. • Despite this, view objects are typically decoupled from model objects in

an MVC application.

• Both the UIKit and AppKit frameworks provide collections of view classes, and Interface Builder offers dozens of view objects in its Library.

• Communication: View objects learn about changes in model data through the application’s controller objects and communicate user-initiated changes• For example: text entered in a text field—through controller objects to an

application’s model objects.

MVC

Controller Objects• A controller object acts as an intermediary between one or

more of an application’s view objects and one or more of its model objects.

• Controller objects are thus a conduit through which view objects learn about changes in model objects and vice versa.

• Controller objects can also perform setup and coordinating tasks for an application and manage the life cycles of other objects.

• Communication: A controller object interprets user actions made in view objects and communicates new or changed data to the model layer.

• When model objects change, a controller object communicates that new model data to the view objects so that they can display it.

MVC

Application Lifecycle

Execution States for Apps• At any given moment, your app is in one of the states

listed in the next table. • The system moves your app from state to state in

response to actions happening throughout the system. • For example, when the user presses the Home button, a

phone call comes in, or any of several other interruptions occurs, the currently running apps change state in response.

App StatesState Description

Not Running The app has not been launched or was running but was terminated by the system.

Inactive The app is running in the foreground but is currently not receiving events. (It may be executing other code though.) An app usually stays in this state only briefly as it transitions to a different state.

Active The app is running in the foreground and is receiving events. This is the normal mode for foreground apps.

Background The app is in the background and executing code. Most apps enter this state briefly on their way to being suspended. However, an app that requests extra execution time may remain in this state for a period of time. In addition, an app being launched directly into the background enters this state instead of the inactive state.

Suspended The app is in the background but is not executing code. The system moves apps to this state automatically and does not notify them before doing so. While suspended, an app remains in memory but does not execute any code.When a low-memory condition occurs, the system may purge suspended apps without notice to make more space for the foreground app.

State Delegates• Most state transitions are accompanied by a

corresponding call to the methods of your app delegate object.

• These methods are your chance to respond to state changes in an appropriate way.

• These methods are listed below, along with a summary of how you might use them.

State Delegates TableDelegate Description

application:willFinishLaunchingWithOptions

This method is your app’s first chance to execute code at launch time.

application:didFinishLaunchingWithOptions

This method allows you to perform any final initialization before your app is displayed to the user.

applicationDidBecomeActive Lets your app know that it is about to become the foreground app. Use this method for any last minute preparation.

applicationWillResignActive Lets you know that your app is transitioning away from being the foreground app. Use this method to put your app into a quiescent state.

applicationDidEnterBackground Lets you know that your app is now running in the background and may be suspended at any time.

applicationWillEnterForeground Lets you know that your app is moving out of the background and back into the foreground, but that it is not yet active.

applicationWillTerminate Lets you know that your app is being terminated. This method is not called if your app is suspended.

App Termination• Apps must be prepared for termination to happen at any

time and should not wait to save user data or perform other critical tasks.

• System-initiated termination is a normal part of an app’s life cycle.

• The system usually terminates apps so that it can reclaim memory and make room for other apps being launched by the user, but the system may also terminate apps that are misbehaving or not responding to events in a timely manner.

App Termination• Suspended apps receive no notification when they are

terminated; the system kills the process and reclaims the corresponding memory.

• If an app is currently running in the background and not suspended, the system calls the applicationWillTerminate: of its app delegate prior to termination.

• The system does not call this method when the device reboots.• In addition to the system terminating your app, the user can

terminate your app explicitly using the multitasking UI. • User-initiated termination has the same effect as terminating a

suspended app. • The app’s process is killed and no notification is sent to the

app.

Starting ViewController• 2 methods for starting a viewcontroller from another

viewcontroller.• Method #1: Use built in Storyboard connection (example

will be shown in class)• Method #2: By Code (shown in Figure 1)

Figure 1

Passing Data between ViewControllers

• Since there are two methods for starting a viewcontroller, there is likewise two methods for passing data from VC to VC.

• Method #1: Pass data from VC to VC using method #2 of “Starting ViewController” and use the VC’s properties.

• Method #2: Pass data from VC to VC using method #1 of “Starting ViewController” slide but add prepareForSegue method.

iOS Examples• Storyboard• Adding ViewControllers and Views• Presenting ViewControllers• Passing Data

References• https://developer.android.com/guide• https://developer.apple.com