This post is to write down what I’ve learnd by using Android. I am a Java developer, and trying to learn Android for fun and future career. There are two reasons why I would like to learn Android. Firstly, I am naturally interested on any mobile apps. I like developing small games and tools for my mobiles. It is very fun to play and run your code on your own mobile device. And secondly Android is one of the most popular mobile OS in world. As a developer, Android uses Java as the programming language which makes it really cheap to learn.
Four Fundamental Building Blocks
- Activity Class:
- To provide GUI to user,
- The others do not have UI
- Primary Class for user interaction
- For single focused tasks
- Service
- Run in background
- To perform long-running operations
- Support remote interaction
- BroadcastReceiver
- Component listen for and responds to events
- Use publish/subscribe pattern
- Events represented by the intent class and broadcast
- Broadcastreceiver receive event and respond
- ContentProvider
- share data
- Store and share Data across applications
- Uses database-style interface
- Handles interprocess communication
Building an Application
The figure below shows an particular process to build an android project. Also, using Gradle is a very good idea to build and manage android project. Android project building process:
Activity Class
- The activity class
- Applications has multiple activities
- Android supports navigation in serveral ways
- Tasks
- A task is a set of related activities
- Don’t have to be in same applications
- Most task start at the home screen
- The task backstack
- Suspending & resuming activities
- Activity lifecycle - (Just Override ~)
- resumed/running - visible, user interacting
- paused - visible, user not interacting, can be terminated
- stopped - not visible, can be terminated
- I know this diagram is too classic, but I still like to share:
- Understanding each part on the activity lifecycle
- onCreate() :
- call super.onCreate()
- set the activity’s content view
- retain reference to UI views as necessary
- configure views as necessary
- onRestart():
- call if the activity has been stopped and is about to be started again
- typical actions : special processing needed only after having been stopped
- onStart()
- activity is about to become visible
- typical actions:
- start when visible - only behaviors
- loading persistent application state
- onResume()
- activity is about to interacting with users
- start foreground actions like animations
- onPause()
- focus about to switch to another activity
- shutdown foreground: killing animation or persistent state
- onStop()
- activity is no longer visible to user
- may not be called if android kills your app
- onDestroy()
- activity is about to be destroyed
Starting activities
- pass newly created intent to methods such as startActivity(), startActivityforResult()
- invokes a callback method when the called activity finishes to return a result. To start activity:
Return a result from an activity by call Activity.setResult()
, ResultCode(an int): RESULT_CANCELED
,REULT_OK
, RESULT_FIRST_USER
, custom result codes can be added:
Handling configuration changes
- device configuration can change at runtime (keyboard, orientation, locale)
- on configuration changes, android usually kills the current activity & then restart it
- by override onRetainNonConfigurationInstance() to build & return configuration object
- will be called between onStop() and onDestroy()
- retaining an object by call getLastNonConfigurationInstance() during onCreate() to recover retained object (could be deprecated on fragment class)
- by declare manually in
androidmanifest.xml
The Intent Class
- Starting activities with Intent
- A data structure that represent to be performed or
- An event that has occurred
- adb shell dumpsys package > data.txt
- explicit activation
- can be named explicitly by setting the intent’s components
- implicit activation via intent resolution
- can be determined implicitly, when activity to be activated is not explicitly named, android tries to find activities that match intent
- Receiving Implicit intent -to receive implicit intents an activity should specify an intentfilter with the category
- Priority:
- android:priority - priority given to the parent component when handling matching intents
- causes andorid to prefer one activity over another
- values shoud be greater than -1000 to 100, higher value in higher priority
- This process is called intent resolution:
- rely on an intent describing a desired operation
- IntentFilters which describe which operations an activity can handle
- specified either in ANDROIDMANIFEST.xml or programmatically - Intent Resolution data
- Action,
- Data (both uri & type)
- category
Specifying IntentFilters:
Adding Data to IntentFilter:
Intents as desired operations
- Intents provide a flexible language for specifying operations to be performed
- e.g. pick a contact or take a photo
- intent is constructed by one component that wants some work done
- received by one activity that can perform that work
Intent fields
- action
- string representing desired operation, e.g. ACTION_DIAL - dial a number
- setting the intent action:
Intent newint = new Intent(Intent.ACTION_DIAL);
Intent intent = new Intent(); intent.set();
- data
- data associated with the intent:
- formatted as a uniform resource identifier (URI). e.g. uri.parse(“…”)
- e.g. Data to view on map
- e.g. number to dial in the phone app
- setData() or in constructor
- category
- additional information about the components that can handle the intent
- type
- specifies the mime type of the intent data
- if not set, android will match the type itself
- set by setType(), or setDataAndType
- component
- the component that should receive this intent
- use this when there’s exactly one component that should receive the intent
Inent(Context packageContext, Class<?> cls)
orsetComponent()
,setClass()
orsetClassName()
- Context is an interface used to access global application information
- extras
- additional information associated with intent treated as a map (key-value pairs)
- e.g. Intent.EXTRA_EMAIL: email recipients
putExtra(String name, float[] floats)
orputExtra(String name, String string)
- flags
- specify how the intent to be handled
- e.g.
FLAG_ACTITY_NOHISTORY
,FLAG_DEBUG_LOG_RESOLUTION
Permissions
- android permissions
- android protects resource and data with permissions
- used to limit access to
- user information - e.g. contacts
- cost-sensitive APIs- e.g. sms/mms
- system resource - e.g. camara - permission are represented as strings - in androidmanifest.xml, apps declare the permissions - they use the permissions themselves - they require of other components to use the permission to invoke themselves
- defining & using application permissions
- defining permissions:
- suppose your application a privileged/dangerous operations
- use the tag
<permission ...></permission>
to declare a permission - should be include this permission with the application
- app specify permissions use through a
tag - users must accept these permissions before an application can be installed:
Component permissions & permissions-related APIs
- individual components can set their own permissions, restricting which other components can access them
- component permissions take precedence over application-level permissions
- activity permissions : rastrigin which components can start the associated activity, checked with startActivity(), startActityForResult()
- service permissions: checked within context.startServices(), context.stopService(), context.bindService()
- BroadcastReceviver permissions
- ContentProvider permissions
The Fragment Class
- Support multiple ui panes/ user behaviors at the same time
- Single activity holds multiple fragments
- Represent a behavior / portion of UI within an activity
- Multiple fragments can be embedded in an activity to create a multi-pane ui
- A single fragment can be reused across multiple activities
- Fragment lifecycle:
- fragment lifecycle is coordinated with the lifecycle of its containing activity
- fragments have their own lifecycles and receive their own callbacks
- fragment lifecycle states
- resumed: fragment is visible in the running activity
- paused: another activity is in the foreground and has focus, containing activity is visible
- stopped: the fragment is not visible
- lifecycle callback method:
- activity created :
onAttach()
- fragment is first attached to its activity
-
onCreate()
- initialize the fragment (don’t setup the ui)
-
onCreateView()
- Fragment sets up & returns its user interface
-
onActivityCreated()
- containing activity has completed onCreate() and the fragment has been installed
- (depend on the host activity lifecycle) activity started:
onStart()
- hosting activity is about to become visible
- activity resumed:
onResume()
- hosting activity about to become visible and ready for user interaction
- activity paused:
onPause()
: - hosting activity is visible but not has focus
- activity stopped:
onStop()
: - activity destroyed:onDestroyView()
- view previously created by
onCreateView()
has been detached from the hosting activity -onDestroy()
- fragment is no longer in use
- typical actions:
- cleanup the fragment resources
onDetach()
- cleanup the fragment resources
- fragment no longer attached to its activity
- null out reference to the hosting activity