Android Mobile Application Development Essentials

Computer science16.66 KB

CSC525 Wireless and Mobile Computing

Mobile Devices: The Good

  • Always-on person
  • More than one means of connection
  • Applications are free or low cost
  • Has many sensors: accelerometer, GPS
  • Increasing in capability at an alarming rate

Mobile Devices: The Bad

  • Battery life
  • Unreliable, costly, and high-latency network access
  • Screen size
  • Different platforms across and even within device families
  • Input
  • Processor
  • Storage

How do you think you can compensate for these shortcomings?

Why Android?

  • Popularity
  • Feature set
  • Flexibility
  • No license fee
  • Powerful SDK
  • Documentation and developer community
  • Android market
  • No approval process
  • Ease of distribution and monetizing

Native vs. Web Applications

What are the pros and cons?

Types of Applications

  • Foreground: Typically only useful when visible and suspended otherwise.
  • Background: Limited interaction.
  • Intermittent: Some interaction, but mostly runs in the background. (e.g., Media player)
  • Widgets: Visual components for users' home screens.

Android Policies

  • Must respond to all user actions within 5 seconds!
  • Broadcast Receiver must return within 10 seconds!

Developing Android Applications

  • Android Studio (Eclipse-based)
  • Android SDK
  • Android Virtual Device/Emulator

Technologies Overview

  • Extensible Markup Language (XML): Human and computer-readable.
  • Specify the layouts and components to use, as well as their attributes.
  • Android Studio parses the XML to display your design in the layout editor.
  • XML is also used for app resources, such as strings, numbers, and colors.
  • Good practice: Define all strings, numeric values, and other values in XML resource files.
  • Placed in the subfolders of a project’s res folder.
  • Create resources for strings and measurements (such as a font’s size).
  • Color resources based on Google’s Material Design color palette (Google Color Guide).
  • To reach the widest audience, consider customizing apps for various locales and spoken languages.
  • Internationalization: Configuring your app so that it can be customized for various locales.
  • Localization: Customizing for a specific locale (e.g., the app on an AVD or device configured for Spanish).

Scaled Pixels and Density-Independent Pixels

  • Density-independent (dp or dip): Views and other on-screen elements.
  • Scale-independent (sp): Font sizes. Scales like dp, but also factors in user's preferred font size.

XML Fundamentals

  • XML stands for EXtensible Markup Language.
  • XML was designed to describe data.
  • Capable of describing a tree structure (vs. Table).
  • Basic Building Blocks:
    • Elements: <element>blabla</element>
    • Attributes: <sometype id=“A324”>

Processing Instr.

Open-tag

Kurt P. Brown

PRPL: A Database Workload Specification Language

1992

Univ. of Wisconsin-Madison

Element

Paul R. McJones

The 1995 SQL Reunion

Attribute

Digital System Research Center Report

SRC1997-018

1997

db/labs/dec/SRC1997-018.html

Close-tag

http://www.mcjones.org/System_R/SQL_Reunion_95/

Rules for XML

  • XML is case sensitive.
  • Open tags must have a corresponding Close tag.
  • XML preamble is the first statement: <?xml version=“1.0” encoding=“utf-8”?>
  • Every document must contain a single root element.
  • Attribute values must have quotation marks.
  • Certain characters are reserved for parsing.
  • Whitespaces are not allowed for element names.
  • Element names cannot begin with a digit.
  • Attributes only appear once in an element.

Colors in Android

  • RGB: #RRGGBB, #RGB
  • ARGB: #AARRGGBB, #ARGB

Android Manifest

  • Define min/target versions.
  • Specialized HW needs - input types.
  • Permissions: <uses-permission/>
  • Display requirements: <supports-screens/>
  • Activities
  • Any new activity must be defined in the AndroidManifest.xml file.

Resources

res subdirectories that contain the resources for your application:

  • drawable/: Directories for drawable resources, other than launcher icons.
  • layout/: Directory for files that define your app's user interface like activity_my.xml, which describes a basic layout for the MyActivity class.
  • menu/: Directory for files that define your app's menu items.
  • mipmap/: Launcher icons.
  • values/: Directory for other XML files that contain a collection of resources, such as string and color definitions.

The User Interface (UI)

  • An Android app is built using a hierarchy of View and ViewGroup objects.
  • View objects are usually UI widgets such as buttons or text fields.
  • ViewGroup objects are invisible view containers that define how the child views are laid out (i.e., LinearLayout).

Layouts

A layout contains Views:

  • FrameLayout: Each child view is in reference to the top-left corner. Use if only one View is on screen at a time.
  • LinearLayout: Views in a line, either vertically or horizontally.
  • RelativeLayout: Define positions of each child view relative to each other and screen boundaries.
  • TableLayout: Rows and columns.

EditText Properties

  • id: A unique identifier for the view. @ is required when you're referring to any resource object from XML. (e.g., android:id"@+id/edit_messag")
  • layout_width: value specifies that the view should be only as big as needed to fit the contents of the view.
  • layout_weight: Specifies the amount of remaining space each view should consume, relative to the amount consumed by sibling views. Default weight for all views is 0.

Starting Another Activity

  • android:onclick="sendMessage" – Java method
  • Intent intent = new Intent(this, DisplayMessageActivity.class);
  • An Intent is an object that provides runtime binding between separate components (such as two activities). You had to import the class.
  • An Intent can carry data types as key-value pairs called extras. See putExtra() method.
  • startActivity(intent);
  • findViewById()
  • EditText editText = (EditText) findViewById(R.id.edit_message);

Activities Overview

An “activity” is an application component that provides a screen with which users can interact.

  • Activity is usually a single screen.
  • Implemented as a single class extending Activity.
  • Displays user interface controls (views).
  • Reacts on user input/events.
  • An application typically consists of several activities.
  • Each screen is typically implemented by one activity.
  • Each activity can then start another activity (new screen).
  • An activity may return a result to the previous activity.
  • The"mai" activity is presented to the user when launching the application for the first time.

Activity Lifecycle

Each activity receives callbacks due to a change in its state during its lifecycle — whether the system is creating it, stopping it, resuming it, or destroying it:

  • onCreate(): Called when the activity is first created. Provides you with a Bundle containing the activity's previously frozen state, if there was one. Always followed by onStart(). Note: Created from Java folder! Note: Required the main activity as its hierarchical parent! All subclasses of Activity must implement the onCreate() method. This method is where the activity receives the intent with the message, then renders the message.
  • onStart(): Called when the activity is becoming visible to the user. Followed by onResume() if the activity comes to the foreground, or onStop() if it becomes hidden.
  • onResume(): Called when the activity will start interacting with the user. At this point, your activity is at the top of the activity stack, with user input going to it. Always followed by onPause().
  • onPause(): Called when the system is about to start resuming a previous activity. Implementations of this method must be very quick because the next activity will not be resumed until this method returns. Followed by either onResume() or onStop().
  • onStop(): Called when the activity is no longer visible to the user. Followed by either onRestart() if this activity is coming back to interact with the user, or onDestroy() if this activity is going away.
  • onDestroy(): The final call you receive before your activity is destroyed. This can happen either because the activity is finishing (someone called finish() on it), or because the system is temporarily destroying this instance of the activity to save space. You can distinguish between these two scenarios with the isFinishing() method.

Receiving the Message

  • Intent intent = getIntent();
  • String message = intent.getStringExtra(MyActivity.EXTRA_MESSAGE);

The TextView

  • TextView textView = new TextView(this);
  • Create textView object.
  • textView.setText(message);
  • RelativeLayout layout = (RelativeLayout) findViewById(R.id.content);
  • layout.addView(textView);

Notifications

  • Toast Notification
  • Status Bar Notification
  • Dialog Notification

Toast Usage

Toast.makeText(this, "your message", Toast.LENGTH_LONG).show();

Services

A Service is an application component that runs in the background, not interacting with the user, for an indefinite period of time.

  • Higher priority than inactive Activities, so less likely to be killed.
  • If killed, they can be configured to re-run automatically (when resources available).
  • Each service class must have a corresponding <service> declaration in its package's AndroidManifest.xml.
  • Services can be started with Context.startService() and Context.bindService().
  • Execute in the main thread of the application’s process.
  • CPU-intensive tasks must be offloaded to background threads using Thread or AsyncTask.
  • Alarms can be used to fire Intents at set times. These can start services, open Activities, or broadcast Intents.

Service Lifecycle Methods

  1. void onCreate()
  2. void onStartCommand()
  3. void onDestroy()

onStartCommand: Called whenever the Service is started with a startService call. So beware: may be executed several times in a Service’s lifetime! Controls how the system will respond if the Service is restarted (START_STICKY). Run from the main GUI thread, so the standard pattern is to create a new Thread from onStartCommand to perform processing and stopService when complete.

Forms of Services

  • Started: A service is "started" when an application component (such as an activity) starts it by calling startService(). Runs indefinitely, so it needs to stop itself!
  • Bound: A service is "bound" when an application component binds to it by calling bindService(). A bound service offers a client-server interface that allows components to interact with the service, send requests, get results, and even do so across processes with interprocess communication (IPC).

Starting a Service

// Implicitly start a Service
Intent myIntent = new Intent(MyService.ORDER_PIZZA);
myIntent.putExtra("TOPPING", "Margherita");
startService(myIntent);

// Explicitly start a Service
startService(new Intent(this, MyService.class));

(To use this example, you would need to include an ORDER_PIZZA constant in the MyService class and use an IntentFilter to register the Service as a provider of ORDER_PIZZA).

Stopping a Service

// Stop a service using the service name.
stopService(new Intent(this, service.getClass()));

Binding Activities to Services

Activity maintains a reference to a Service:

  • Activity can make calls on the Service just as any other instantiated class.
  • To support this, implement onBind for the Service.
private final IBinder binder = new MyBinder();

@Override
public IBinder onBind(Intent intent) {
    return binder;
}

public class MyBinder extends Binder {
    MyService getService() {
        return MyService.this;
    }
}
  • A component can bind to a service to interact with it and even perform interprocess communication (IPC).
  • Once the Service is bound, all public methods and properties are available through the service Binder object obtained from the onServiceConnected handler.

Background Threads

To make the app responsive, move all time-consuming operations off the main app thread to a child thread. Very important!

  • Two options: AsyncTask or Write own Threads.

On Main Thread

  • NO working with files.
  • NO network operations.
  • NO complex operations longer than 5 seconds.
public void onClick(View v) {
    new DownloadImageTask().execute("http://example.com/image.png");
}

private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
    protected Bitmap doInBackground(String... urls) {
        return loadImageFromNetwork(urls[0]);
    }

    protected void onPostExecute(Bitmap result) {
        mImageView.setImageBitmap(result);
    }
}

Execution of Asynchronous Tasks

Execution goes through the following main steps:

  • doInBackground(Params...): Used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result will be passed to onPostExecute(). publishProgress(Progress...) is used to publish one or more units of progress by calling onProgressUpdate(Progress...).
  • onProgressUpdate(Progress...): Invoked after a call to publishProgress(Progress...). Used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.
  • onPostExecute(Result): Invoked after the background computation finishes. The result of the background computation is passed to this step as a parameter.

© Copyright 1992-2016 by Pearson Education, Inc. All Rights Reserved.

Download

PDF Word HTML