Coursera-android
Back to current versionRestore this version

coursera-android#

Time spent#

Day hours
2014-01-21 1
2014-01-22 1
2014-01-23 1
2014-01-25 2
2014-01-31 1
2014-02-01 2
2014-02-06 2
2014-02-12 1
2014-02-14 1
2014-02-15 2
2014-02-18 1
2014-02-19 2
2014-02-20 1
2014-02-21 1
2014-02-25 1
2014-02-26 1
2014-03-01 1
2014-03-02 2

TODO#

Weeks#

Week 1#

metskem@athena ~ $ telnet localhost 5554
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Android Console: type 'help' for a list of commands
OK
help
Android console command help:

    help|h|?         print a list of commands
    event            simulate hardware events
    geo              Geo-location commands
    gsm              GSM related commands
    cdma             CDMA related commands
    kill             kill the emulator instance
    network          manage network settings
    power            power related commands
    quit|exit        quit control session
    redir            manage port redirections
    sms              SMS related commands
    avd              control virtual device execution
    window           manage emulator window
    qemu             QEMU-specific commands
    sensor           manage emulator sensors

try 'help <command>' for command-specific help
OK
adb -s emulator-5554 logcat WikiNotes:I *:S

week 2#

Four main building blocks in Android :

Non code (resource) files

Activity

The Activity Lifecycle:

android-activity-lifecycle.png

-- onRestart() , do specific stuff required after activity was stopped
-- onStart() , loading persistent application state
-- onResume() , start foreground-only actions
-- onPause() , shutdown foreground-only actions, save persistent stat
-- onStop() , cache state (may not be called when Android kills the activity)
-- onDestroy() , release activity resources (may not be called when Android kills the activity)

Activities are created by creating Intents, and passing these Intents to startActivity() or startActivityForResult() . Started activity can set the result with Activity.setResult().

AndroidManifest.xml

Contains:

week 3#

Intents

Intent is a data structure that represents:

Intent fields:

Activity is a subclass of Context, so you can for example use new Intent(MyActivity.this, SecondActivity.class);

Two ways of Intent resolution:

Implicit Intent resolution uses the following data of the Intent:

Installed apps have intent-filters defined in their AndroidManifest.xml.
These filters can specify things like data, action, category and so on. If they want to react to implicit intents, they always have to specify the intent-filter category.DEFAULT.

If you want to know what's on your device (for example all intent filters) :

adb shell dumpsys package

Permissions

Android uses permissions to protect Resources, data and operations.

Applications can define their own permissions to protect their own resources (other apps are required to have those permissions). (permission tag) And applications can define the permissions they use themselves (uses-permission).

There are application-level permissions and component-level permissions, the latter take precedence.

And we have :

Fragments

Introduced in Android 3.0 to better support larger screens (Tablets).
Fragments represent a portion of a UI within an Activity => multi-pane activities.
A single Fragment can be used across multiple activities.
The lifecycle of a Fragment is coordinated with the lifecycle of an Activity, but they also have their own lifecycle callbacks.
Fragment lifecycle states :

Fragment callbacks :

Statically add Fragment to Activity by specifying them in the layout file, or programmatically using the FragmentManager.

week 4#

User Interfaces

The View is the place and the means to exchange information between the user and the Application.

View is the key building block. It occupies a rectangular space on the screen, they are responsible for drawing themselves and handling events.
Predefined Views:

Common View operations:

View Listener Interfaces:

Displaying Views

Views are organized as a tree, Views with child Views Android walks the View tree three times:

  1. measure all views
  2. layout views
  3. draw views

ViewGroups

ViewGroups are invisable that contain other Views , use it to group/organize Views and ViewGroups.

Predefined ViewGroups:

Layouts are ViewGroups.

LinearLayout - less or more fixed order RelativeLayout - layout is relative TableLayout - child views are arranged in rows and columns GridView - 2-dimensional scrollable View

Menus and ActionBar

Activities support Menus (a quick way to access important functions). Activities can add items to the menu.

Menu types:

Creating menus getMenuInflater() , and inflate with a context menu

ActionBar, similar to desktop applications, quick access to common operations . Multiple Activities and Fragments can add items there.

Dialogs:

week 5#

Notifications

2 types of notifications, "Toast" messages, and Notifications at the status bar / drawer.

The second allowes for custom Notifications, with custom views, custom sounds, Autocancel or not, and the possibility for a "PendingIntent" that gets fired when the user clicks on the notification at the drawer. (See last part of the video, or the project NotificationStatusBarWithCustomView.

BroadcastReceiver

Base class for components that :

BroadcastReceiver register the events (Intents) they are interested in. When an intent is being broadcast, the BroadcastReceiver gets it via it's onReceive() method.

Typical use case:

Registering can be

When sending a Broadcast Intent, you can specify a permission that Receivers should have in order to get the Intent .

Event Broadcast:

And:

Debugging tips

When an intent is delivered to the onReceive(), two parms are passed:

The process receiving the intent has high priority during onReceive() processing and runs on the main thread, so make it quick. If you have long running work, let it handle by a Service.

Receiver is not considered valid after onReceive() returns. Android might terminate the BroadcastReceiver . BroadcastReceivers can't wait for asynchronous callbacks, because they then migth already be gone. So no ShowDialogs and not startActivityForResult().

BroadcastReceivers can abort the broadcast, making the Intent unavailable to receivers lower in the prio. (abortBroadcast())

BroadcastReceivers can setResultData() to the broadcast, so each receiver can see what the previous receiver has done with the result.

With sticky intents, intents can "overwrite" older intents they match.

When a BroadcastReceiver registers itself, all Android cached sticky intents will be delivered to the broadcastreceiver, and one matching sticky intent is returned to the caller.

Threads, AsyncTasks and Handlers

Only the Thread that originally created a view hierarchy is allowed to touch these views !.

So, using the UI Toolkit is reserved for the UI thread. Android provides several methods that are guaranteed to run on the UI thread:

AsyncTask

Provides a structured way to manage work involving background and UI threads.

General approach:

AsyncTask is a generic class, it takes 3 parameters: AsyncTask<Params,Progress, Result>

AsyncTask runs as follows:

Handler

Is associated with a specific Thread. One Thread can hand off work to another Thread by sending Messages and posting Runnables to a Handler associated with another ThreadM

A Handler can handle both. A Runnable is an executable piece of code, so the sender of the Runnable knows what to run and delegates this to the handler to run on his thread. A Message can also be sent, but in that case the code to be executed is in the Handler class, it should determine from the Message what/how to run stuff. (the implementation is in the Handler)

Each Android Thread is associated with a MessageQueue that holds Runnables and Messages. With this MessageQueue there is a looper associated, which picks off the runnables and messages of the queue.

So :

Alternatives handler method's :

Alarms

Mechanism to send Intents at some point in the future. An app can have code executed, even when the app itself is no longer running. Even if the device is asleep. The Alarm can wake up the device, or the Alarm can go off when the device wakes up. Alarms are cancelled on device shutdown/restart.

Examples:

Interact with the AlarmManager: getSystemService(Context.ALARM_SERVICE)

Set the alarm with set(int type, long triggerTime, PendingIntent intent) and setRepeating(. . . ) and setInexactRepeating(. . . ) , the last one lets Android decide handle it, for more efficient battery use.

Alarm types, 2 degrees of configurability:

RTC_WAKEUP, RTC, ELAPSED_REALTIME, ELAPSED_REALTIME_WAKEUP/

3 ways to get the PendingIntent : getActivity() , getBroadcast(), getService()

Networking

Useful classes:

AndroidHttpClient is an Android implementation of the Apache HttpClient, with extra customization options.

AndroidHttpClient offers use of separate response handler classes, like the JSONResponseHandler

week 6#

Graphics

Classes:

Drawing to Views, attach Drawables to Views (via xml or programming)

ShapeDrawable Are use for simple shapes, represented by subclasses:

Canvas

You need 4 things:

Drawing primitives:

Paint: setStrokeWidth(), setTextSize(), setColor(), setAntiAlias()

Canvas is suitable if you want to update the drawing frequently. Access to Canvas through GenericViews (less frequent updates) or a subclass of SurfaceView (for frequent updates)

provide secondary thread for drawing.

ostInvalidate() tells android to redraw a View.

For higher frequency smoothly updates, use Canvas with SurfaceView. SurfaceView need a separate thread.

SurfaceView must be subclassed and this subclass must implement the SurfaceHolder.callBack() interface.

Animation

Android supports several Animation support classes.

.. not many notes on this subject , no time and interest this time....

MultiMedia

Important MultiMedia classes:

AudioManager

SoundPool represents a collection of audio, multiple sample at the same time

RingToneManager provides access to audio clips used for incoming phone calls, notifications, alarms etc. It allows application to get and set ringtones and to stop/play them.

MediaPlayer controls the playback of audio and video streams and files.

common methods

VideoView is a subclass of SurfaceView. Used for displaying video.

MediaRecorder used to record audio and video (state machine). Use setAudioSource() , setVideoSource(), and the other usual ones.

Camera - access the camera service. Your application can capture images, start/stop preview. You need CAMERA permissions of course. Also specify the uses-feature tag in AndroidManifest.xml.

Commona approach:

week 7#

Sensors

Sensors are hardware devices that measure the physical environment. There are 3 type of sensors:

Important classes:

Sensor Coordinate System This does not change if the orientation changes.

Sensor values will vary constantly, for example, you cannot hold your device exactly straight or steady. So these values can be filtered, in multiple ways:

Location & maps

Classes :

Different Tradeoffs for each provider between:

LocationManager options:

Procedure for getting location:

MAPS

A visual presentation of area. Android provides maps support through the Google Maps Android V2 API

Map types:

Customizing the map:

Some map classes:

Setting up Maps application:

Required permissions:

week 8#

Data management

SharedPreferences
Small amounts of primitive data.
A persistent map, key-values, are persisted across application sessions.

Activity.getPreferences(mode) (mode=private) for one activity.
Context.getSharedPreferences(name, mode) for data shared across multiple activities.

SharedPreferences.edit() returns a SharedPreferences.Editor object, and then things like putInt() putString() and remove(key), and finally Editor.commit().

retrieving sharedprefs:

PreferenceFragment
To display and modify User Preferences.

File Storage

Internal Storage
Small to medium amounts of private data, private to the applications.

File API

FileOutputStream.openFileOutput(String name, int mode) opens private file for writing, creates it if it does not exist.

External Storage
Larger amounts of data that is non-private, such as media files. Media can appear and disappear without warning. So first determine the state of the storage, with Environment.getExternalStorageState().

Requires permission: WRITE_EXTERNAL_STORAGE

Cache files

Context.getCacheDir() returns absolute path to directory for temporary files.

Context.getExternalCacheDir()

Databases
Small to medium amounts of structured private data. SQLite is full fledged, implements most of SQL92 and supports ACID transactions (Atomic, Consistent, Isolated, Durable).