Professional Documents
Culture Documents
I know this is a little lame but... Who am I? Who are you guys? What kind of programming experience do you have? Any experience with Android / mobile app development? What are you hoping to get out of the course?
Android Architecture
Applications
Fairly self explanatory, this upper layer is where the applications themselves live Set of services and systems available to all application
Application Framework
Views: used to build applications includes: lists, grids, text boxes, buttons, and more Content Providers: allow access to data from other applications, and to share own data
Resource Manager: access to non-code resources, like images and layout files Notification Manager: lets applications display custom alerts Activity Manager: application lifecycle management and stack navigation System C Library standard linux style system C library Media Libraries based on OpenCORE supports, MPEG4, H.264, MP3, AAC, AMR, JPG, and PNG formats among some others
Libraries
Surface Manager manages the display LibWebCore modern web browser engine supports Android browser and web views SGL 2D graphics engine 3D libraries based on Open GL 1.0 APIs FreeType font rendering library SQLite database engine Set of core libraries that contains most of the functionalities of core Java libraries Applications all run in a Dalvik Virtual Machine
Android Runtime
Linux Kernel
Linux 2.6 Kernel Manages interaction between hardware and the rest of the software stack Provides memory management, process management, network stack, and driver model services
Where do we start?
From google, you will need to signup for a gmail account to access this, however no additional application or signup is necessary anymore. You will need to go to http://appinventor.googlelabs.com/learn/setup/ Follow the instruction to configure your computer.
This is the app inventor palette, and will appear on the left side of the screen You drag and drop elements from here to add them to the canvas Click on the question marks to go to a description of that element
This is the viewer, or canvas. It shows what you'll see on the screen You arrange your elements here At the bottom are non-visible components
This is the components pane, here you can see the things you have added to your view You can rename and delete components using the buttons near the bottom If you have added any media they will appear in the media section below this pane
This is the properties tab, here you can set default values for your components Also allows you to set height and width Settings in here will be the initial settings when the component loads but may be changed later
This is the block editor where we will put together the code for an app inventor project There are built-in functionalities and we can add our own either based on the components we added or functions we need to create
Designed to address performance issues of handheld environment Traditional Java virtual machines include all the libraries used to build each application Android Libraries could be 10-20MB or more The Dalvik VM reuses parts of the various libraries to reduce the size by half or more (.jar vs .dex) It does not at this time implement Just-In-Time compilation
Dalvik VM continued
Attempting to reduce instruction set by nearly 30 percent Performance speed increase due to this particulary important for handheld devices as we expect very responsive performance
This means you cannot execute Java byte code in android, despite java being the language it is built on You must convert Java code to .dex Dalvik VM files
We covered this pretty well back in lecture one Important to remember that there are two layers of libraries we work with
These are combined in the Dalvik VM, check your book for more details on the specific APIs Limitations: USB connections, Camera, Video, Headphones, Battery, Bluetooth
Android Emulator
The Android UI
Fourth Generation UI like JavaFX or Microsoft Silverlight. Interfaces (called Views) are declared in XML files (these are our building blocks) These can be grouped into View Groups A full screen or menu is called an Activity and it made up of multiple views and view groups Lifecycle of the application works at activity level (start, stop, pause, resume, etc.)
Intents
A combination of ideas intended to achieve an action It is basically a passive data structure containing information on the action to be performed 2 main parts: action and data Accessed through the R class Can be used for simple strings or files, but also for XML based views and more I.D.s are autogenerated and facilitate easy access and use of resources
Resources
Content Provider
Abstract wrapper for data sources to make them appear to be a consumer and emitter of RESTful services RESTful Representational State Transfer Focuses on using the http verbs and URIs to manage web services, more on this as we move on Somewhat interesting as Google uses SOAP (Simple Object Access Protocol) for almost all of their web services
For some more info on android packages and components see Ch 1. in your book
Includes: Buttons, Labels, Textfields, etc. Knows how to draw itself (Fourth Generation)
Uses: broadcast a message, start a service, launch activity, display web page, dial a number May be initiated by your application or from a separate application
Content Provider and Services these provide access to resources and functions AndroidManifest.xml important file similar to web.xml in J2EE
Let's look at how these parts come together when you make an app Open up Eclipse New Project Android Project You should see a form to create a new project Give your project a name, let it create a new project in the workspace, and select an Android Version (2.1 or 2.2 will usually be best)
Application name will appear at the top of your application Package name should be the initial package to create Create Activity will create an initial activity (UI Screen) Min SDK Version should be set to match your android version Fill this out: Package = com.helloclass Activity = HelloActivity
Click Finish this will build an application skeleton based on your settings Now we move on to working on the application
Expand the app folder, src folder, and package, till you get to the .java file Open that up and take a look You should see a class implementation and the OnCreate function Notice how things are broken out in the package explorer
Much like the work we did on the app inventor, regular Android apps are event driven Given the graphical nature and interface restrictions of mobile apps this is necessary OnCreate is an event triggered whenever the activity is created, it's a lifecycle event and not something we call Much of what we will be working with will work like this as we move forward
super.onCreate(savedInstanceState)
This will call the base activity onCreate method and load any saved state information This will load the views for the activity It will get the information from the resources (res), layout group, main.xml file
setContentView(R.layout.main)
Eclispse should add the include for android.widget.TextView Since we are not adding this properly through an xml file we need to get change the setContentView line
setContentView(tv);
Now run your application Eclipse should ask you about what you want it to run as, select android application You will also need to let ADT create an emulator to run it in You can look to Ch. 2 of our book for some more instruction on run configurations Now we will take a look at the application structure
Examining an App
For now we are just going to take a look at the res resource folder Underneath the top layer res folder you will see several others, you can add more here as needed and create even deeper levels These are accessed with the R resource class
Open up Layout main.xml This will open a area for you to do the layout graphically In the bottom of that window you should see a main.xml tab, click that to see the code view You'll see we already have a text view element in there, lets see what thats all about Go back into you app and change the code
Resources
Raw resources: video, sound, etc. Assets: these resources do not get generated id's and are not compiled
Resources
Values are not hard coded in, meaning they can be changed without recompiling and redeploying One point of reference, changing the resource changes that value everywhere it is used
Imagine the marketing department decides on a font change, you change the setting on your string resources and you are all done
Strings several forms of strings Layouts used to build an UI screen Colors Identifiers for hex color codes Dimensions size information for elements Images images, .jpg .gif .png and so on Drawable many options, colored shapes XML arbitrary xml file, must be parsed Raw raw data, non-compiled binary or text Assets arbitrary non-compiled files, no ids
Strings
Can hold values with plain strings, java formatted strings, and even html tagged strings (mostly supports formatting tags)
<resoursces>
</resoursces>
Strings
activity.getString(R.string.mystring);
<TextView... android:text=@string/mysting />
<string name=javastring> Hello %1$s </string> String myJavaString = activity.getString (R.string.javastring); MyJavaString = String.format(myJavaString, World!)
Strings
<string name=htmlString>This is <i>slanted</i>, this is <b>bold</b></string> String htmlString = activity.getString(R.string.htmlString) Spanned mytextspan = android.text.Html.fromHtml(htmlString) textview.setText(mytextspan) Or <TextView... android:text=@string/htmlString It will recognize this as an html string and handle it
Colors
Accessed through R.color.<id> Many values per file (like string) in /res/values Node structure /resources/color
Colors
To use a color
Dimensions
Stores dimension information that you use to style your UIs and change without changing the code Dimensions may be specified in
px Pixels in Inches mm: Millimeters pt: Points dp: Density-independent pixels (based on 160 dpi) sp: Scale-independent pixels
Dimensions
Accessed by R.dimen.<id> Many per file stored in /res/values Node Structure /resources/dimen Usage example
Image
ID will be the filename minus the extension Accessed with R.drawable.<id> Each image file is placed seperately in /res/drawable
Image
<Button... android:background=@image/<filename> /> I recommend the above method but you could... BitmapDrawable image = activity.getResources().getDrawable(R.drawable.<filename>); Button.setBackgroundDrawable(image); or Button.setBackgroundResource(R.drawable.image);
Shape-Drawable
These are colored shapes that can be used like images, there are four different shapes. Called a ColorDrawable in our book
See the book for how to make a Color-Drawable. Shape is now a documented resource so we will use that.
Shape-Drawable
Accessed through R.drawable.<filename> One XML file per shape, you can set the nodes
<shape /> you'll set the shape in here <padding /> set the padding like an html block <corners /> used to create rounded rectangle <gradient /> set a color gradient <size /> set the size <solid /> solid color instead of the gradient see android documentation for all the available options
Shape-Drawable
Example file:
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <solid android:color="#F00000FF"/>
<padding android:left="7dp" android:top="7dp" android:right="7dp" android:bottom="7dp" /> <corners android:radius="8dp" /> </shape>
Shape-Drawable
To implement
<TextView... android:background=@drawable/<filename> /> I recommend the above but just in case... GradientDrawable myRect = (GradientDrawable)activity.getResources().getDrawable(R. drawable.filename) textView.setBackground(myRect)
Arbitrary XML
Allows you to work with any old XML file, providing quick reference, localized resource, compiled and stored efficiently Stored in /res/xml as individual files Referenced via R.xml.<filename> no extension You need to use the XmlPullParser to parse the file.
Arbitrary XML
<root>
<subElement>
</subElement>
Get a parser
Arbitrary XML
StringBuffer sb = new StringBuffer(); xpp.next(); int eventType = xpp.getEventType(); while (eventType ! = XmlPullParser.END_DOCUMENT) { if(eventType == XmlPullParser. START_DOCUMENT) { sb. append(" ******Start document") ; }
Arbitrary XML
else if(eventType == XmlPullParser.START_TAG) { sb. append(" \nStart tag "+xpp. getName()) ; } else if(eventType == XmlPullParser.END_TAG) { sb. append(" \nEnd tag "+xpp. getName()) ; } else iff(eventType == XmlPullParser.TEXT) {
Arbitrary XML
sb. append(" \nText " +xpp.getText() ); } eventType = xpp. next() ; }//eof-while sb.append("\n******End document" );
the string buffer can now be sent to a TextView or wherever the data is needed
Raw Resources
Allows you to store raw uncompiled binary or text files. They are given an ID for R.java though. Accessed via R.raw.<filename> These is no node structure as these are individual files not XML You will need to use a java InputStream to process the file, look into java documentation for more info on InputStream
Assets
You can create your own directory structure under /assets to keep whatever files you like Not part of the /res directories Does not generate IDs for R.java You must specify the relative path to the file starting at /assets (do note include /assets) Use the AssetManager class to access them
Assets
Usage example
assume that we have /assets/test.txt AssetManager am = activity.getAssets() ; InputStream is = am.open(" test.txt") ; do something is.close() ;
/res/values/strings. xml or /colors.xml or /dimens.xml or /attrs. xml or /styles.xml /res/drawable/*. png or /*. jpg or /*. gif or /*. 9. png /res/anim/*. xml /res/layout/*. xml /res/raw/*.* /res/xml/*.xml /assets/*. */*. * Note the anim directory, we aren't really covering that at the moment, you can look up Animation Resources in the Android documentation
Content Providers
Create a wrapper around data (encapsulation) Allow us to expose, or access, an applications data Only needed for external access Usually based around an SQLite database Android has built in providers and you can write your own custom content provider
Content Providers
In your Android SDK directory find \platform-tools run \platform-tools\adb.exe shell to get shell access to the device you can see built in providers under /data/data Custom providers will also place their databases in here You can access the database with sqlite3 <db>
Content Providers
Content Providers combine elements of many other concepts out there like: web sites, web services, RESTful operations, and stored procedures. Like a website each content provider has is registered with a uri string (like a url) called an authority The authority is unique and will base of a set of URIs that will expose what the content provider offers
<provider android:name="MyProvider" android:authorities="com.my-company.MyProvider" /> android:name the provider class name android:authorities the uri used to access the content provider
Content Provider
content://com.my-company.MyProvider/
Many android internal services are not fully qualified, so may be accessed through shortened uri, such as content://contacts/ Through these URIs content providers expose data like a service The caller in this case is expected to know the columns and rows structure of the data and no special help with that is passed along
Content Providers
In order to provide proper access to these columns the provider should implement an interface or group of constants providing the column names We'll see some of this in our first example app. A MIME type will be included to indicate the type of data the URI is providing Retrieving this MIME type can help you decide how to handle the data
Content Providers
MIME type specifications have two parts, a type and sub type
http: //www.iana.org/assignments/media-types/
Content Providers
Android uses the vnd type and subtypes to indicate vendor specific non-standard types Android also has two MIME type forms
When creating MIME types type and subtype need to be unique for the data they represent You will almost always need the vnd prefix Namespace them based on your need
Content Providers
Let's look at an example of using a built in content provider First we have to add the access permission in the manifest
We import android.provider.ContactsContract, we can look at the documentation to see what this provides us
Content Providers
Using a cursor:
A cursor is an object that holds a collection of rows, accessed one at a time Make a query to get our cursor (c) c.moveToFirst the cursor starts before the first record so we need to move it up c.getString, c.getInt, etc. providing column names to retrieve the data You need to know the column name and type
Content Providers
c.moveToNext to move to the next record The cursor can be moved forward or back, and can provide a row count Projection an array of column names Learn about built in provider columns by reading the documentation There are many more cursor methods, see the documentation
Content Providers
Passed through the uri content://<authority>/notes/2 Explicit where in our query managedQuery(Uri uri, String[ ] projection, String selection, String[ ] selectionArgs, String sortOrder) Make selection and selectionArgs non null
Content Provider
ContentValues
key/value pair dictionary used to hold values for a single record These are like a column name/vaue setup We make this first for any record we want to add Used to insert the record We are not making a direct database insert Uri uri = contentResolver. insert(CONTENT_URI, values);
Content Resolver
Content Provider
Content Provider
You will also need to set up a database, and you should create a class or interface to provide constants for all the database metadata We'll look at all of these things in our example of a custom content provider. After we set up our custom content provider, we'll look at accessing it both from the local app and from a seperate app.
Intents
Can invoke other application from your app Can invoke internal and external components of your application Can raise events Intents can carry a payload (data) that can affect the action taken by your application
Intents
We have to register these actions so that our app knows what to do in the manifest
<activity android:name="BasicViewActivity" android:label="Basic View Tests"> <intent-filter> <action android:name="com.androidbook.intent.action.ShowBasicView"/> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity>
Intents
Intents
ACTION_WEB_SEARCH invoke a web search (based on payload) ACTION_DIAL open phone dialer with an entered number based on payload ACTION_CALL call a phone number based on payload (there seems to be some permission issues with this) ACTION_VIEW this will largely depend on the payload, In fact we can override this
Intents
Lets look at an example. Also looking at using a menu Finally a class challenge, make a contacts picker
Run the app again, and look we have some text If we look in main.xml we see the following
<TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" />
We see some settings for the text view being displayed @string/hello what does this do We are referencing the string value identified as hello Explore into the values folder instead of layout, open strings.xml From here we can see and change the hello string
Layout Managers
LinearLayout: Children are organized either horizontal or vertical TableLayout: Organize children in tabular form RelativeLayout: Organize children relative to one another or parent FrameLayout: Allows you to dynamically control layout AbsoluteLayout: depricated format
Layout Managers
This means that we can access layout managers by instanciating them as a ViewGroup
Linear Layout
This is the manager we are familiar with Children are added inside the linear layout in the order we want them to appear We can use weight and gravity to adjust the exact appearance a bit, as show in our example
Table Layout
Extends LinearLayout and creates a row/column structure To create a table layout in xml
Declare the TableLayout just like a LinearLayout Use <TableRow></TableRow> to define the row nodes Each view in the row node will create a column for the layout Number of columns determined by biggest row
Table Layout
android:stretchColumns list the columns to stretch android:shrinkColumns list columns to wrap content on in order to it better android:collapseColumns hides listed columns android:layoutSpan allows you to set a view to span multiple columns
Relative Layout
This layout manager allows you to arrange views relative to each other
Create the RelativeLayout like our other layouts In each child element assign the values of layout_below, layout_above, layout_toRightOf, layout_toLeftOf, layout_alignParentTop, layout_alignParentBottom, and/or layout_alignParentCenter These elements can be combined as necessary to create desired layout
Frame Layout
Very simple layout generally used to hold one view object that will be swapped in and out All child objects are attached to the upper left any new ones will just over write on top of previous ones, unless you hide some Often used with images, but could be used with other views Largest child element determines size
Menus
It automatically creates a basic menu and passes it to onCreateOptionsMenu(Menu) If that method returns true then a menu will be available We add items using
menu.add(<group>,<itemID>,<order>,<title>) menu.add(0,1,0,Item One) Every item but <title> is optional use MENU.none
Menus
onOptionsItemSelected(MenuItem item) Use a switch(item.getItemId()) to respond based on which item was clicked Return super.onOptionsItemSelected(item) as the default to release the menu display You can also implement menuItem.setOnMenuItemClickListener(myResponse); to use a callback function in place of the default You can also set an intent directly with setIntent()
Menus
Expanded menus you'll get a more menu item if you overflow the menu space Use menuitem.setIcon(drawable) to set a picture for the menu item You can also create submenus and context menus, you can find these in your book and we may cover them in coming classes Menus can be defined through XML
XML Menu
<menu>
</menu>
Place that file in /res/menu (R.menu.<name>) Load the menu by the resource id Respond to items based on their resource id
XML Menus