Android Fundamentals - Launchpad Developer Community

tibburfrogtownMobile - Wireless

Dec 14, 2013 (3 years and 8 months ago)

88 views

A An nd dr ro oiid d F Fu un nd da am me en ntta alls s
Subbu Jagadeesan
Engineering Manager – Enterprise Software
Bangalore Solution CenterDEVELOP FASTER FOR MORE
DEVICES, SOLUTIONS AND
O OP PP PO OR RT TU UN NIIT TIIE ES S
FOR
ENTERPRISEAgenda
What is Android? What is .APK file?
Why Android? Application Components
Android Architecture Activity
Linux Kernel Intent
 N Na attiiv ve e L Liib br ra ar riie es s  S Se er rv viic ce e
Android Runtime (DVM) Broadcast Receiver
Application Security Sandbox Notification
Application Framework Content Provider
ApplicationsWhat is Android?
What is Android?
Operating System?
Middleware?
Applications?
IItt’’s s a a s so offttw wa ar re e s stta ac ck k c co on ns siis sttiin ng g o off a allll tth he es se e
Kernel based on Linux 2.6Why Android?
Robust - based on Linux 2.6
Open – all applications are treated equally
 E En nd d u us se er r iis s tth he e K Kiin ng g!!!!
Developer Community SupportAndroid ArchitectureLinux Kernel
Linux 2.6 kernel core services
Memory Management
Process Management
 N Ne ettw wo or rk k S Stta ac ck k
Security
Driver ModelNative Libraries
LIBC – standard “C” library (customized for embedded Linux)
OpenGL – 2D/3D graphics
SQLite – light weight relational database engine
 F Fr re ee etty yp pe e – – b biittm ma ap p a an nd d v ve ec ctto or r ffo on ntt r re en nd de er riin ng g
Surface Manager – manages access to display subsystem
LibWebCore – webkit based library to support browser and web views
SSL – Secure Socket Layer
Media Libraries – playback / recording of popular video / audio formatsAndroid Runtime
Dalvik VM
Runs optimized Dalvik byte code (.dex format)
Java class/jar files converted to .dex at build time
Supports multiple virtual machines per deviceApplication Security Sandbox
When an Android app to be executed
A Linux user is created with the random user id
The rwx file permissions are set for the owner only and no permission is
given to group and others
A Linux process is started for the DVM
The Android app runs in that DVMApplication Framework
Activity Manager – Manages lifecycle of the activity
Package Manager – Holds information about apps loaded in the system
Telephony Manager – Handle information about telephony
 W Wiin nd do ow w M Ma an na ag ge er r – – m ma an na ag ge es s tth he e w wiin nd do ow wiin ng g s sy ys stte em m ffo or r d diis sp plla ay y
Resource Manager – Access to non-code resources such as localized strings
Content Providers – Facilitates to access data from other applications
Location Manager – Handles information about location
Notification Manager – To display custom alerts in status barApplications
Android ships with a set of core applications (Contacts, Calendar, etc)
All apps are written in Java
Developer’s code resides along with core apps
 E Ev ve en n G Go oo og glle e a ap pp ps s u us se e tth he e s sa am me e A AP PIIs s tth ha att iis s a av va aiilla ab blle e ffo or r o op pe en n d de ev ve ello op pe er r
communityWhat is .APK file?
It is a package containing
.dex files
Resources
 A As ss se etts s
Certificates
Manifest file
APK files are ZIP formatted packages based on JAR file formatAndroid Application FundamentalsAndroid Versions
Platform Version API Level VERSION_CODE
Android 4.1, 4.1.1 16 JELLY_BEAN
Android 4.0.3, 4.0.4 15 ICE_CREAM_SANDWICH_MR1
Android 4.0, 4.0.1, 4.0.2 14 ICE_CREAM_SANDWICH
Android 3.2 13 HONEYCOMB_MR2
Android 3.1.x 12 HONEYCOMB_MR1
Android 3.0.x 11 HONEYCOMB
Android 2.3.4
10 GINGERBREAD_MR1
Android 2.3.3
A An nd dr ro oiid d 2 2..3 3..2 2
Android 2.3.1 9 GINGERBREAD
Android 2.3
Android 2.2.x 8 FROYO
Android 2.1.x 7 ECLAIR_MR1
Android 2.0.1 6 ECLAIR_0_1
Android 2.0 5 ECLAIR
Android 1.6 4 DONUT
Android 1.5 3 CUPCAKE
Android 1.1 2 BASE_1_1
Android 1.0 1 BASEApplication Components
The following are the components of Android application:
Activity
Service
 IIn ntte en ntts s
IntentService
BroadcastReceiver
ContentProvider Activity
Activity Overview
Activity Lifecycle
Activity Callbacks
 A Ac cttiiv viitty y L Liiffe ec cy yc clle e E Ex xp pllo or re ed d
Registering Activity
Activity Sample
Preference ActivityActivity Overview
An activity is roughly a screen.
A typical application may have many activities.
Activities are typically expensive and so are managed by the system. Activity LifecycleActivity Lifecycle
Activities are highly managed by the system’s ActivityManager.
ActivityManager drives the activity through its states.
You as an app developer get to say what happens on transitions.Activity Callbacks
onCreate()
Used to setup your activity. You will almost always have to have it. Good place
to inflate the UI and setup listeners.
onResume() and onPause()
U Us se e tth he em m tto o ttu ur rn n o on n a an nd d o offff tth hiin ng gs s tth ha att y yo ou u’’d d lliik ke e tto o h ha av ve e r ru un nn niin ng g o on nlly y w wh hiille e tth he e
activity is visible. This is important for things that consume a lot of battery, such
as GPS and sensors.
onStart() and onStop()
Use to setup code that starts/stops the activity. Unlike onResume() and
onPause(), it includes Paused state as well. Activity Callbacks
onRestart()
Called when the activity is restarted. It is followed by onStart() and onResume().
onDestroy()
A good place to do any cleanup before the activity is cleaned up from memory.
T Th hiis s iis s tth he e c co ou un ntte er r- -p pa ar rtt tto o o on nC Cr re ea atte e( () )..
onCreateOptionsMenu()
Called when the menu is loaded (typically from an XML resource).
onOptionsItemSelected()
Called whenever an option menu item is clicked on.Activity Lifecycle Explored
Starting for the first time Pressing Home button
onCreate OnSaveInstanceState
onStart onPause
onResume onStop
Rotating the screen Restarting next time
OnSaveInstanceState onRestart
o on nP Pa au us se e o on nS Stta ar rtt
onStop onResume
onDestroy
onCreate
onStart
OnRestoreInstanceState
onResumeRegistering Activity
Register the activity in the manifest file:
...
<activity
android:name=".ActivityDemo“
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
< <//iin ntteen ntt--ffiilltteerr> >
</activity>
...
The intent filter specifies that this activity is to be the main entry point into the
application as well as that it should be shown in the app launcher on home
screen.
Any other activity
... <activity android:name=".AnotherActivity"></activity> ...Activity SamplePreference Activity
Specialized activity that knows how to display, read and write application’s user
preferences.
import android.os.Bundle;
import android.preference.PreferenceActivity;
publicclass PrefsActivityextends PreferenceActivity {
@Override
p prro otteecctteed d v vo oiid do on nC Crreeaattee( (B Bu un nd dlle e s sa av ve ed dIIn ns stta an nc ce eS Stta atte e) ) { {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.prefs);
}
}
R.xml.prefs refers to PreferenceScreen resourcePreference Activity
res/xml/prefs.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<CheckBoxPreference
android:title="Background data"
android:key="background_data"
android:summary="Use background data?">
</CheckBoxPreference>
< <L LiissttP Prreeffeerreen nccee
android:key="text_size"
android:entries="@array/text_size_entries“
android:entryValues="@array/text_size_values"
android:title="Text Size">
</ListPreference>
</PreferenceScreen>Preference Activity SampleIntent
Intent Overview
Using Intents
Intent Filters
 E Ex xp plliic ciitt a an nd d IIm mp plliic ciitt IIn ntte en ntts s S Sa am mp plle es sIntent Overview
Intents are like events or messages.
You can use them so start activities, start/stop services, or send broadcasts.
Intents can be implicit or explicit. Using Intents
startActivity()
Starts an activity specified by the intent. If activity does not exist already, it calls
onCreate() to create it. Otherwise, it calls onStart() and onResume().
startService()
S Stta ar rtts s a a s se er rv viic ce e.. E Ev ve en n iiff tth he e s se er rv viic ce e iis s n no ott c cr re ea atte ed d y ye ett,, iitt c ca alllle ed d o on nC Cr re ea atte e( () ) o on n
the service first.
stopService()
Stops a service that is already running. If service is not running, it does nothing.Using Intents
bindService()
Binds to a service. Requires that the service returns a binder via onBind()
method.
sendBroadcast()
S Se en nd ds s a a b br ro oa ad dc ca as stt.. IIff tth he er re e’’s s a a b br ro oa ad dc ca as stt r re ec ce eiiv ve er r r re eg giis stte er re ed d tto o ffiilltte er r ffo or r tth he e
same action as this intent is specifying, that receiver’s onReceive() method will
be called.Intent Filters
Intent filter is a way for us to assign certain action to an activity, service,
receiver or similar.
Action is one of system defined actions, or something you come up with.
Intent filter typically goes into Android Manifest file, within <activity>,
<service>, or <receiver> elements.
Android Manifest file
...
<intent-filter>
<action android:name="some.action.goes.here"/>
</intent-filter>
...Explicit Intent Sample
ActivityDemo.java
...
startActivity(newIntent(this, AnotherActivity.class));
...
startService(newIntent(this, ServiceDemo.class));
...
this is the context from which this intent is being sent, in our case an Activity.Implicit Intent Sample
ActivityDemo.java
...
startService(newIntent(“MSI.intent.action.IntentServiceDemo"));
...
sendBroadcast(newIntent(“MSI.intent.action.ReceiverDemo"));
...Intent Filter Sample
Requires that there’s an intent filter filtering for this particular intent, for
example:
AndroidManifest.xml
...
<service android:name=".IntentServiceDemo">
<intent-filter>
< <aaccttiio on n a an nd dr ro oiid d::n na am me e= =“ “M MS SII..iin ntte en ntt..a ac cttiio on n..IIn ntte en nttS Se er rv viic ce eD De em mo o" "//> >
</intent-filter>
</service>
...
<receiver android:name=".ReceiverDemo">
<intent-filter>
<action android:name=“MSI.intent.action.ReceiverDemo"/>
</intent-filter>
</receiver>
...Service
Service Overview
Service Lifecycle
Service Lifecycle Explored
 S Se er rv viic ce e S Sa am mp plle e
Service Callbacks
Registering Service Service Overview
Services are code that runs in the background.
They can be started and stopped. Services doesn’t have UI.Service LifecycleService Lifecycle
Service starts and "runs" until it gets a request to stop.
Service will run on the main application thread.
To offload work from main thread, use intent service.
 IIn ntte en ntt s se er rv viic ce e u us se es s w wo or rk ke er r tth hr re ea ad d,, s stto op ps s w wh he en n d do on ne e w wiitth h w wo or rk k..
Services can be bound or unbound. Service Lifecycle Explored
Starting a service first time
onCreate
onStartCommand
Restarting the same service
onStartCommand
S Stto op pp piin ng g tth he e s se er rv viic ce e
onDestroy
Starting the intent service
onCreate
onHandleIntent
onDestroyService Callbacks
onCreate()
Called when service is first created.
onStartCommand()
Called every time the service is started.
onDestroy()
Called when service is stopped. It is subsequently destroyed.
onBind()
Required, but for unbound services, we just return null. This is called when
bindService() is called.IntentService Callbacks
Constructor
It needs to pass the name of this service to its super.
onCreate()
Called when service is first created.
onHandleIntent()
This is where the work of the service runs.
onDestroy()
Called when service is stopped. It is subsequently destroyed. Registering Service
Registering a service that will be called explicitly by its class name
...
<service android:name=".ServiceDemo"></service>
...
Registering a service that will be called via action
. .. .. .
<service android:name=".IntentServiceDemo">
<intent-filter>
<action android:name=“MSI.intent.action.IntentServiceDemo" />
</intent-filter>
</service>
…IntentService SampleBroadcast Receiver
Broadcast Receiver Overview
Broadcast Receiver Sample
Broadcast Receiver Callbacks
 R Re eg giis stte er riin ng g B Br ro oa ad dc ca as stt R Re ec ce eiiv ve er rBroadcast Receiver Overview
An Intent-based publish-
subscribe mechanism.
Great for listening
system events such as
SMS messagesReceiver Lifecycle Explained
Sending a broadcast to a receiver
onReceiveBroadcast Receiver Callbacks
onReceive()
This is the only method you typically care about for a broadcast receiver. It is
called when this receiver is invoked.Registering Broadcast Receiver
Registering in Android Manifest file
<receiver android:name=".ReceiverDemo">
<intent-filter>
<action android:name=“MSI.intent.action.ReceiverDemo"/>
</intent-filter>
</receiver>Broadcast Receiver SampleNotification
Notification Overview
Notification Usage SampleNotification Overview
Alerts the user in the status bar
Contains the following elements
Icon
Notification text
Time of notification
 T Tiittlle e
Description
Intent to be started - typically some Activity gets started on clicking the
notification
Don’t forget to cancel the notificationNotification Usage SampleContent Provider
Content Provider Overview
Content Provider Lifecycle
Content Provider Lifecycle Explored
 C Co on ntte en ntt P Pr ro ov viid de er r S Sa am mp plle e
Content Provider Callbacks
Registering Content Provider Content Provider Overview
Content Providers share content with
applications across application boundaries.
Examples of built-in Content Providers are:
C Co on ntta ac ctts s
MediaStore
Settings and more. Content Provider Lifecycle
Content provider is initiated first time it is used via a call to onCreate().
There is no callback for cleaning up after the provider.
When modifying the data (insert/update/delete), open/close database atomically.
When reading the data, leave database open or else the data will get garbage
collected. Content Provider Callbacks
onCreate()
Used to initialize this content provider. This method runs on UI thread, so
should be quick. Good place to instantiate database helper, if using database.
getType()
R Re ettu ur rn ns s tth he e m miim me e tty yp pe e ffo or r tth he e g giiv ve en n u ur rii.. T Ty yp piic ca alllly y,, tth hiis s M MIIM ME E tty yp pe e w wiillll e eiitth he er r b be e
something like vnd.android.cursor.item/vnd.MSI.android.lifecycle.status for a
single item or vnd.android.cursor.dir/vnd.MSI.android.lifecycle.status for
multiple items.
insert()
Inserts the values into the provider returning uri that points to the newly inserted
record. Content Provider Callbacks
update()
Updates records(s) specified by either the uri or selection/selectionArgs combo.
Returns number of records affected.
delete()
D De elle ette es s r re ec co or rd ds s( (s s) ) s sp pe ec ciiffiie ed d b by y e eiitth he er r tth he e u ur rii o or r s se elle ec cttiio on n//s se elle ec cttiio on nA Ar rg gs s c co om mb bo o..
Returns number of records affected.
query()
Queries the provider for the record(s) specified by either uri or selection /
selectionArgs / grouping / having combo. Registering Content Provider
Registering in the manifest file:
...
<provider
android:name=".ProviderDemo“
android:authorities="com.MSI.android.lifecycle.providerdemo"/>
...
The authority of this provider must match the uri authority that this provider is
r re es sp po on nd diin ng g tto o..Recap
All applications are treated equally
Decide on the API level that your app will be supporting
All the applications are developed in Java
Each Android application runs in Application Security Sandbox
Android system can kill your activity anytime if it decides not required. Hence
save your screen data
Your application settings can be stored / retrieved easily using Preference
Activity
You could register intent filters to start your activity from any other app
Services are the code that does not have UI
Use IntentService to perform any background activity
Broadcast Receiver listens to the system event to occurT TH HA AN NK K Y YO OU U