Saltar al contenido principal
Android Worshop

 Marc Mc Loughlin
   14/12/2010
Getting Started
• Android Developer Website
  http://developer.android.com/
   –   Dev Guide
   –   Reference
   –   Resources
   –   Video / Blog

• Setting up the SDK
  http://developer.android.com/sdk/installing.html
   – Install Eclipse IDE
   – Download SDK
   – Set system PATH to point to C:<path to sdk>tools
        • Allow shell wide access to SDK tools
             – Android
             – Emulator
             – adb, etc
   – Install the Android Development Tools (ADT) Plugin
   – Windows: Install USB driver to connect to external device
Development Tools
• Android Developer Tools (ADT) plugin
   – Lets you access development tools from Eclipse
   – Provides Android Project wizard, exports your
      project to APK
   – Allows you to create an Android Virtual Device
      (AVD)
   http://developer.android.com/guide/developing/
   eclipse-adt.html

• Android Virtual Device
   – Device configuration that lets you model
     device specifications
       • Hardware (memory)
       • Android OS version
       • Storage
   – Created using either the ADT or the android
     tool (SDK-directory/tools/)
   – Runs on the Emulator
Development Tools
• Emulator
   – Included in SDK (SDK-DIRECTORY/tools/)
   – Load AVD configuration to specify Android version,
     hardware for the emulator instance
   – Uses disk images on development machine to simulate
     flash images on device
   – Has networking capabilities but requires setup

• Android Debug Bridge (adb)
   – Allows access to the emulator instance or Android Device
       • Allows Eclipse access to device data
             – Installing applications
             – Debugging
       • Allows developers to execute commands (adb devices)
             – Installing applications (adb -s emulator_name install
               helloWorld.apk)
             – Copying files to and from device (adb pull / adb push)
             – Provides shell to run commands on device (adb -s
               emulator_name shell)
Android Architecture
•   Applications
      • Core applications shipped with
          device (email client, calendar,
          maps, browser, etc)
      • All user installed applications
•   Application Framework
      • Set of services and systems that
          your application can use
      • Activity Manager, Content
          providers, Resource Manager
•   Core Libraries
      • Subset of J2SE
•   Android Runtime
      • Dalvik virtual machine optimized
          for mobile devices
      • Runs class files (dex files)
•   Libraries
      • C/C++ libraries but called
          through java interfaces
•   Linux kernel
      • Underlying operating system
Android Application Components
•   Activities                                 •   Broadcast Receivers
     — Activity: A window to                        – Listens for events
       draw user interface                          – Receives broadcast
       components on                                  announcements (Intents)
     — Numerous activities =                          and reacts to them
       Task = Android App                             (timezone changes, etc)
     — Each window is a subclass
       of the activity class




• Services                                     • Content providers
    — Background                                  — Persist data
       processes                                  — SQLite database
    — Carries out any long         ― Intents      — Shared preferences
       process
Intents

•Activities, Services and Broadcast
Receivers talk to each other via
Intents

•Intents = messages among the
application components
     •Can be within your application:
     calling an activity or service in
     your application
     •Or System wide: accessing the
     address book activity
     •Accessing functionality of other
     applications (e.g. zxing)

•An intent contains
     •Action (what has to be done)
     •Data (Info)
Manifest file




• Each application runs on an individual Dalvik virtual machine inside a linux
  process

• To access other applications and specific parts of the API it must have
  permission
    – An applications permissions are set in it’s manifest file
    – Manifest file: Tells the android operating system about the application
        • Permissions
        • Its components (Activities, Services, Content Providers, etc)
        • Has to be updated when you add specific elements to your application (activities, sdcard
          access, location manager access, etc.)
Building your User Interface (UI)
Activities
Android - Activities
• Activity class
   – Each UI Window extends the
     activity class (android.app.Activity)
       • activity is a frame or window to hold
         the GUI

   – Each activity loads a view

   – Handles user inputs
       • You put your code to handle user
         interaction in the activity

   – Activity has three states
       • Active or Running: Activity is the
         focus of users actions
       • Paused: Activity has lost focus but
         still visible
       • Stopped: Activity is completely
         hidden from user
/src

Android Project   /gen
                         This is where all the java sources files are put. Similar to /src
                         folder in normal Java projects. Source files should be organised
                         into packages

                         Another source folder but contains only a single but very
                         important java source file called R.java. That is automatically
                         created in eclipse via the ADT
                         R.java keeps track of all the resources in your project so you can
                         reference them in your code
                  /android
                         Contains the android libraries that are need for the project
                         similar to “/lib” folder in normal java projects
                  /res
                         Contains external resources (interface layouts, application data,
                         images etc.) that are used by the android application
                         /res/drawable-ldpi
                         /res/drawable-mdpi
                         /res/drawable-hdpi
                                 Contains all images needed for the application
                         /res/layout
                                 Contains all the UI layouts for the application
                         /res/values
                                 Contains xml files that hold key – value pairs that can be
                                 references in the application
                                          Color codes
                                          Strings
                                          dimensions
                  /assets
                         You can any external resources here
                         Resources are in raw format and can only be read
                         programmatically
                  AndroidManifest.xml
                         Contains all the information about the application, every
                         application must have one
                         Info about activities, services, permissions
Activities
• Activity Manager
   – Manages the lifecycle of
     activities
   – As it moves between states
     specific methods are called
       • Hooks you can override to do
         work when the state changes
   – Manages back stack for user
     navigation
Android Activities
                       Lifecycle Methods
• All activities should implement the onCreate(Bundle) method
    – Called every time an activity is launched
    – This is where activity is initialised
        • Loading views
        • Initiating fields

• Nearly all activities will implement:
    – onResume()
        • Creating database connections
        • Getting intent information
    – onPause() method
        • This is where persist (save) any data
    – onDestroy()
        • This is where clean up is generally carried out
        • Killing any other threads attached to the application, etc.
Creating your view
                                        LinearLayout linearLayout = new LinearLayout(this);
• User Interfaces can be                parentView.addView(linearLayout, relativeParams);

  created in two ways:                  TextView tv1 = new TextView(this);
   1. Create layouts at                 tv1.setId(1);
                                        TextView tv2 = new TextView(this);
      programmatically at runtime       tv2.setId(2);
   2. Declare UI elements in xml
      and loaded as a resource          layout.addView(tv1);
                                        layout.addView(tv2, lp);
      (Preferred) at runtime
      • Create UI in xml and then
        reference them in your code     <RelativeLayout...>
      • At runtime android parses the    <TextView>
        xml resource files and             android:id="@+id/label1" />
        instantiates them               </TextView>
                                         <TextView ...
                                           android:id="@+id/label2"
• Allows you to separate the               android:layout_below: "@id/label1" />
  presentation from code                </RelativeLayout>
Creating the view layout in xml
•   Similar to creating webpages in html
     – Tree of xml elements
                                                  <?xml version="1.0" encoding="utf-8"?>
     – Each element of the tree is a view         <LinearLayout
         class(TextView, ImageView, etc.)         xmlns:android="http://schemas.android.com/apk/res/and
                                                  roid"
                                                    android:orientation="vertical"
•   Must contain one root element (View or          android:layout_width="fill_parent"
    ViewGroup) where additional views are           android:layout_height="fill_parent"
    added as children                               >
     – View: A widget that appears on screen      <TextView
        (buttons, text boxes, labels, etc.)         android:id="@+id/textview"
                                                    android:layout_width="fill_parent"
     – ViewGroup: Provides layout structure for     android:layout_height="wrap_content"
        your views                                  android:text="@string/hello"
          • LinearLayout                            />
                                                  </LinearLayout>
          • AbsoluteLayout
          • TableLayout
          • RelativeLayout
          • FrameLayout
          • Scrollview
Creating the view layout in xml
•   Once a root element is defined you build
    your view by adding more view elements to
    it

•   Each View or ViewGroup has it’s own xml
    attributes
     – Some are common to all
            • “id” attribute: Gives the View a
               unique ID to idenfiy it. Used to
               add new resources to R.java
            • Layout Parameters:
               “layout_height” / “layout_width”
     – Some View have their own specific
          attributes
            • TextView: textsize
External Resources
                                                                   Table 1: Resource Directories
                                                       Directory                  Resource Type
•   Stored in “/res” directory in the project
                                                                                  XML files that define tween
                                                       anim/
                                                                                  animations.
•   Types of resources                                                            XML files that define a state list of
     –   Color information                             color/
                                                                                  colors.
     –   Layout (UI) information
     –   Strings (Application text)                                                Bitmap files (.png, .9.png, .jpg,
     –   Etc..                                         drawable/                   .gif) or XML files that are
                                                                                   compiled into drawable resources
•   R.java file managed by ADT creates new                                         XML files that define a user
    resource ID when resource added to                 layout/
                                                                                   interface layout.
    application
     –   This resource ID can be reference in source                               XML files that define application
         code                                          menu/                       menus, such as an Options Menu,
                                                                                   Context Menu, or Sub Menu.
•   When packaged each Android application
    has a resource table where it keeps all the
    resource information                                                           Arbitrary files to save in their raw
                                                       raw/
                                                                                   form.
•   In an Android project the sub directories of
    the /res directory must follow specific
    patterns (see Table 1)                                                         XML files that contain simple
                                                       values/                     values, such as strings, integers,
                                                                                   and colors.

                                                                                   Arbitrary XML files that can be
                                                       xml/
                                                                                   read at runtime
Loading your view into an activity
                                                             Referencing View elements in
   Loading View                                              source
   •    UI layout resource loaded in onCreate()              To apply logic in your source code for views
        using setContentView() method                        created in an xml layout you must reference them
        inherited from the activity class                    in your source
          –   You pass the reference to the UI layout you    1.    Create a variable of your view type in your
              create to the setContentView (int                    source code
              layoutResID)                                   2.    Then assign it to a view in your layout file
          –   R.layout.main                                        using findViewByID(int id) method
                                                                   inherited from the activity class
                                                                    –   You pass in the id of the view you want to
   •    Your activity provides the window and                           reference
        you fill the window using                                   –   The findViewByID(int id) returns a object of
        setContentView (int layoutResID)                                type View so you must cast the view to the
          –   If you do not call this method no UI will be              specific instance you created
              displayed

@Override                                                    @Override
protected void onCreate(Bundle savedInstanceState) {         protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);                   super.onCreate(savedInstanceState);
       this.setContentView(R.layout.main);                   this.setContentView(R.layout.main);
}
                                                             TextView textView1 =
                                                             (TextView)this.findViewById(R.id.button1);
                                                             }
Android application package file:
Manifest File                            .apk file
• A xml file saved as                    • Just a zip file similar to
  AndroidManifest.xml
• Every application must have one,         other java archive files jar,
  it specifies:                            war, etc.
    – All components of an application
    – What activity is displayed on      • It contains:
      application launch
                                            – all the application code in
    – The android API the application
      requires                                .dex files (class files)
    – The permissions the application       – Resources
      has (sdcard read/write,
      networking, etc.)                     – Resource table
• Each activity added to the                – Assets and manifest
  application must be declared in
  the manifest file
User Interaction
UI events
• Events are fired every time a user interacts with a View
• Capture these events to react to these interactions
• How?
    – The View class provides interfaces (or event listeners) with callback methods
        • These methods are call by Android when an action occurs on a view to which a listener is
          registered to
    – The following are some of the listener interfaces that can be implemented
        •   OnClickListener
        •   OnFocusChangeListener
        •   OnKeyListener
        •   OnLongClickListener
        •   OnTouchListener

• Procedure
    – Create your listener interface
        • Numerous ways to do this, the best way is to let your activity implement the listener
          interface
    – Set the view’s onClickListener to your listener
        Button button1 = (Button)this.findViewById(R.id.button1);
        button1.setOnClickListener(this);
Implementing OnClickListener
OnClickListener implemented in                                   Anonymous Implementation of
your activity (best way)                                         OnClickListener
public class StartActivity extends Activity implements           public class StartActivity extends Activity{
OnClickListener{
                                                                       @Override
     @Override                                                         protected void onCreate(Bundle savedInstanceState) {
     protected void onCreate(Bundle savedInstanceState) {              super.onCreate(savedInstanceState);
     super.onCreate(savedInstanceState);                               this.setContentView(R.layout.startactivitylayout);
     this.setContentView(R.layout.startactivitylayout);
                                                                       TextView textView1 =
     TextView textView1 =                                              (TextView)this.findViewById(R.id.textview);
     (TextView)this.findViewById(R.id.textview);
                                                                       Button button1 = (Button)this.findViewById(R.id.button1);
     Button button1 = (Button)this.findViewById(R.id.button1);
     button1.setOnClickListener(this);                                 button1.setOnClickListener(new OnClickListener(){
     }
                                                                               @Override
     @Override                                                                 public void onClick(View v) {
     public void onClick(View v) {                                             // Code to deal with user interaction
     // Code to deal with user interaction
                                                                                   }
                                                                             });
     }
                                                                       }
                                                                 }
}
Moving between Activities
• An Intent is a message that holds data
  about action that has to be carried out

• Intents can be used to activate appplication
                                                                  Intents
  components: activities, services and
  broadcast receivers
    – They are delivered by passing them through
      specific methods
        • activities: startActivity(), startActivityForResult()
        • services: startService(), bindService()
        • Broadcast receivers: sendBroadcast(),
          sendOrderedBroadcast()


• Can access components of native and
  installed applications as well!

• An intent can hold the following pieces of
  information
    – Action: what action has to be performed
    – Data: data that can operated on
    – Category: provides more data about the action
    – Type: type of intent data
    – Component: Specifics the specific name of
      component calls to use
    – Extras: Any additional information to be sent
Explicit Intents
• Have a specified component that provides the
  exact class to be run
• Usually do not include any more information
  except data you want to pass to the component
  Intent intent = new Intent();
  intent.setClassName("ie.marc", "ie.marc.SecondActivity");
  this.startActivity(intent);

  Intent intent = new Intent(this, SecondActivity.class);
  this.startActivity(intent);

  Intent intent = new Intent("com.google.zxing.client.android.SCAN");
  intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
  startActivityForResult(intent, 0)
Implicit Intents
•   Intents don’t explicitly name a target component

•   Android tests the data in the Intent Object against intent filters associated with potential targets

•   Intent Resolution: maps intent to Activity, BroadcastReceiver or service

•   To ascertain what component best serves the intent following information is analysed
     –   Action
     –   Category
     –   Data
•   This data is matched to intent filters set in other applications

    Intent intent = new Intent();                              <intent-filter>
    intent.setAction("android.intent.action.VIEW");              <action android:name="android.intent.action.VIEW" />
                                                                 <category
    intent.setData(Uri.parse("http://www.lit.ie"));
                                                               android:name="android.intent.category.DEFAULT" />
    this.startActivity(intent);                                  <scheme android:name="http" />
                                                                 <scheme android:name="https" />
                                                                 <scheme android:name="file" />
                                                               </intent-filter>
Launching Activities
• Launching an activity with no data
  returned
    – Use startActivity(Intent)
         Intent intent = new Intent(this,
         SecondActivity.class);
         this.startActivity(intent);

• Launching an activity where data
  needs to be returned
    – Use startActivityForResult(intent,
      resultcode)

    – The launched activity returns the data
      by creating an intent and passing it to
      setResult(int resultCode, intent)

    – The calling activity must Override
      onActivityResult(int requestCode, int
      resultCode, Intent data)
         • This is called by the activity manager
         • It passes in the data in an intent and
           result code from the returning activity
Launching an activity where data
                 needs to be returned example
     Activity 1 – Calling activity                                          Activity 2 – Launched activity
@Override
public void onClick(View arg0) {
       Intent intent = new Intent(this, SecondActivity.class);
       this.startActivityForResult(intent, REQUESTCODE);

}
                                                                            Intent data = new Intent();
@Override
                                                                            data.putExtra(SecondActivity.RETURNEDNAME,
protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
                                                                            textInput.getText().toString());
        switch(requestCode){                                                this.setResult(Activity.RESULT_OK, data);
        case REQUESTCODE:                                                   this.finish();
               if (resultCode == RESULT_OK){
                  textView1.setText(data.getStringExtra("returnedText"));
               }else{
                  textView1.setText(data.getStringExtra("A problem
                  occured when getting the returned information"));
               }
               break;
               default:
               break;
               }
}
Getting Started
• Refresh your knowledge of Java (Do some tutorials)
• - Java tutorial on classes, inheritance & interfaces
   http://download.oracle.com/javase/tutorial/java/concepts/index.html
   - Tutorial on interfaces,
   http://download.oracle.com/javase/tutorial/java/IandI/index.html

• Learn how to use the Debugger!
    – http://eclipsetutorial.sourceforge.net/debugger.html

• Look at the tutorials on the Android Developer site
    – http://developer.android.com/resources/tutorials/hello-world.html
    – http://developer.android.com/resources/tutorials/views/index.html
    – http://developer.android.com/resources/tutorials/notepad/index.htm
      l