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

No comments:

Post a Comment