Lecture Presentation

Lecture Presentation

Goals

  • Understand the basic building blocks of an Android application
  • Create a simple user interface with text and buttons
  • Access and change the text of objects in the user interface
  • Start other applications (Activities) from your application
  • Classes and methods introduced in this chapter
    • Activity, onCreate, TextView, Button, onClick, Intent, startActivity, Toast

What is Android?

  • Open source
  • Linux kernel
  • Optimized for mobile devices
  • Uses Java for building applications (1.5)
  • Can also run native code in C/C++
  • Has its own runtime (not standard Java runtime) - Dalvik
  • History
    • Google buys Android in 2005, unveiled in the fall of 2007
    • Android versions are named after sweets/pastries in alphabetical order

Android version history

  • 1.0 2008 (September)
  • 1.5 Cupcake 2009 (April)
  • 1.6 Donut 2009 (September)
  • 2.1 Eclair 2009 (October)
    • Live wallpapers. Account Manager.
  • 2.2 Froyo 2010 (May)
    • Store apps on SD card. Cloud to device messaging.
  • 2.3 Gingerbread 2010 (December)
    • Multiple cameras. Gyroscope and more sensors.
  • 3.0, 3.1, 3.2 Honeycomb 2011 (February)
    • Fragments. Action bar. New animation framework. For tablets only.
  • 4.0 Ice Cream Sandwich 2011 (October)
    • GridLayout. Resizable widgets. WiFi Direct.
  • 4.1, 4.2 Jelly Bean 2012 (June, November)
    • Multi-user support. Lock screen widgets. Second display support.

Create a new project

  • Choose "File, New, Android Application"
  • Application name
    • The title shown to users when installing, below icon etc. Example: My Test Application
  • Project Name
    • The name of the project folder in Eclipse workspace. Example: MyTest
  • Package Name
    • Unique (reverse) domain name that identifies the application to the platform. Does not have to be a registered domain or site. Example: se.mobileapplab.mytest

Create a new project (2)

  • Minimum Required SDK
    • The oldest Android version where the application will install.
  • Target SDK
    • The newest Android version that the developer is aware of and might have optimized for.
  • Compile With
    • Should always be the latest installed Android version to get the most recent tools, compilers etc when building the application.
  • Theme
    • Default styles that will be applied to different components in the user interface. Not guaranteed on versions older than "Target SDK", since chosen theme might not be available there.
  • Use defaults for all other options and dialogs

Deciding on an Android version

  • One single application
    • Can run on many different Android versions
    • Can check and adjust itself to take advantage of newer features on newer versions
  • Multiple versions of the application
    • Build separate applications with different "Minimum Required" versions
    • Some/much shared code
    • Two versions should cover most of the needs for version separation
  • If there is a specific feature your application requires in order to function
  • If there are features that will enhance your application, but isn't essential
  • Statistics of running versions

Files and folders in project

  • src
    • Java source files. This is where you will add your code. Organized in subfolders according to the different parts of the package name (reverse domain name).
  • assets
    • Optional raw data files that the application might need. Not handled by the platform in any way.
  • libs
    • Extra libraries with code that the application mgith need.
  • res
    • Important resource files in both xml and binary (images) format. These files are handled and selected by the platform according to different properties (qualifiers) of the device.
  • AndroidManifest.xml
    • Main configuration of the application. Specifies all activities of the application, some names, the icon, permissions and more.

Important objects in an application

  • Activity
    • The basic object of all Android applications. Without an Activity, nothing will be displayed on the screen. An application must contain at least one Activity, but can contain more.
  • View
    • The basic visual object when building the user interface. All specific visual components are derived from the View. Can be buttons, input fields, formatted text, images etc.
  • ViewGroup
    • A special View that contains other Views layed out on screen according to some rule/specification. Usually a ViewGroup-derived layout class is the root of your user interface.
  • Intent
    • Describes an action that should be performed, most often in the form of starting an Activity.

Not so important objects

  • Application
    • The root object of your application. Must always exist, and there will only be one. You can derive your own class from the Application class if you want to handle something application specific, but we will not need to do that in this course.
  • Window
    • The Window object handles a top level View for an application. The Window contains a View, but can also handle a title and some more visuals. You rarely or never need to access the Window of your application.
  • Context
    • Generalization of the resources and other objects that relates to the application. You will use it as an argment in many calls, but you don't need to know anything more about it and you can always use the Activity (this) for the course's examples.

Resource files

  • Configuration/definition files below the "res" folder of your project
    • Mostly binary files (like jpg) or xml files
    • Each subfolder below "res" has a special meaning to the platform
    • We'll talk more about resource files in the next chapter
  • User interface specification
    • Stored as xml files below the "layout" subfolder
    • We'll edit this file in our first project
  • Text translations
    • Stored as xml files below the "string" subfolder
    • We'll get back to these in the next chapter

Your first Activity

  • Visual appearence - layout
    • Defined in res/layout/main.xml
    • Specifies elements to show in the user interface
  • Java Class where your code/logic resides
    • Stored in src/se.mobileapplab.demo/MainActivity.java
    • Contains code that will be called by the platform when events happen
  • Separation of layout/code is quite similar to how ASP.NET separates between an aspx-file and a code-behind file

Layouts in an Activity

  • RelativeLayout
    • This is the default type of layout for new projects
    • Every visual element is placed in relation to some other/previous element
    • We'll always change this to LinearLayout for the examples in this course
  • LinearLayout
    • A little less powerful and less efficient than the RelativeLayout
    • But I think it is easier to use and understand
    • All visual elements are either layed out horisontally or vertically
    • Nested LinearLayouts can be used for more complex layouts

LinearLayout basics

  • Until next chapter, we'll use it like this
  • Vertical orientation for elements below each other
    <LinearLayout android:orientation="vertical"
    
  • All child elements are full width and height according to contents
    <TextView
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
    

Views in a layout

  • TextView
    • Simple text content
    • android:text is the content
  • Button
    • Button that can be pressed
    • android:onClick is name of Activity method to call when pressed
    • Method can have any valid Java name, but must be void and take View argument
      public void onButton(View source)
      

Methods in an Activity class

  • Some methods have predefined names which makes them into event handlers
  • Event handlers are called by the Android platform during the life cycle of an Activity
  • onCreate
    • Event when the application is created for the first time. Initialize all variables here. Read any stored data from persistant storage. The onCreate of your first (single?) Activity can be thought of as the main method of your whole application.

Access to a visual element from your Java code

  • You often need to change visual elements from Java
  • Give the visual element an id in the xml layout file
    <TextView android:id="@+id/title">
    
  • Declare an object in your class with same name as visual element
    TextView _someAppTitle;
    
  • Set object to refer to the visual element in onCreate using findViewById

Use a reference to a visual element

  • Change the text of a TextView
    _someAppTitle.setText("Now my title is different");
    
  • Most attributes in the xml have corresponding set-methods for changing them from Java
    • However, some are a bit more difficult to set/change (like android:layout_width)

Start other application

  • Android has something similar to file extension associations
    • Applications can register to handle different types of "actions". Such a specification is called an "Intent" on Android. By using Intents, you don't need to know about which other applications are installed on the device but still take advantage of their features from your application.
  • Create an Intent object with an Action (and optional specification)
    Intent dosomething = new Intent(Intent.ACTION_DIAL);
    
  • Launch other application with startActivity
    startActivity(dosomething);
    

Phone-related intents

  • Start the dialer with a prepared phone number
    Intent dial = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:0123456789"));
    startActivity(dial);
    
  • Start the messaging app to a prepared phone number with a text
    Intent sms = new Intent(Intent.ACTION_SENDTO, Uri.parse("sms:0123456789"));
    sms.putExtra("sms_body", "Hi there. How are you?");
    startActivity(sms);
    
  • Call a phone number immediately. Requires the CALL_PHONE permission!
    Intent call = new Intent(Intent.ACTION_CALL, Uri.parse("tel:0123456789"));
    startActivity(call);
    

Web-related intents

  • Start the web browser and go to web site
    Intent browse = new Intent(Intent.ACTION_VIEW, Uri.parse("http://m.hj.se"));
    startActivity(browse);
    
  • Use the web browser to search for something
    Intent search = new Intent(Intent.ACTION_WEB_SEARCH);
    search.putExtra(SearchManager.Query, "android settings intent example");
    startActivity(search);
    
  • Share a text to any registered application (like Facebook)
    Intent share = new Intent(Intent.ACTION_SEND);
    share.putExtra(Intent.EXTRA_SUBJECT, "Good morning!");
    share.putExtra(Intent.EXTRA_TEXT, "Time to get up. This will be a good day.");
    startActivity(share);
    

Android Manifest

  • The configuration xml file for the whole application
  • Contents
    • Activities in the application
    • The permissions the application requires to run
    • System events that the application can handle (Intents and Broadcast receivers)
  • This is where the display name of the application can be changed
  • Editable in Eclipse via helper forms, or in its raw xml form (last tab in Eclipse)

Android Permission system

  • Applications define permissions that they require in the manifest
    • Never require more permissions that you actually need
  • User will see these permissions before confirming to install application
    • Permissions are an all-or-nothing option. If the user isn't confident with the requested permission(s), the user can only select NOT to install the application at all.
  • Defined in root element of AndroidManifest.xml
    <uses-permission android:name="android.permission.CALL_PHONE" />
    
  • http://developer.android.com/reference/android/Manifest.permission.html

Toast

  • Nothing you eat or drink
    • Android's name for a short text message that appears on top of the user interface and is automatically removed after a few seconds
  • Good feature for notification messages
    • Can also be used for simpler debugging purposes, like checking a value or ensuring a code statement is reached (without using the full debugging capabilities of Eclipse)
  • Show a toast message
    Toast.makeText(this, "Hello, world!", Toast.LENGTH_LONG).show();
    

More information

  • Book references
    • Android Programming Unleashed, Chapter 1 Introduction to Android, Creating the First Android Project
    • Android Programming Unleashed, Chapter 2 Basic Widgets, Overview of the Android Project Files
    • Android Programming Unleashed, Chapter 2 Basic Widgets, Creating and Starting an Activity