Thursday, October 30, 2014

Next Web

I recently watched Eric Bidelman's talk from Google I/O 2013 on Web Components.  This talk was on the Future of the web platform. This talk reminds me of Angular methodology where you are adding custom tags to HTML.

As well  Peter Gasston talks about web components and CSS. Example of video player which runs on javascript, html, css.  If you show hidden dom, you can see markup.

Show shadow dom in web tools under wrench:

shadow root, host, dom

shadow root:
var newroot  = $(foo).createShadowRoot(), newElem =  '<h2<test</h2>' ;

newroot.innerHTML = newElem ;

<div id ="foo"><h1> First</h1></div>

div tag  is the shadow host, and h1 text replaces h2 with test.

widget example: <div id ="foo"><h1> First</h1></div>
want it but in different color
encapsulation - has all it needs contains within itslef, nothing gets in, nothing gets out
encapsulation in html is iframe today - issues extra network, multiplee rendering, cross orgin conflicts
better encapsulation is web components
reusable web components - shadowdom, templates,  custom tags

templates - put stuff in it

<template id ="foo"><h2> First</h2></template>
<div id ="bar"><h1>text 2</h1></div>

mark up inside is inert - does nothing, does not get loaded

inside template known as content

var test = $(foo).content.cloneNode(true), bar = document.getElementById('bar');

puts template inside bar div tag  - template active

share templates across multiple files using import

4 main areas (Shadow DOM gives encapsulation, templates or chunk of markup that later you can stamp out your elements, custom tags, html imports that can be reused via CDN URLs):

HTML templates:
Template out your markup 
Put dom in it
Parsed not rendered - won't run until you stamp it out, same for media
Hidden from document, cant traverse into,  its in its own context

Content property - document fragment , clone it, stamp it out, see whats in it


Clone it is what stamps it out (here it runs script when that happens):

New spec for html templates  : chrome supports it.

Shadow dom (Secret markup in elements):
markup encapsulation, DOM encapsulation, css style boundary protection, no bleeding in, style boundaries, exposes to developers mechanics browser vendors use to create their html elements

iframe has it but bloated, hard to use  (extra network requests needed, multiple rendering contexts)

Dom nodes can host hidden dom

hidden dom  can't be accessed by outside  javscript

Hidden document fragment

Using markup to control it

Browser vendors been holding out

Filled in markup

Shadow dom gets rendered

Style things

This time add styling make it red


Host element provide default styles

Custom elements (require hyphen)

Ability to define new elements

Plunkr example 

Using js html.prototype

Html imports

Tuesday, October 28, 2014

Coursera Android Notifications, Broadcast Receivers, AsyncTask (week 5)

Notifications pt1 slides & presentation

Notifications- messages shown to users outside normal interface (i.e download finishes and show message 1) toast messages pop up on screen 2) notification area status area system control notification area at top of device

Toasts (temporary messages that fade in/ fade out) - success or not, wont gather information
Notification area - unpredictable events that don't interrupt

Toast.makeText(getApplicationContext(), "You're toast!", Toast.LENGTH_LONG).show();
Toast with custom view
setView() - inflated view passed in

Notifications pt2 presentation

Notification area status bar where alert user of events User Interface

component called a drawer where they can pull it down to see more details

Notification can have title, detail, or icon
Notification area small ticker text, and an icon
Notification drawer to view and an action if they click on one of items - can attach an intent, can create a custom view

There is a notification Manager - system service that manages notifications

Notification.Builder notificationBuilder = new Notification.Builder     ( getApplicationContext())        .setTicker(tickerText)           .setSmallIcon(android.R.drawable.stat_sys_warning)         .setAutoCancel(true) .setContentTitle(contentTitle)         .setContentText( contentText + " (" + ++mNotificationCount + ")")           .setContentIntent(mContentIntent).setSound(soundURI)         .setVibrate(mVibratePattern); 
// Pass the Notification to the NotificationManager: NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); mNotificationManager.notify(MY_NOTIFICATION_ID,;

creates a PendingIntent using the PendingIntent.getActivity() method. The call to that method passes in an Intent flag, Intent.FLAG_ACTIVITY_NEW_TASK so that The underlying Intent may be called outside of an existing Activity.

  ContentIntent = PendingIntent.getActivity(getApplicationContext(), 0, mNotificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK);

Broadcast Receiver pt1 slides & presentation

BroadcastReceiver - base class
receive messages for that which interested, informed of events via intents, these intents broadcasted to system, delivered to those that are registered to receive them
receives event by OnReceive() being called, broadcast receivers handle event

statically by android manifest xml file:
<receiver> with <intent-filter>:

android: enabled -True/False to enabled
android : exported : outside its application
android : name - name of class implements this receiver
android : permission 
action,data,categories in intent filter

boot up - registration gets bootstrapped


<receiver android:name=".Receiver" android:exported="false" >
     <action android:name="course.examples.BroadcastReceiver.show_toast" > </action>

sendBroadcast(new Intent(CUSTOM_INTENT),android.Manifest.permission.VIBRATE);

public class Receiver extends BroadcastReceiver {  
private final String TAG = "Receiver";  
@Override public void onReceive(Context context, Intent intent) {

Dynamically - register it dynamically at runtime 

intent filter, broadcast receiver, registerReceiver

LocalBroadcastManager class - only within 1 app
Context class - system wide by any application

Context.registerReceiver()  - receiver will be called with any broadcast Intent that matches filter, in the main application thread.


mBroadcastMgr = LocalBroadcastManager .getInstance(getApplicationContext()); mBroadcastMgr.registerReceiver(receiver, intentFilter);
...       mBroadcastMgr.sendBroadcast(new Intent(CUSTOM_INTENT)); 

...       protected void onDestroy() { mBroadcastMgr.unregisterReceiver(receiver);

normal - undefined order
ordered - multiple in priority order
sticky intent - sticks around may still receive it (i.e. battery state changes)
non-sticky : discarded after initial broadcast
permission can be applied

FLAG_DEBUG_LOG_RESOLUTION - set intent flag to this for debugging

Broadcast Receiver pt2  presentation

Delivered to OnReceive (context,intent) -  android may have to start receiver , high priority when running, expensive short lived, should not block. runs in main thread, event handling should not be lengthy, try service for processing if lengthy , android may terminate onReceive() receiver, receivers cant start asynch operations.

BcastRecCompBcast in - sent out normally

BcastRecCompOrdBcast in SendOrderedBroadcast (priority order)
sendOrderedBroadcast(new Intent(CUSTOM_INTENT), android.Manifest.permission.VIBRATE);


<receiver android:name=".Receiver2" android:exported="false" > 
<intent-filter android:priority="10" > <action android:name="course.examples.BroadcastReceiver.show_toast" > </action> </intent-filter> </receiver> 

<receiver android:name=".Receiver3" android:exported="false" > 
<intent-filter android:priority="1" > <action android:name="course.examples.BroadcastReceiver.show_toast" > </action> </intent-filter> </receiver>

IntentFilter intentFilter = new IntentFilter(CUSTOM_INTENT);
registerReceiver(mReceiver, intentFilter);

Intent with priority 10 received first, followed by priority 3, however broadcast canceled by this call in receiver:

if (isOrderedBroadcast()) {abortBroadcast(); }  has different parms for method with call back like method when all receivers have been invoked.

non-sticky event is over it disposes of event,  where as sticky is opposite. want event to remain when receiver is not registered (persist over time). an example is a battery going low.  sticky events are cached by android.  new intents override older intents they match.


sendStickyBroadcast , sendStickyOrderedBroadcast

BROADCAST_STICKY permission required

telnet localhost port#

power capacity 95

Messaging pt1 slides & presentation

Multiple apps running at same time -Multithreaded
Thread - computations running at same time in process , own program counter and stack, but share heap
Runnable run()

start() - start thread,
sleep(time) - suspend thread
 wait() waits until another thread invokes the notify() on the object
notify() - wakes up a single thread that is waiting()

instantiate - use new thread() , but doesn't start thread
start thread - invoke start() and run() gets called
thread terminates - when run() returns

-load icon that takes a while
- other button toast message ,
- operation preventing the other button working

- views created by other threads can be allowed to launch it

applications have main thread (UI thread), application complements in same  process use same UI thread, life cycle methods handled in UI thread, UI toolkit not thread safe, blocking UI thread hurts applications responsiveness, long running operations need to be put in background threads. thus, dont access UI components from non-UI thread, But, update UI in UI thread.

methods that are guaranteed to run in UI thread:
- boolean action)(
- void Activity.runOnUiThread(Runnable action)


Async Tasks and Messaging pt2 presentation

Async Task - short operations
managing tasks involve work background thread and UI thread

  • bg thread - long running operations report their progress
  • ui thread  - initial setup, intermediate progress, completing operation after background does its work

class AsyncTask <Params,Progress,Results>

params -type used in background work
progress - type used when indicating progress 
result - type of result

OnPreExecute() - run in UI thread before doInBackground() starts
Result given in doInBackground() does most of works

may call publishProgress() long running progress

onProgressUpdate() to UI update

onPostExecute() in UI thread

ThreadingAsyncTask application added progress bar, how much of bit map loading is complete

AsyncTaskActivity has an inner class:
   class LoadIconTask extends AsyncTask<Integer, Integer, Bitmap> {

when someone clicks button:
   new LoadIconTask().execute(R.drawable.painter);

OnPreExecute()  in LoadIconTask
    run on UIThread and sets visibility

doInBackground() - passed in resource Id and does work of loading bitmap
    call periodically publishProgress()

OnProgressUpdate() -UIThread
   receives integer passed in to publishProgress and updates the screen percentage loaded

OnPostExecute -UIThread
   receives bitmap and makes it visible

Handler - handing off work between any 2 threads, more flexible for any 2 threads

each handler assoc specific threads - send messages and posting runnables

messages - has data sent so can run in another thread

thread has : message queue and looper

message queue -data struct holds messages and runnables dispatched by looper

handler post()

handler sendMessage() method

- message placed on message queue

handler waiting -looper reacts based on what arrived

if message , handlemessage() method
if runnable, calls runnables run() method

runnable- post(runnable r)



create messages- create message Handler.obtainMessage()

Message.obtain() - set data for message




ThreadingHandlerRunnable application

Class HandlerRunnableActivity

class LoadIconTask implements runnable

when someone clicks button:
   new Thread(new LoadIconTask(R.drawable.painter)).start();

 LoadIconTask class run method ()
   posts runnable: Runnable() { @Override public void run() {
mProgressBar.setVisibility(ProgressBar.VISIBLE); } });

 Subsequent to first post is several other  handler posts

ThreadingHandlerMessages application

in the LoadIconTask, it looks at message it receives by calling handler.obtainMessage()

calls sendMessage for Handler to execute

Android supports several HTTP clients - HttpURLConnection recommended

Runnables are used when the Sender implements the action to be taken.

Messages are used when the Handler implements the Message response​

MainActivity extends Activity implements SelectionListener

- onCreate calls ensureData()
- onResume
    // Register the BroadcastReceiver to receive a 
    // DATA_REFRESHED_ACTION broadcast
   IntentFilter filter = new IntentFilter();
   registerReceiver(mRefreshReceiver, filter);

DownloaderTask extends AsyncTask<String, Void, String[]> 

private MainActivity mParentActivity;
protected String[] doInBackground(String... urlParameters) {
     -> calls download(urlParameters);
- download method simulates tweets and then calls notify(downloadCompleted);
- notify() :
      // Sends an ordered broadcast to determine whether MainActivity is
      // active and in the foreground. Creates a new BroadcastReceiver
      // to receive a result indicating the state of MainActivity
      // The Action for this broadcast Intent is
     // MainActivity.DATA_REFRESHED_ACTION
     // The result MainActivity.IS_ALIVE, indicates that MainActivity 
     // is active and in the foreground.


Sunday, October 19, 2014

Coursera Android User Interface classes (week 4)

The fourth week covers the User Interface classes. The videos are over an our total in length.


User Interfaces pt1 presentation  & slides

View class - key building block, rectangular space, draw and events
- Button : OnClick()
- ToggleButton : 2 button states, pressed or unpressed
 - CheckBox, 2 state,  checked or not
 - RatingBar, : stars ,  highlight number of stars
AutoCompleteTextView : editable, list of text entries, touch single entry, dont have to scroll thru list

UIAutoComplete Text Entry

View events

set visibility
set checked state
set listeners
set properties

OnClickListener.onClick() , OnLongClickListener.onLongClick(), OnFocusChangeListener.onFocusChange, OnKeyListener.onKey()

view events
- listeners to indiv views
- difft listener types
- OnClick() clicked
- OnLongClick - pressed and held pressed
- OnFocusChange() - lost focus
-OnKeyListener.OnKey() - When a hardware key event is about to be presented to the View.

Measure, Positions,Draws passes


OnKeyUp() OnKeyDown()

User Interface pt 2 presentation

View Groups (compound view) - note that it is a base view for containers or layouts

RadioGroup for range like checkbox or radios that are mutually exclusive UIRadioGroup with textview and radio group, text changes to choice made

TimePicker select a time UITimePicker select button and time picker view group appears
DatePicker UIDatePicker
WebView view group that displays web pages UIWebView
MapView view groups that allows user to interact with them UIGoogleMaps

Adapter View allows you to work with data types i.e. ListView  , child views are managed by Adapter. The Adapter manages the data and provides data views to the AdapterView when it asks for it. AdapterView responsible for displaying the data only.

ListView is an adapter view, scrollable view of selectable items. Its items managed by ListAdapter, can filter items based on text that is input UIListView
call SetListAdapter with is an ArrayAdapter
- /res/layout/list_items.xml defines TextView

Spinner is AdapterView which is scrollable list of items. SpinnerAdapter UISpinner
TextView and Spinner in layout

Gallery horizontally scrolling list data managed with SpinnerAdapter UIGallery

User Interface pt 3 presentation

Layouts - view that contains viewgroup
-LinearLayout arranges children in single row (vert or horiz) UILinearLayout
-RelativeLayout  arranges children relative to each other and their parent UiRelativeLayout
-TableLayout  arranges children in rows and columns UITableLayout
-GridView arrange children in 2 dimensional scrollable grid UIGridLayout , see ImageAdapter which extends BaseAdapter

Menus - access important functions, activities add item to menu. handle clicks example:  HelloAndroidWithMenus -

1)options  menus- older style with menu key, new devices may not have this, global like data OnCreateOptionsMenu, OnOptionsMenuItemSelected

2)context menus -presses and holds view on certain views, page like data

Note: Context Menus are generally associated with individual Views, while Options Menus are generally associated with the entire application.

3)sub menus - secondary menus

Can also have shortcut keys,  group menu items, send Intents on selections of menu items

User Interface pt 4 presentation

Related menu items in group

shortcuts for menu items

Bind Itents to menu items

Action Bar added in 3.0, like a application bar in desktop apps, quick access (file,edit,help), quick access to items they use.


if your application contains a Fragment and that Fragment wants to place actions in the Action Bar
- onCreateOptionsMenu()., setHasOptionsMenu()

ActionBar.Tab - consistent way of switching views, tab area and content area


- OnTabSelected()

-AlertDialog - shows message with Y/N
-ProgressDialog - show you message about state of app progress w fragment

UIAlertDialog - first two dialogs

ToDoItem (domain object)
- public enum Priority { LOW, MED, HIGH };
- public enum Status { NOTDONE, DONE };

ToDoManagerActivity (has adapter of ToDoListAdapter mAdapter) extends ListActivity
- ListActivity.getListView() Get the activity's list view widget.
- ListView.addFooterView(View)
- ListView.setAdapter(ListAdapter)
- LayoutInflater   on footer_view.xml
  •  LayoutInflater inflater = (LayoutInflater)getApplicationContext().getSystemService (Context.LAYOUT_INFLATER_SERVICE);
  • (TextView)inflater.inflate(R.layout.footer_view, null);
  • TextView has method setOnClickListener()

ToDoListAdapter extends BaseAdapter - see Adapter

AddToDoActivity (details in put screen for ToDo)
- sends data input back to calling Activity:
      Intent data = new Intent();       ToDoItem.packageIntent(data, titleString, priority, status, fullDate);         setResult(RESULT_OK, data);       finish();

EditText -  extends TextView

  • setHint() - Sets the text to be displayed when the text of the TextView is empty.
  • setText()
  • check() -  sets the selection to the radio button whose identifier is passed in parameter
  • getCheckedRadioButtonId() -Returns the identifier of the selected radio button in this group.

Coursera Android Amazon App Store

Amazon Store how to register for  [students]

Other Android resources:
Common intents

Layout Inflater

Monday, October 13, 2014

Coursera Android Intents, Permissions, Fragement class (week 3)

Week 2 touched on Intents, now in week 3 Intents are covered in more detail.

This weeks code examples quick reference:

1) Intents Part 1 slides & presentation
intent is a data struct that represents:
- an operation to be performed
- event that has occurred in system and that you want to notify other components about
Language for specifying operations that you want to have performed
Constructed by Activity that wants some work done, Received by Activity that performs the work.

action is string that names operation to be performed such as action_edit or action_sync (set by setter or constructor of an intent)
data associated with event that is formatted as URI such as URI.parse()  (set by setter or constructor of an intent)
category is additional information about what the event can handle such as category_browsable or category_launchable
type is the mime type such as image/type (here is method for setting data and type)
component indicates the target activity passing in context and the class (see setClass, setComponent, setClassName)
extras has additional info in key value pair such as Intent.extra_email key with putExtra method
flags indicate how intent should be handled such as flag_activity_no_history or flag_debug_log_resolution which provides more information about how Android determines which Activities can respond to a given Intent.

Intents Part 2 presentation

target activity explicitly named by component
   Intent helloAndroidIntent = new Intent(LoginScreen.this, HelloAndroid.class);

also its possible to start an activity and receive a result back (example is start a camera app and receive the captured photo as a result)

Send the response back after a startActivityForResult

   Intent returnIntent = new Intent(); 

implicitly by Intent used properties on device

intent resolution - not explicit so android tries to find activities that match the intent. looks at :

  1. action
  2. data
  3. category

provide intent describing operation and intent filters describing operations the activity can handle via the manifest file or programatically

to receive an implicit intent must specify android.intent.category.DEFAULT

-1000 to 1000  priority with matching implicit intents

% adb shell dumpsys package

2) Android Permissions slides & Presentation

Android protects applications, resources & data with permissions Permissions are represented as strings Applications specify permissions they use through a tag Users must accept these permissions .

Permissions they use themselves,  or require of others.

specify permissions that the device's user must grant to the application before that application can run on the user's device:

Bookmarks permission

contacts list is private data
<uses-permission android:name="android.permission.READ_CONTACTS" >
in AndroidManifest.xml

In addition to using permissions, an app can define and enforce their own permissions. you may not want any application to use yours. Other applications must be problematically granted your permission otherwise wont be able to use the application. : simple app that has a dangerous action (Boom goes Dynamite).

Define a permission: <permission android:name="course.examples.permissionexample.BOOM_PERM" android:description="@string/boom_perm_string" android:label="@string/boom_permission_label_string"> </permission> requires 
<uses-permission android:name="course.examples.permissionexample.BOOM_PERM" /> to run

can set permission to individual components known as Activity Permissions -precedence over app level permissions 

checked with context on services start,stop,bind 
broadcast receiver permissions
content provider permissions says who can read and write data

3) Android Fragments Part 1 slides & Presentation

Fragments added for large devices in 3.0  for tablets. Fragments represent portion of UI within activity. In other words, an activity can host multiple fragments. Also, a single fragment can be reused over several activities.

Fragment life cycle coordinated with activity but has its own callbacks too

Running or Resumed (fragment is visible within running activity)
Paused (another activity visible and in foreground)
Sopped (fragment not visible)

Fragment Lifecycles
onAttach() - Fragment is first attached to its activity
onCreate() initializes fragment, doesn't create UI component though
onCreateView() sets up a returns a View (user interface) that is given to Activity
onActivityCreated() Fragment has been installed in Activity
OnStart() - coordinated with the activities OnStart() method
OnResume() - about to become visible and ready for user interation
OnPause() - losing focus
OnStop() - no longer visible
OnDestroyView()  clean up resources
OnDestroy()  no longer in use
OnDetach() - fragment no longer attached to activity

Android Fragments Part 2 Presentation

statically added or fragment manager programatically

1) in layout and set in setContentView

2) programmatically via the FragmentManager 

onCreateView returns the inflated view thats at root of the fragment layout, its is then added to the associated activity

FragmentStaticLayout FragmentStaticLayout example:


<fragment android:id="@+id/titles" android:layout_width="0px" android:layout_height="match_parent" android:layout_weight="1" class="course.examples.Fragments.StaticLayout.TitlesFragment" /> 

<fragment android:id="@+id/details" android:layout_width="0px" android:layout_height="match_parent" android:layout_weight="2" class="course.examples.Fragments.StaticLayout.QuotesFragment" />



QuoteFragment extends Fragment

  like a setContentView:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.quote_fragment, container, false);

Can add fragment dynamically on fly while its running by
1) get reference to fragment manager, 2) begin fragment transaction 3) add fragment to activity 4)commit fragment transaction

another example:

// Get a reference to the FragmentManager FragmentManager  mFragmentManager = getFragmentManager(); // Start a new FragmentTransaction FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction(); // Add the TitleFragment to the layout from main_activity.xml fragmentTransaction.add(, mFriendsFragment); // Commit the FragmentTransaction fragmentTransaction.commit();

After commit above the fragment methods get called:

  • public void onAttach(Activity activity) {
  • public void onCreate(Bundle savedInstanceState) {
  • public void onActivityCreated(Bundle savedInstanceState) {


Subviews are FrameLayout instead of fragments here.

FragmentManager fragmentManager = getFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager .beginTransaction(); fragmentTransaction.add(, new TitlesFragment()); fragmentTransaction.add(, mQuoteFragment); fragmentTransaction.commit();



public void onListSelection(int index) { if (!mQuoteFragment.isAdded()) { FragmentTransaction fragmentTransaction = mFragmentManager .beginTransaction(); fragmentTransaction.add(, mQuoteFragment); fragmentTransaction.addToBackStack(null); fragmentTransaction.commit(); mFragmentManager.executePendingTransactions(); } if (mQuoteFragment.getShownIndex() != index) { mQuoteFragment.showIndex(index); } }

config changes

Suppose you have an Activity that hosts a Fragment. This Fragment has invoked the setRetainInstance() method, passing in the parameter true.

setRetainInstance (true) - wont destroy state of fragment on config changes and retain fragment state - onDestroy and OnCreate wont be called if the Activity is later killed and restarted.

onActivityCreated method
- action: A string naming the action to perform. Usually one of the platform-defined values such as ACTION_SEND or ACTION_VIEW.
- data:  A description of the data associated with the intent.
- category : provides an additional way to characterize the activity handling the intent, usually related to the user gesture or location from which it's started. There are several different categories supported by the system, but most are rarely used. However, all implicit intents are defined with CATEGORY_DEFAULT by default.

<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="http" />

Start a new Activity using this second Intent.

Uri pageURI = Uri.parse(URL); Intent baseIntent = new Intent(Intent.ACTION_VIEW, pageURI); PackageManager packageManager = getPackageManager(); List<ResolveInfo> activities = packageManager.queryIntentActivities(baseIntent, 0); boolean isIntentSafe = activities.size() > 0;
Multiple applications may be able to handle this Intent App Chooser:

Intent chooserIntent = Intent.createChooser(baseIntent, CHOOSER_TEXT);

private EditText mEditText;
EditText  extends TextView

Saturday, October 11, 2014

Just took a Bower

Tool for easily manage the 3rd party client side libraries within your code.

The old school process is to browse, download, extract zip, find files, copy, links to files in html.

Bower eliminates most of this Its for client side files, but can do any type of files. Bower calls the files modules Packages

Bower calls into Github to get files

 npm install -g bower

 bowser install <proj>

 Dist directory js and minified one

 Add it to your project in script tag

 Get rid of something
   bower uninstall <proj>

 Updating projects (i.e. multiple)

bower update

Might need to be careful

One at a time

bower install <proj>

What packages?

bower list

bower search <proj>

bower.json file
- name,  version, main, dependencies

bower init
- prompted to create json file

- directory:relative path to folder

bower install
bower install <project> --save
bower uninstall <project> --save

Related post : []

Monday, October 6, 2014

Android Mobile Coursera class week 2 (Fundamentals and Activities)

The second week begins.

This weeks code examples quick reference:

1)Application Fundamentals 1

Activity - GUI user, interaction, single focused thing user can do, example  DialTactsActivity for tabs
Service - runs in background, non-GUI, long running operations, interaction with remote processes, share data i.e. music MediaPlaybackService
Broadcast Receiver listen for and respond to events, publish/subscribe pattern, Events represented by Intents, Broadcast receiver responds to broadcast events i.e Messaging app with broadcasting sms_recieved Intent, listener will start up service download message
- see SMS Receiver class [intent]  [intent] [lifecycle]
Content Provider store and share data, inter process communication, example browser stores bookmark in content provider BrowserProvider

src->compile->apk (signed) -> run

Define app resources (non code such as strings, layout, etc)-> implement code -> package -> install/run

string/string arrays/plurals(qunatities) - see res/values xml

<string name="myname">Luke</string>
Resource file  *string/string_name or Java R.string.string_name
accessed by other resources by @string/string_name
MapLocation App

2) Application Fundamentals 2
Layout specified in a XML file  in res/layout directory, in Java with R.layout.layout_name,
accessed by other resources by @layout/layout_name
multiple layouts by screen size and orientation
XML tag RelativeLayout, EditText visual tag, Button, graphical layout tab in eclipse
layout directory or layout-land (landscape) file generated from resources which is accessed in a program. It contains inside it other classes like id, layout, string

entry point for activity  onCreate()  - restore saved state, set content view, init the ui, bind ui actions
MapLocation activity class

AndroidManifest.xml file - name of app, components, permissions, min api level

3)  Activities Part 1

Task - set of related activities, can span multiple apps, and most start at home screen

Task Backstack -  when activity launched pushed onto stack, likewise when an activity is destroyed/exited/suspended (manually or system initiated, pops activity from stack.

Can un-suspend when user hits back button where Activity can restore state of activity on top of stack

Activity Lifecycle -
once started in running /resumed
paused - visible and user not interacting with it, can be terminated
stopped - not visible, can be terminated

announces lifecyle changes by calling template method OnCreate, OnStart (becomes visible here) OnResume (ready for user interaction), OnPause (stops being available for user interaction), OnRestart (becomes visible here sometimes when activity comes back into focus), OnStop (becomes invisible), OnDestroy. To take control you would overrride one of these methods. Collboration between your application and android.

Activity main entry point :
 <action android:name="android.intent.action.MAIN" />
if an icon for this application/activity should appear in the top-level launcher: 
<category android:name="android.intent.category.LAUNCHER" />

4) Activities Part 2

- sets up inital state calling super.OnCreate() (android initialization) , sets activity content view (what user interface should be), reference UI view elements, configure ui view elements MapLocation::OnCreate
- activity is stopped, but is about to be started again, special processing after being stopped
- Activity is about to become visible, when visible only actions such as loading saved application, state, determine location, etc
- activity visible and about to interact with user,forgeround only behavior like playing sound, or special starting app displays
-called when activity about to lose focus, shutdown foreground only displays and actions, save persistent state of app
- When activity is no longer visible to user, keeping in mind it may be restarted later, cache activity state that you want to restore later, may not be called when activity terminates (android self killing process due to low memory)
OnDestroy() - Activity aout to be killed, release activity resources, may not be called when activity terminates (android self killing process due to low memory)

One Activity may kick off another Activity programatically - create an event object called an intent which sends within it an specified information on Activity you want to start, thens pas this intent to methods such as startActivity(),where as  startActivityForResult() sends the result to callback method OnActivityResult() callback,

Here you see the request code as the second parameter:
startActivityForResult(intent, PICK_CONTACT_REQUEST);

Once its started its responsible for sending the result pack to calling program with setResult() passing in the result code, and possibly some result data (in an intent). Some built in codes that could be sent are RESULT_CANCELED, RESULT_OK, RESULT_FIRST_USER (custom result codes).

 Intent returnIntent = new Intent();  returnIntent.putExtra("result",result);  setResult(RESULT_OK,returnIntent);  finish();

- see MapLocationFromContactsActivity
The method onActivityResult() is a callback that gets invoked when a response is sent from the called Activity. This callback method gets passed in the initial request code that was sent in, the result code from the Activity, and Intent (that may contain data).

To end an activity

Can change device configuration at run time. Examples are language, screen size, orientation. When a device configuration change happens, device will kill activity and restart based on changed configuration.

Restart code should be quick. Example is changing screen orientation. Can save application state or hard to recompute data. For example, you can retain a Java object containing important state information. This is done by overriding method onRetainNonConfigurationInstance () method to build and return the configuration object. This is called between OnStop() and OnDestroy().

When this happens, OnDestroy called followed by OnCreate. The method getLastNonConfigurationInstance() is called in OnCreate to recover  this retained object. Note these methods are deprecated (see Fragments).

You can control which configuration changes you would like to handle manually. This is done with a manual declare in manifest xml file Android:configChanges and OnConfigurationChanged() method which is sent a configuration object of the new config. It is in this method you can perform work based on the new config. See

Also, here and  here on the new fragment approach.

onSaveInstanceState(Bundle savedInstanceState is called before calling OnDestroy to save Activity state. You then can restore Activity state in OnCreate or after the OnStart via Activity callback  OnRestoreInstanceState

public void onSaveInstanceState(Bundle savedInstanceState) {     
// Save state information with a collection of key-value pairs
savedInstanceState.putInt(MY_KEY, myIntVal);

onRestoreInstanceState (Bundle savedInstanceState) gets called after onStart when being reinitialized from saved out state which is passed in to this method

References :

Button launchActivityTwoButton = (Button) findViewById(;

Button extends TextView

(TextView) findViewById(;
TextView extends  View
- setText(String)

On a mac, change screen orientation with ctrl -func- f11