android fundamentals and components kris secor mobile application development

41
ART40544 Android Fundamentals and Components Kris Secor Mobile Application Development

Upload: candace-booker

Post on 29-Dec-2015

223 views

Category:

Documents


0 download

TRANSCRIPT

ART40544Android Fundamentals and Components

Kris Secor

Mobile Application Development

1. Activities

2. Services

3. Broadcast Receivers

4. Content Providers

Mobile Application Development

Overview of Terms/Life Cycles

Activity is the basic building block of every visible android application.

It provides the means to render a GUI. Every screen in an application is an activity

by itself. We can call each visible component as an

activity in android. Though more than one activities work

together to present an application sequence, each activity is an independent entity.

Mobile Application Development

Android Activity

Mobile Application Development

Life Cycle of an Activity in Android

Service is another building block of android applications which does not provide any UI.

It is a program that can run in the background for an indefinite period.

That means if we want to do a long operation (example: download data from internet), then we need to create an Android service for this purpose.

Mobile Application Development

Android Services

Started Service (Unbounded) This type of service is created and called by Android

Activities. There is no 2 way communication between Android Activity and Service. The Activity just started the service and does not care about the status of the service. The Service will finish it’s work and automatically stops when finish it’s job.

Bound Service (Bounded) This type of Android Service is for 2 way

communication. Suppose an Android Activity has started a bound service, then Activity can be notified the status by the service.

Mobile Application Development

2 Types of general Android Service

Mobile Application Development

LifeCycle of a Service in Android

Broadcast receivers can receive or respond to any broadcast announcements

Eg:when a new message comes to your inbox, this information will be broadcast to all applications. If any application wants to do something with the new message, then it can receive the broadcasted message details (Like: sender’s number, content etc.) and process accordingly.

Mobile Application Development

Android Broadcast Receivers

Content Providers are a separate league of components that expose a specific set of data to applications.

If you want to search a contact in your contact database (Like: name, number etc), then you can use Content Provider for this purpose. You can say Content provider is the pointer in your application to a specific data base from other application.

Mobile Application Development

Android Content Providers

C.R.U.D.

Mobile Application Development

Live Cycle of a Content Provider

We need to see how the aforementioned component communicate which is why we need to know intents and intent filters.

Mobile Application Development

Intents

Intents are messages that are passed between components.

They are not API’s 1. API calls are synchronous while intent-

based invocation is asynchronous (mostly)

2. API calls are bound at compile time while intent-based calls are run-time bound (mostly)

Mobile Application Development

Android Intents

In simple word, the core android components of an application — activities, services, and broadcast receivers — are activated through messages, called intents.

For example an activity can send an intent to the Android system which starts another activity. So Intent is just a way to send message in android.

Mobile Application Development

Intents (cont.)

Implicit intents specify the action which should be performed by other components or applications.

For Example: If you want to open an URL in a web browser from your application code, Then following code tells the Android system to view a webpage. Typically the web browser is registered to this Intent but other components could also register themselves to this intent. That means if you have installed web browsers like IE, Mozilla Firfox and Google Chrome, then all browsers might be registered to the intent (Intent.ACTION_VIEW) to show a web page as per you request.

Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.mm214.com"));

startActivity(i); If only one component (our web browser in this example) is found, Android

starts this component directly. If several components are identified by the Android system, the user will get an selection dialog and can decide which component should be used for that Intent.

Mobile Application Development

Implicit Intents

Explicit intents explicitly define the exact component which should be called by the Android system, by using the Java class as identifier.

The following code shows how to create an explicit intent and send it to the Android system. That means Android system will directly execute your intent request as you requested. Explicit intents are typically used within an application as the classes in an application are controlled by the application developer. If you want to open an Android Activity from another activity, then below is the code using intent. Also you can send some data to that activity if required.

Intent i = new Intent(this, ActivityTwo.class); i.putExtra("First Value", "This First Value for ActivityTwo"); i.putExtra("Second Value", "This Second Value ActivityTwo");

Mobile Application Development

Explicit Intents

To inform the system which implicit intents they can handle, activities, services, and broadcast receivers can have one or more intent filters. Each filter describes a capability of the component, a set of intents that the component is willing to receive.

Eg:A note saving application might have two filters — one for starting up with a specific note that the user can view or edit, and another for starting with a new, blank note that the user can fill in and save.

Mobile Application Development

Android Intent Filters

Basically IntentFilters are defined in the AndroidManifest.xml file.

For a BroadcastReceiver it is possible to define in coding.

IntentFilters are defined by its category, action and data filters. It can also contain additional metadata. If a component does not define an Intent filter, then it can only be called by explicit Intents.

Mobile Application Development

Intent Filters (cont.)

Interfaces: Two Alternatives Code or XML

You have two ways you can create the interface(s) of your Application.

1.Code = write code using SDK with classes like LinearLayout, TextView, ……

2.XML = create XML files in res/Layout (i.e. main.xml) that contain Android XML view tags like <LinearLayout> <TextView>, etc.

Lets look at this option first

Option: XML Interface

XML Interface Creation

Generally, I would say if it is possible, doing XML would be better as it means a decoupling of design from Java code.

You can have both in your system…. Lets discuss this first.

The Layout --- the interface

Layouts defined with XML located in

res/layout

The Layout-the interface res/layout/main.xml = contains layout for

interface<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:orientation="vertical"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

>

<TextView

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="@string/hello"

/>

</LinearLayout>

The above will create an interface in vertical (versus portrait) mode that fills the parent

Both in width wraps and content as necessary.

XML interface

it's a tree of XML elements, ◦ Inspired by web authoring◦ Build up UI quickly

each node is the name of a View class (example is just one View element). ◦ Create your own View ---extends ◦ Each node can have multiple attributes◦ Look to API for details

XML interface

<TextView xmlns:android="http://schemas.android.com/apk/res/android"  android:layout_width="fill_parent"  android:layout_height="fill_parent"  android:text="@string/hello"/>◦ xmlns:android XML namespace declaration that tells the Android tools

that you are going to refer to common attributes defined in the Android namespace. The outermost tag in every Android layout file must have this attribute.

◦ android:layout_width This attribute defines how much of the available width on the screen this View should consume. As it's the only View so you want it to take up the entire screen, which is what a value of "fill_parent" means.android:layout_height This is just like android:layout_width, except that it refers to available screen height.

◦ android:text This sets the text that the TextView should display. In this example, you use a string resource instead of a hard-coded string value. The hello string is defined in the res/values/strings.xml file.

Using Eclipse IDE to Visually Create XML file

Visual creation of XML file Create New->Other->Android->XML file-

◦ Select for layout type◦ Play with it….

drag and drop

Using Eclipse IDE to Visually Create XML file

Visual creation of XML file Create New->Other->Android->XML file-

◦ Select for layout type◦ Play with it….

drag and drop

Visually Creating XML interface I dragged and dropped an EditText view and

a Button. Below I show you the corresponding code.

res/layout/main2.xml

<?xml version="1.0" encoding="utf-8"?>

<AbsoluteLayout

xmlns:android="http://schemas.android.com/apk/res/android"

android:orientation="vertical"

android:layout_width="match_parent"

android:layout_height="match_parent">

<EditText android:text="@string/hello" android:id="@+id/editText1" android:inputType="textMultiLine" android:layout_width="169dp" android:layout_height="115dp" android:layout_x="11dp" android:layout_y="20dp"></EditText>

<Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" android:layout_x="27dp" android:layout_y="146dp"></Button>

</AbsoluteLayout>

Besides drag and drop you can edit the xml file directly. Lets discuss some of the Android XML Interface related tags

XML Interface tags

Control structure of interface

Layout Tags

Layout Tags

Determines how the layout is structured. Some Tags

LinearLayout A Layout that arranges its children in a single column or a single row.

The direction of the row can be set by calling setOrientation(). You can also specify gravity, which specifies the alignment of all the child elements by calling setGravity() or specify that specific children grow to fill up any remaining space in the layout by setting the weight member of LinearLayout.LayoutParams. The default orientation is horizontal.

AbsoluteLayout A layout that lets you specify exact locations (x/y coordinates) of its

children. Absolute layouts are less flexible and harder to maintain than other types of layouts without absolute positioning.

RelativeLayout FrameLayout TableLayout

LinearLayout XML tag Visual creation of XML file XML Attributes Attribute Name Related

Method Description android:baselineAligned setBaselineAligned(boolean) When set to false, prevents the layout from aligning its children's baselines.  android:baselineAlignedChildIndex setBaselineAlignedChildIndex(int) When a linear layout is part of another layout that is baseline aligned, it can specify which of its children to baseline align to (that is, which child TextView).  android:gravity setGravity(int) Specifies how to place the content of an object, both on the x- and y-axis, within the object itself.  android:measureWithLargestChild When set to true, all children with a weight will be considered having the minimum size of the largest child.  android:orientation setOrientation(int) Should the layout be a column or a row? Use "horizontal" for a row, "vertical" for a column.  android:weightSum Defines the maximum weight sum. 

Control structure of interface, but commonly a sub-area

Related Layout Tags

ListView <ListView …..> A view that shows items in a

vertically scrolling list.Attributes android:divider Drawable or color to draw

between list items.  android:dividerHeight Height of the divider.  android:entries Reference to an array resource

that will populate the ListView.  android:footerDividersEnabled When set to false,

the ListView will not draw the divider before each footer view. 

android:headerDividersEnabled When set to false, the ListView will not draw the divider after

each header view. 

Gallery <Gallery ….>

A view that shows items in a center-locked, horizontally scrolling list.

The default values for the Gallery assume you will be using Theme_galleryItemBackground as the background for each View given to the Gallery from the Adapter. If you are not doing this, you may need to adjust some Gallery properties, such as the spacing.

Attributes android:animationDuration setAnimationDuration(int) Sets

how long a transition animation should run (in milliseconds) when layout has changed. 

android:gravity setGravity(int) Specifies how to place the content of an object, both on the x- and y-axis, within the object itself. 

android:spacing setSpacing(int)   android:unselectedAlpha setUnselectedAlpha(float) Sets the

alpha on the items that are not selected. 

Code—setting up Gallery

@Overridepublic void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.main);

    Gallery gallery = (Gallery) findViewById(R.id.gallery);    gallery.setAdapter(new ImageAdapter(this));

    gallery.setOnItemClickListener(new OnItemClickListener() {        public void onItemClick(AdapterView parent, View v, int position, long id) {            Toast.makeText(HelloGallery.this, "" + position, Toast.LENGTH_SHORT).show();        }    });}

Making the elements of your GUI

Views and ViewGroups

Views and ViewGroups An Activity can contain views and ViewGroups.

android.view.View.* = base class for all Views.◦ example sub-classes include: TextView, ImageView, etc.

android.view.ViewGroup = Layout for views it contains, subclasses include◦ android.widget.LinearLayout◦ android.widget.AbsoluteLayout◦ android.widget.TableLayout◦ android.widget.RelativeLayout◦ android.widget.FrameLayout◦ android.widget.ScrollLayout

LinearLayout (<LinearLayout> or android.widget.LinearLayout)

arranges by single column or row. child views can be arranged vertically or

horizontally. <?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:orientation="vertical" >

<Text View

android:layout_width=“fill_parent”android:layout_height=“wrap_content”android:text=“@string/hello”/>

</LinearLayout>

Linear Layout Example<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent“ android:orientation="vertical" >

<Button android:id="@+id/btn_webbrowser" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Web Browser“ android:onClick="onClickWebBrowser" />

<Button android:id="@+id/btn_makecalls" android:layout_width="fill_parent" android:layout_height="wrap_content“ android:text="Make Calls" android:onClick="onClickMakeCalls" />

<Button android:id="@+id/btn_showMap" android:layout_width="fill_parent" android:layout_height="wrap_content“ android:text="Show Map" android:onClick="onClickShowMap" />

<Button android:id="@+id/btn_launchMyBrowser" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Launch My Browser" android:onClick="onClickLaunchMyBrowser" />

</LinearLayout>

LinearLayout attributes

You can set either in XML or with set*() methods.

i.e. Xml android:orientation=“vertical”

code (ll is LinearLayout instance) ll.setOrientation(VERTICAL);

Each View or ViewGroup can have its own set of attributes…but, some are very common

Attribute Description

layout_width specifies width of View or ViewGroup

layout_height specifies height

layout_marginTop extra space on top

layout_marginBottom extra space on bottom side

layout_marginLeft extra space on left side

layout_marginRight extra space on right side

layout_gravity how child views are positioned

layout_weight how much extra space in layout should be allocated to View (only when in LinearLayout or TableView)

layout_x x-coordinate

layout_y y-coordinate