Architecting Android Apps

download Architecting Android Apps

of 50

Transcript of Architecting Android Apps

  • 8/18/2019 Architecting Android Apps

    1/50

    Architecting Android AppsMarko Gargenta @Marakana

    chitecting Android Apps Overview

    http://localhost/Users/marko/github/android/courseware/Talks/Architecting_Android_Apps_Talk.html#slide-2

  • 8/18/2019 Architecting Android Apps

    2/50

     About Marko Gargenta

    Marko Gargenta

    Entrepreneur, Author, SpeakerDeveloper of Android Bootcamp for Marakana.

    Instructor for 1,000s of developers on Android at Qualcomm, Cisco, Motorola, Intel, DoD and

    other great orgs.

    Author of Learning Android published by O’Reilly.

    Speaker at OSCON (4x), ACM, IEEE(2x), SDC(2x), AnDevCon(2x), DroidCon.

    Co-Founder of SFAndroid.org

    Co-Chair of Android Open conference: Android Open

    http://androidopen.com/http://amzn.to/learningandroidhttp://marakana.com/training/android/android_bootcamp.html

  • 8/18/2019 Architecting Android Apps

    3/50

     Architecting Android Apps Overview 

  • 8/18/2019 Architecting Android Apps

    4/50

    Architecting Android Apps Overview 

    he goal of this module is to introduce you to main components used to create

    Android apps. By the end of this module, you should have a good idea what

    Android app building blocks are, and their key properties.even iterations of an app:

    Part 1 - Activities and Android UI

    Part 2 - Intents, Action Bar, and More

    Part 3 - Services

    Part 4 - Content Providers

    Part 5 - Lists and Adapters

    Part 6 - Broadcast Receivers

    Part 7 - App Widgets

  • 8/18/2019 Architecting Android Apps

    5/50

    Yamba

    Yamba

    bjectives of Yamba

    he objective of this module is to explain how to go about designing a typical

    Android app. You will have a chance to see an example app, Yamba, using most

    he standard Android building blocks. By the end of this talk, you should have

    igh-level understanding about designing an Android app.

  • 8/18/2019 Architecting Android Apps

    6/50

    Yamba Approach

    Yamba OverviewYamba: Yet Another Micro-Blogging App

    Comprehensive Android example application.Works with services that support Twitter API.

    Project PhilosophySmall increments - build it organically

    App must always run - whole and complete

    Refactor when needed - do simplest thing first

  • 8/18/2019 Architecting Android Apps

    7/50

    Part 1 - Activities and Android UI

    Yamba Part 1

  • 8/18/2019 Architecting Android Apps

    8/50

    Activity Overview 

    Example of Activities

    An activity is roughly a screen.

    A typical application may have many activities.

    Activities are typically expensive and so are managed by the system.

  • 8/18/2019 Architecting Android Apps

    9/50

    Activity Lifecycle

     Activity Lifecycle

    Activities are highly managed by the system’s ActivityManager.

    ActivityManager drives the activity through its states.

    You as an app developer get to say what happens on transitions.

  • 8/18/2019 Architecting Android Apps

    10/50

    Activity Callbacks

    ifecycle

    onCreate()onCreate()

    Used to setup your activity. You will almost always have to have it. Good place tnflate the UI and setup listeners.

    onResume()onResume() and onPause()onPause()Use them to turn on and off things that you’d like to have running only while th

    ctivity is visible. This is important for things that consume a lot of battery, such

    s GPS and sensors.

    onStart()onStart() and onStop()onStop()Use to setup code that starts/stops the activity. Unlike onResume()onResume() andonPause()nPause(), it includes Paused state as well.

    onRestart()onRestart()alled when the activity is restarted. It is followed by onStart()onStart() andonResume()nResume().

    onDestroy()onDestroy()A good place to do any cleanup before the activity is cleaned up from memory.his is the counter-part to onCreate()onCreate().

    ther

    onCreateOptionsMenu()onCreateOptionsMenu() and

    onOptionsItemSelected()onOptionsItemSelected()Use them to setup your menu. onOptionsItemSelected()onOptionsItemSelected() loads the menu,ypically from an XML resource. onOptionsItemSelected()onOptionsItemSelected() is called whenen option menu item is clicked on.

    Various listeners and event handlers, such as onClick()onClick()Used to handle the UI events.

  • 8/18/2019 Architecting Android Apps

    11/50

    Registering Activity 

    Main Activity 

    egister the activity in the Android Manifest file:

     Android Manifest file

    he intent filter specifies that this activity is to be the main entry point into the

    pplication as well as that it should be shown in the app launcher on home scre

    ny other activity  Android Manifest file

    ...

     

     

     

     

    ...

    ...

    ...

  • 8/18/2019 Architecting Android Apps

    12/50

    Building Android UI

    here are two approaches to building Android UI:

    eclaratively 

    Declare UI in XML

    Eclipse provides nice drag-n-drop tools

    Inflate the XML views in Java

    rogrammatically 

    Instantiate all widgets programmatically

    Set properties for each

    he best is to use both:

    1. Star with declaring the look and feel using XML

    2. Inflate XML into Java

    3. Finish by programming the actions using Java

  • 8/18/2019 Architecting Android Apps

    13/50

    Layouts and Views

    Layouts and Views

  • 8/18/2019 Architecting Android Apps

    14/50

    Part 2 - Intents, Action Bar, and More

    Yamba Part 2

  • 8/18/2019 Architecting Android Apps

    15/50

    Intent Overview 

    Example of Intents

    Intents are like events or messages.

    You can use them so start activities, start/stop services, or send broadcasts.

    Intents can be implicit or explicit.

  • 8/18/2019 Architecting Android Apps

    16/50

    Using Intents

    startActivity()startActivity()tarts an activity specified by the intent. If activity does not exist already, it call

    onCreate()nCreate() to create it. Otherwise, it calls onStart()onStart() and onResum()onResum().

    startService()startService()tarts a service. Even if the service is not created yet, it called onCreate()onCreate() onhe service first.

    stopService()stopService()tops a service that is already running. If service is not running, it does nothing

    bindService()bindService()inds to a service. Requires that the service returns a binder via onBind()onBind()

    method.

    sendBroadcast()sendBroadcast()ends a broadcast. If there’s a broadcast receiver registered to filter for the sam

    ction as this intent is specifying, that receiver’s onReceive()onReceive() method will bealled.

  • 8/18/2019 Architecting Android Apps

    17/50

    Explicit and Implicit Intents

    xplicit Intent ActivityDemo.java

    thishis is the context from which this intent is being sent, in our case an Activity.

    mplicit Intent ActivityDemo.java

    equires that there’s an intent filter filtering for this particular intent, for examp

     AndroidManifest.xml

    ...

    startActivity(new  Intent(this, AnotherActivity.class));

    ...

    startService(new  Intent(this, ServiceDemo.class));

    ...

    ...

    startService(new  Intent("marakana.intent.action.IntentServiceDemo"));

    ...

    sendBroadcast(new  Intent("marakana.intent.action.ReceiverDemo"));

    ...

    ...

     

     

     

    ...

     

     

     

    ...

  • 8/18/2019 Architecting Android Apps

    18/50

    Intent Filter

    ntent filter is a way for us to assign certain action to an activity, service, receive

    r similar.

    Action is one of system defined actions, or something you come up with.

    ntent filter typically goes into Android Manifest file, within ,

    service>, or  elements.

     Android Manifest file

      ...

     

     

     

      ...

  • 8/18/2019 Architecting Android Apps

    19/50

    Action Bar

    he action bar , introduced in Honeycomb (API 11) is a title bar that includes:

    The application icon

    The activity title

    A set of user-selectable actions (optional)

    A set of user-selectable navigation modes (optional)

  • 8/18/2019 Architecting Android Apps

    20/50

    Enabling the Action Bar

    Android automatically displays an action bar on an API 11+ system if the  element of your applications manifest:

    Sets minSdkVersionminSdkVersion to 11 or later, or 

    Sets targetSdkVersiontargetSdkVersion to 11 or later

    ither or these settings enable the "holographic look and feel" introduced in

    Honeycomb, which includes action bar support.

    If neither minSdkVersionminSdkVersion nor targetSdkVersiontargetSdkVersion are set to 11+, then an API 11+ systemrenders the app in a legacy theme, without action bar support.

    With the action bar enabled, legacy option menu items appear automatically in

    he action bar’s overflow menu. You reveal the overflow menu with:

    The hardware Menu button (if present), or 

    An additional button in the action bar (for devices without a hardware Menu button)

  • 8/18/2019 Architecting Android Apps

    21/50

    Adding Action Items

    o display an option menu item as an action item, in the menu resource file add

    android:showAsAction="ifRoom"ndroid:showAsAction="ifRoom" to the  element.

    The device will display the item if there is room available in the action bar, otherwise the item

    appears in the overflow menu.

    Devices running API 10 or earlier ignore the showAsActionshowAsAction attribute.

    f your menu item supplies both a title and an icon, the action item shows only

    con by default.

    To display the text title, add withText withText to the android:showAsActionandroid:showAsAction attribute. Forexample:

    The withText withText value is a hint to the action bar. The action bar will show the title if possible, bu

    might not if an icon is available and the action bar is constrained for space.

     

  • 8/18/2019 Architecting Android Apps

    22/50

    Part 3 - Services

    Yamba Part 3 

  • 8/18/2019 Architecting Android Apps

    23/50

    Service Overview 

    Example of a Service

    Services are code that runs in the background.

    They can be started and stopped. Services doesn’t have UI.

    Keep in mind that service runs on the main application thread, the UI thread.

  • 8/18/2019 Architecting Android Apps

    24/50

    Service Lifecycle

    Service Lifecycle

    Service starts and "runs" until it gets a request to stop.

    Service will run on the main UI thread.

    To offload work from main thread, use intent service.

    Intent service uses worker thread, stops when done with work.

    Services can be bound or unbound.

  • 8/18/2019 Architecting Android Apps

    25/50

    Service Callbacks

    onBind()onBind()equired, but for unbound services, we just return nullnull.

    onCreate()onCreate()alled when service is first created.

    onStartCommand()onStartCommand()alled is called every time service is started.

    onDestroy()onDestroy()alled when service is stopped. It is subsequently destroyed.

  • 8/18/2019 Architecting Android Apps

    26/50

    IntentService Callbacks

    Constructort needs to pass the name of this service to its supersuper.

    onCreate()onCreate()alled when service is first created.

    onHandleIntent()onHandleIntent()his is where the work of the service runs.

    onDestroy()onDestroy()alled when service is stopped. It is subsequently destroyed.

  • 8/18/2019 Architecting Android Apps

    27/50

    Registering ServiceRegistering a service that will be called explicitly by its class name

    Registering a service that will be called via action

    ...

    ...

    ...

     

     

     

    ...

  • 8/18/2019 Architecting Android Apps

    28/50

    Part 4 - Content Providers

    Yamba Part 4 

  • 8/18/2019 Architecting Android Apps

    29/50

    Content Provider Overview 

    Example of Content Provider 

    Content Providers share content with applications across application boundaries.

    Examples of built-in Content Providers are:

    Contacts

    MediaStore

    Settings and more.

  • 8/18/2019 Architecting Android Apps

    30/50

    Typical Usage of Content Providers

    Typical Usage of Content Providers

  • 8/18/2019 Architecting Android Apps

    31/50

    Content Provider Lifecycle

    Content Provider Lifecycle

    Content provider is initiated first time it is used via a call to onCreate()onCreate().

    There is no callback for cleaning up after the provider.

    When modifying the data (insert/update/delete), open/close database atomically.

    When reading the data, leave database open or else the data will get garbage collected.

  • 8/18/2019 Architecting Android Apps

    32/50

    Content Provider Callbacks

    onCreate()onCreate()Used to initialize this content provider. This method runs on UI thread, so shou

    e quick. Good place to instantiate database helper, if using database.

    getType()getType()eturns the mime time for the given uri. Typically, this MIME type will either be

    omething like

    vnd.android.cursor.item/vnd.marakana.android.lifecycle.statvnd.android.cursor.item/vnd.marakana.android.lifecycle.stator a single item or

    vnd.android.cursor.dir/vnd.marakana.android.lifecycle.statuvnd.android.cursor.dir/vnd.marakana.android.lifecycle.statu

    or multiple items.

    insert()insert()nserts the values into the provider returning uri that points to the newly insert

    ecord.

    update()update()Updates records(s) specified by either the uri or selectionselection / selectionArgsselectionArgs

    ombo. Returns number of records affected.

    delete()delete()Deletes records(s) specified by either the uri or selectionselection / selectionArgsselectionArgsombo. Returns number of records affected.

    query()query()Queries the provider for the record(s) specified by either uri

    r`selection`/ selectionArgsselectionArgs / groupinggrouping / havinghaving combo.

  • 8/18/2019 Architecting Android Apps

    33/50

    Registering Content ProviderRegistering in Android Manifest file

    he authority of this provider must match the uri authority that this provider is

    esponding to.

    ...

    ...

  • 8/18/2019 Architecting Android Apps

    34/50

    Part 5 - Lists and Adapters

    Yamba Part 5 

  • 8/18/2019 Architecting Android Apps

    35/50

    Lists and Adapters Overview 

    Lists and Adapters Overview 

    Adapters connect potentially large data sets to small views

  • 8/18/2019 Architecting Android Apps

    36/50

    Fragments

    Fragments

  • 8/18/2019 Architecting Android Apps

    37/50

    So, What’s a Fragment?

    A fragment  is a class implementing a portion of an activity.

    A fragment represents a particular operation or interface running within a larger activity.

    Fragments enable more modular activity design, making it easier to adapt an application to

    different screen orientations and multiple screen sizes.

    Fragments must be embedded in activities; they cannot run independent of activities.

    Most fragments define their own layout of views that live within the activity’s view hierarchy.

    However, a fragment can implement a behavior that has no user interface component.

    A fragment has its own lifecycle, closely related to the lifecycle of its host activity.

    A fragment can be a static part of an activity, instantiated automatically during the activity’s

    creation.

    Or, you can create, add, and remove fragments dynamically in an activity at run-time.

  • 8/18/2019 Architecting Android Apps

    38/50

    Loaders

    oaders make it easy to load data asynchronously in an activity or fragment.

    oaders have these characteristics:

    They are available to every Activity and Fragment.

    They provide asynchronous loading of data.

    They monitor the source of their data and deliver new results when the content changes.

    They automatically reconnect to the last loader’s cursor when being recreated after a

    configuration change. Thus, they don’t need to re-query their data.

    oaders were introduced in Honeycomb (API 11).

    The Android Support Package includes support for loaders. By including the support packageyour application, you can use loaders even if your application for a minSdkVersionminSdkVersion of 4 orlater.

  • 8/18/2019 Architecting Android Apps

    39/50

    Using Loaders in an Application

    An application that uses loaders typically includes the following:

    An ActivityActivity or FragmentFragment.

    An instance of the LoaderManagerLoaderManager.

    A CursorLoaderCursorLoader to load data backed by a ContentProviderContentProvider. Alternatively, you can

    implement your own subclass of LoaderLoader or AsyncTaskLoaderAsyncTaskLoader to load data from some othsource.

    A data source, such as a ContentProviderContentProvider, when using a CursorLoaderCursorLoader.

    An implementation for LoaderManager.LoaderCallbacksLoaderManager.LoaderCallbacks. This is where you create newloader instances and manage your references to existing loaders.

    A way of displaying the loader’s data, such as a SimpleCursorAdapterSimpleCursorAdapter.

  • 8/18/2019 Architecting Android Apps

    40/50

    Availability of Fragments and Loaders

    ragments: Implemented in Honeycomb (3.0) or Later

    ragments were added to the Android API in Honeycomb, API 11.

    he primary classes related to fragments are:

    android.app.Fragmentandroid.app.Fragmenthe base class for all fragment definitions

    android.app.FragmentManagerandroid.app.FragmentManagerhe class for interacting with fragment objects inside an activity

    android.app.FragmentTransactionandroid.app.FragmentTransactionhe class for performing an atomic set of fragment operations

    ragments: Implemented in Donut (1.6) or Later

    oogle provides the Compatibility Package, a Java library that you can include in

    pplication, implementing support for fragments and other Honeycomb feature

    oaders).

  • 8/18/2019 Architecting Android Apps

    41/50

    Part 6 - Broadcast Receivers

    Yamba Part 6

  • 8/18/2019 Architecting Android Apps

    42/50

    Broadcast Receiver Overview 

    Broadcast Receiver Lifecycle

    An Intent-based publish-subscribe mechanism.

    Great for listening system events such as SMS messages.

  • 8/18/2019 Architecting Android Apps

    43/50

    Broadcast Receiver Callbacks

    onReceive()onReceive()his is the only method you typically care about for a broadcast receiver. It is

    alled when this receiver is invoked.

  • 8/18/2019 Architecting Android Apps

    44/50

    Registering Broadcast ReceiverRegistering in Android Manifest file

    Registering programmatically 

     

       

    ...

    @Override

    protected void onCreate(Bundle savedInstanceState) {

      super.onCreate(savedInstanceState);

      ...

      // Create the receiver 

      receiver = new  TimelineReceiver();

      filter = new  IntentFilter( UpdaterService.NEW_STATUS_INTENT );

    }

    protected void onResume() {

      super.onResume();

      super.registerReceiver(receiver, filter,

      "com.marakana.yamba.SEND_TIMELINE_NOTIFICATIONS", null);

    }

    @Override

    protected void onPause() {

      super.onPause();

      unregisterReceiver(receiver);

    }

    ...

  • 8/18/2019 Architecting Android Apps

    45/50

    Part 7 - App Widgets

    Yamba Part 7 

  • 8/18/2019 Architecting Android Apps

    46/50

    App Widgets Overview 

    App widgets are miniature views that can live in other apps, such as Home app.

    They are a special implementation of Broadcast Receivers.

    eclaring an App WidgetWidgets are essentially Broadcast Receivers

    Yamba App Widget registration in AndroidManifest.xml

    pecifying Meta Data

    Meta data specifies the default size of the widget, plus the update period.

    Yamba Widget meta data

     

     

     

     

     

     

     

  • 8/18/2019 Architecting Android Apps

    47/50

    Yamba App Widget Output

    Yamba App Widget Output 

  • 8/18/2019 Architecting Android Apps

    48/50

    Quiz

    1. Name four main Android app building blocks.

    2. What is an activity?

    3. Name major callback methods of an activity.

    4. What is a service?

    5. Name major callback methods of a service.

    6. What is a broadcast receiver?

    7. Name major callback methods of a broadcast receiver.

    8. What is a content provider?

    9. Name major callback methods of a content provider.

    0. What does an Android app consist of?

  • 8/18/2019 Architecting Android Apps

    49/50

    Architecting Android Apps Summary 

    his module was an introduction to main components that make up an app. By

    ow, you should know of activities, services, providers and receivers as well as

    ntents and other major components of an app.

  • 8/18/2019 Architecting Android Apps

    50/50

     Architecting Android Apps Summary 

    hank you!

    Marko Gargenta & Marakana Team@MarkoGargenta

    pecial thanks to Ken Jones as well as the rest of Marakana team for research

    elated to Fragments, Loaders, and many other new features of ICS.

    lides & video of this presentation is available at Marakana.com

    amba source code is available at https://github.com/marakana/yamba

    c) Marakana.com

    https://github.com/marakana/yambahttp://marakana.com/http://twitter.com/MarkoGargenta