SlideShare a Scribd company logo
Chapter Two
ANDROID - APPLICATION COMPONENTS
Application Components
Android apps are built using components
Application components are the essential building blocks of an Android application.
Android applications are comprised of one or more of the following main “building
block” components:
Activity
Service
Broadcast Receiver
Content Provider
In addition, there are a number of additional components used by these main
components: Views, layout, Fragment, Intent, Manifest and Resources.
Activity
An activity represents a single screen in your app with an interface the user can interact with.
An application has one or more activities plus a Linux process to contain them.
For example, an email app might have one activity that shows a list of new emails, another
activity to compose an email, and another activity for reading individual messages.
Typically, one activity in an app is specified as the "main" activity, which is presented to the
user when launching the application for the first time.
Each activity can then start other activities in order to perform different actions.
An activity is implemented as a subclass of activity.
Android has an activity stack or back stack to keep navigation history of activities the user has
visited.
Each time a new activity starts, the previous activity is stopped, but the system preserves
the activity in a stack (the "back stack"). When the user is done with the current activity
and presses the Back button, it is popped from the stack (and destroyed) and the previous
activity resumes.
An activity has different lifecycles to handle the state changes for your app.
Back Navigation and Back Stack
Back Navigation and Back Stack
Back navigation allows users to return to the previous activity by tapping the device
back button .
Back navigation is also called temporal navigation because the back button navigates
the history of recently viewed screens, in reverse chronological order.
The back stack keeps the set of activities that the user has visited and that can be
returned to by the user with the back button.
Each time a new activity starts, it is pushed onto the back stack and takes user focus.
The previous activity is stopped but is still available in the back stack.
The back stack operates on a "last in, first out" mechanism, so when the user is done
with the current activity and presses the Back button, that activity is popped from the
stack (and destroyed) and the previous activity resumes.
Each time the user presses the Back button, each activity in the stack is popped off to
reveal the previous one, until the user returns to the Home screen.
Activity Lifecycle
Activity Lifecycle: the set of states an activity can be in during its entire lifetime, from the time
it is initially created to when it is destroyed and the system reclaims that activity's resources.
When an activity transitions into and out of the different lifecycle states as it runs, the Android
system calls several lifecycle callback methods at each stage.
This figure shows each of the activity states and the callback methods that occur as the activity
transitions between different states:
Activity Lifecycle
onCreate(): When an activity is first created the system calls the onCreate() method to
initialize that activity.
The activity is being created.
The onCreate() method is the only required callback you must implement in your activity
class.
onStart():After your activity is initialized with onCreate(), the system calls the onStart()
method, and the activity is in the started state.
The activity is about to become visible.
onResume():Your activity is in the resumed state when it is initialized, visible on screen, and
ready to use.
The resumed state is often called the running state, because it is in this state that the user is
actually interacting with your app.
The activity has become visible (it is now "resumed").
The activity remains in the resumed state as long as the activity is in the foreground and the
user is interacting with it.
Activity Lifecycle
onPause():The activity is going into the background, but has not yet been fully
stopped.
Another activity is taking focus
onStop():An activity is in the stopped state when the user has started another
activity, or returned to the home screen.
The activity is no longer visible (it is now "stopped")
onDestroy():When your activity is destroyed it is shut down completely, and the
Activity instance is reclaimed by the system.
The activity is about to be destroyed.
onRestart():The restarted state is a transient state that only occurs if a stopped
activity is started again.
The activity is about to be restarted.
Service
A service is a component that runs in the background to perform long-running operations, like
Alarm and calendar
A service doesn’t provide a user interface
A service can be started and stopped by any component
A service can be started or bound
A started service is a service that an application component starts by calling startService() .
Use started services for tasks that run in the background to perform long-running operations.
A bound service is a service that an application component binds to itself by calling
bindService() .
Use bound services for tasks that another app component interacts with to perform
interprocess communication (IPC).
A service is implemented as a subclass of Service.
Service Lifecycle
The diagram below shows a comparison between the started and bound service lifecycles.
Service Lifecycle
The lifecycle of a service is simpler than that of an activity. However, it's even more important
that you pay close attention to how your service is created and destroyed.
 Because a service has no UI, services can continue to run in the background with no way for
the user to know, even if the user switches to another application. This consumes resources and
drains battery.
Like an activity, a service has lifecycle callback methods that you can implement to monitor
changes in the service's state and perform work at the appropriate times.
 The following are the common callback methods for managing the Service lifecycle
onCreate(): The service is being created
onStartCommand(): The service is starting, due to a call to startService()
onBind(): A client is binding to the service with bindService()
onUnbind(): All clients have unbound with unbindService()
onDestroy(): The service is no longer used and is being destroyed
Broadcast Receiver
A broadcast receiver is a component that responds to system-wide broadcast
announcements.
A broadcast receiver listens for relevant broadcast messages to trigger an event.
Some examples of broadcasted events already sent from the OS are:
The camera button was pressed.
The battery is low.
A new application was installed.
A user-generated component can also send a broadcast, such as:
 A calculation was finished.
A particular thread has started.
A broadcast receiver is implemented as a subclass of Broadcast Receiver.
Content provider
A Content Provider is a component that interacts with a repository. The app
doesn't need to know where or how the data is stored, formatted, or accessed.
A content provider:
Separates data from the app interface code
Provides a standard way of accessing the data
Makes it possible for apps to share data with other apps
A content provider is implemented as a subclass of ContentProvider.
Additional Components
Views : The basic building block for user interface is a View object which is created from the
View class and occupies a rectangular area on the screen and is responsible for drawing and
event handling.
View is the base class for widgets, which are used to create interactive UI components like
buttons, text fields, etc.
Most commonly used android views
Text View
EditText:An editable text view.
Button:A push-button control.
ImageView
ImageButton:A button that displays an image instead of text.
CheckBox:A two-state button for a multiple choice list.
Radio button:A single selection two-state button.
RadioGroup
ListView:Shows items in a vertically scrolling list.
Spinner
AutoCompleteTextView
Toast
Identifying a view
To uniquely identify a view and reference it from your code, you must give it
an id.
The android:id attribute lets you specify a unique id — a resource identifier
for a view.
For example: android:id="@+id/button_add"
The "@+id/button_add" part of the above attribute creates a new id called
button_add for the view.
We use the plus ( + ) symbol to indicate that you are creating a new id .
“@” means we’re referring to something already defined elsewhere.
Referencing a view
To refer to an existing resource identifier, omit the plus ( + ) symbol.
For example, to refer to a view by its id in another attribute, such as
android:layout_toLeftOf to control the position of a view, you would use:
android:layout_toLeftOf="@id/show_count"
In the above attribute, "@id/show_count" refers to the view with the
resource identifier show_count .
 The attribute positions the view to be "to the left of" the show_count view.
Additional Components cont.…
Layout :View hierarchies that control screen format and appearance of the
views.
Most commonly used layout types to develop android apps
Linear Layout
Relative Layout
Table Layout
Frame Layout
Absolute Layout
Linear Layout
Linear Layout: A box model in which view components are lined up in a
column or row ,one after the next.
Linear layout controls
Orientation
Fill model
Gravity
Weight
Padding
Margin
Linear Layout: Orientation
Orientation : indicates whether the Linear Layout represents a row(HORIZONTAL) or a
column (VERTICAL) .
Add the android:orientation property to your Linear Layout element in your XML layout,
setting the value to be horizontal for a row or vertical for a column.
The orientation can be modified at runtime by invoking setOrientation()
Linear Layout: Fill Model
Fill Model :Widgets have a "natural" size based on their accompanying text.
When their combined sizes does not exactly match the width of the Android device's
screen, we may have the issue of what to do with the remaining space.
All widgets inside a LinearLayout must supply dimensional attributes
android:layout_width and android:layout_height to help address the issue of empty space.
Values used in defining height and width are:
1. Specific a particular dimension, such as 125dip (device independent pixels) or 125dp,
125 px(device dependent pixels)
2. wrap_content: which means the widget should fill up its natural space, unless that is too
big, in which case Android can use word-wrap as needed to make it fit.
3. fill_parent: which means the widget should fill up all available space in its enclosing
container.
Linear Layout: Gravity
Gravity: gravity is used to indicate how a control will align on the screen.
By default widgets are left and top aligned.
You may use the XML property android:layout_gravity=“” to set other possible
arrangments like center, bottom, right etc.
The difference between:
android:gravity specifies how to place the content of view both on x- and y-axis with
in the view itself
android:layout_gravity specifies the positions f the view with respect to its parent.
Example:
android:gravity=“center”
Android:layout_gravity=“center”
Linear Layout: Weight
Weight: weight is used to proportionally assign space to widgets in a view.
You set android:layout_weight to a value (1, 2, 3, …) to indicates what proportion of the
free space should go to that widget.
Default value is 0
Linear Layout: Padding and Margin
The padding specifies how much space there is between the boundaries of the widget's
"cell" and the actual widget contents.
The margin specifies how much space there is between the boundaries of the widget’s and
its parent or other widget.
Relative Layout
Relative layout: Places view components based on their relationship.
The attributes we can use with RelativeLayout include the following:
android:layout_above: indicates that the widget should be placed above the widget
referenced in the properity.
android:layout_below: indicates that the widget should be placed below the widget
referenced in the properity.
android:layout_toLeftOf: Positions the right edge of this view to the left of another
view (identified by its ID ).
android:layout_toRightOf: Positions the left edge of this view to the right of another
view (identified by its ID ).
android:layout_centerHorizontal: Centers this view horizontally within its parent.
android:layout_centerVertical: Centers this view vertically within its parent.
android:layout_alignParentTop: Positions the top edge of this view to match the top
edge of the parent.
android:layout_alignParentBottom: Positions the bottom edge of this view to match
the bottom edge of the parent.
Table Layout
Table Layout allows to position widgets in a grid made of identifiable rows and columns.
Columns might shrink or stretch to accommodate their contents.
TableLayout works in conjunction with Table Row.
<TableRow> element is used to build a row in the table. Each row has zero or more cells;
each cell can hold one View object.
TableLayout controls the overall behavior of the container, with the widgets themselves
positioned into one or more Table Row containers, one per row in the grid.
Following are the important attributes specific to TableLayout
android:collapseColumns :This specifies the zero-based index of the columns to
collapse. The column indices must be separated by a comma: 1, 2, 5.
android:collapseColumns :The zero-based index of the columns to shrink. The column
indices must be separated by a comma: 1, 2, 5.
android:stretchColumns :The zero-based index of the columns to stretch. The column
indices must be separated by a comma: 1, 2, 5.
Table Layout
Table Layout cont.…
Absolute Layout
Additional Components cont.…
Intent :Intents are asynchronous messages which allow Android components to request
functionality from other components of the Android system.
For example, an Activity can send an Intents to the Android system which starts another
Activity.
An Intent can also contain data. This data can be used by the receiving component.
There are two types of Intents: Explicit and Implicit.
Explicit Intents explicitly defines the component which should be called by the Android
system, by using the Java class as identifie
For example the following explicit intent tells the Android system to open the activity name
called ActivityTwo
Implicit Intents do not directly specify the Android components which should be called.
For example the following implicit intent tells the Android system to the camera
Intent i=new Intent(this, ActivityTwo.class);
startActivity(i);
Intent i=new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivity(i);
Sending and Receiving data to and from Intents
To send data from one intent to another, we need to use the putExtra method. This method
takes a key and a value as an argument.
The following shows how to send data to an intent:
The component which receives the Intent can use the getIntent().getExtras() method call to
get the extra data.
The following shows how to receive data from an intent:
Intent i=new Intent(this, ActivityTwo.class)
i.putExtra(“key1”,1);
i.putExtra(“key2”, “Hello”);
i.putExtra(“key3”, new char[] {‘a’ , ‘b’});
startActivity(i);
Bundle extras=getIntent.getExtras();
If(extras!=null){
int val1=extras.getInt(“key1”);
int val2=extras.getString(“key2”);
char [] val3=extras.getCharArray(“key3”);
Additional Components cont.…
Manifest :Configuration file for the application.
Defines the basic building blocks of application
Defines details about permissions
Additional Components cont.…
Fragment : A Fragment is a piece of an activity which enable more modular activity design.
It represents a portion of user interface in an Activity.
Think of a fragment as a modular section of an activity which has its own lifecycle, receives
its own input events, and which we can add or remove while the activity is running.
we can combine multiple fragments in a single activity.
Use PagerAdapter to manage page views in fragments.
As fragments can be added, shown, hidden, and removed at any time during the lifecycle of
an activity, their existence is much more short-lived than that of other components.
Similar to an activity, a fragment has onPause(), onResume(),onDestroy(), and onCreate()
methods.
onCreate(Bundle) is the second method called on a fragment; the first one is
onAttach(Activity), which signals that there is a connection to the hosting activity now.
Only after onActivityCreated() is called is the activity passed through its own onCreate()
method.
Additional Components cont.…
Resources:Any static data that can be externalized from code.
 XML files
Images
Video and audio files
Strings
Animation etc.
 Android IDE allows you to maintain them independently
Default vs. Alternative Resources
For any type of resource, you can specify default and multiple alternative
resources for your application
 Default resources are those that should be used regardless of the device
configuration.
 Alternative resources are those that you’ve designed for use with a specific
configuration.
Organizing Resources
You should place each type of resource in a specific subdirectory of your
project's res/ directory, including:
drawable: For images and icons
layout: For layout resource files
menu: For menu items
values: For colors, dimensions, strings, and styles (theme attributes)
Once you provide a resource in your application you can apply it by referencing
its resource ID.
All resource IDs are defined in your project’s R class, which the jdk tool
automatically generates
Resources ID is composed of:
Resources type : Each resource is grouped into a type such as string, layout,
drawable, …
Resources name: The filename, excluding the extension
Accessing Resources
There are two ways to access your resources:
in code – for example, R.drawable.imageName
in xml – for example, @drawable/imageName
You can access a resource in code by passing a resource ID as a method parameter.
For example, you can set an ImageView to use the res/drawable/myImage.png using setImageResource .
ImageView imageView=(ImageView) findViewById(R.id.referenceId);
imageView.setImageResource(R.drawable.ImageName);
You can access a resource in XML by using a reference to an existing resource.
For example, if you add an ImageButton to your layout, you should use drawable resource for the image
<ImageButton
android:id="@+id/referenceId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/imageName"
Android Event Management
The reason we develop an app is to provide services to a user, and in order to use it, there must
be a way for the user to interact with it.
For an Android app, interaction typically includes tapping, pressing, typing, or talking and
listening.
Events are the messages which are generated by controls such as buttons, checkbox, radio
buttons etc.
Following are the three concepts related to Android Event Management
1. Event Listener contains a single callback method.
2.Event Handler is the method that handles the event.
3. Event Listener Registration is a process, where an Event Handler gets registered with an
Event Listener.
Event Handler is called when the Event Listener fires the event.
Event Handlers & Event Listeners
Event Handlers Event Listeners & Description
onClick() OnClickListener(): This is called when the user either clicks or touches or
focuses upon any widget like button, text, image etc.
onLongClick() OnLongClickListener(): This is called when the user either clicks or
touches or focuses upon any widget like button, text, image etc. for some
seconds
onFocusChange() OnFocusChangeListener(): This is called when the widget looses its
focus ie. user goes away from the view item.
onKey() OnFocusChangeListener():This is called when the user is focused on the
item and presses or releases a hardware key on the device.
Event Handlers & Event Listeners
Event Handlers Event Listeners & Description
onTouch() OnTouchListener(): This is called when the user presses the key,
releases the key, or any movement gesture on the screen.
onMenuItemClick() OnMenuItemClickListener(): This is called when the user
selects a menu item.
onCreateContextMenu() OnFocusChangeListener(): This is called when the context menu
is being built(as the result of a sustained "long click)
Event Listener Registration
Event Registration is the process by which an Event Handler gets
registered with an Event Listener so that the handler is called when the
Event Listener fires the event.
The three commonly used ways to register events
Using an Anonymous Inner Class
Activity class implements the Listener interface.
Using Layout xml file to specify event handler directly.
Event Listener Registration Using an Anonymous Inner Class
In this approach event handler methods can access private data of Activity
No reference is needed to call to Activity.
b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(new View. OnClickListener() {
@Override
public void onClick(View v) {
// You can handle your events
}
});
Event Listener Registration by Implementing listener Interface from
the activity Class
If the application has only a single control of Listener type, this is the shortest
and simplest of the approaches.
public class EventActivity extends Activity implements OnClickListener{
Button b1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event_ex1);
b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// You can handle your events
}
}
Event Listener Registration Using layout XML file
If you specify the handler method in layout file (.xml) via the android:onClick
attribute we do not need to implement a Listener interface or call
setOnClickListener, just put the handler method in the main Activity.
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Save"
android:onClick="chooseAction"/>
Event Listener Registration Using layout XML file
public class EventActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event_ex2);
}
@Override
public void chooseAction(View v) {
// You can handle your events
}
}
Event Handling : SMS
There are two ways to send SMS using android devices.
Using SmsManager to send SMS
Using Built-in Intent to send SMS
Using SmsManager to send SMS
The SmsManager manages SMS operations such as sending data to the given
mobile device.
You can create this object by calling the static method SmsManager.getDefault()
as follows:
SmsManager smsManager = SmsManager.getDefault();
Once you have SmsManager object, you can use sendDataMessage() method to
send SMS at the specified mobile number as follows:
smsManager.sendTextMessage("phoneNo", null, "SMS text", null, null);
getDefault(): to get the default instance of the SmsManager
sendTextMessage(String destinationAddress, String scAddress, String text,
PendingIntent sentIntent, PendingIntent deliveryIntent)
Using Built-in Intent to send SMS
You can use Android Intent to send SMS by calling built-in SMS functionality of the Android.
The following are the different Intent objects required to send an SMS.
Intent Object - Action to send SMS:You will use ACTION_VIEW object to launch an
SMS client installed on your Android device.
Intent smsIntent = new Intent(Intent.ACTION_VIEW);
Intent Object - Data/Type to send SMS :To send an SMS you need to specify smsto: as
URI using setData() method and data type will be to vnd.android-dir/mms-sms using
setType() method as follows:
smsIntent.setData(Uri.parse("smsto:"));
smsIntent.setType("vnd.android-dir/mms-sms");
Intent Object - Extra to send SMS
Android has built-in support to add phone number and text message to send an SMS as
follows:
smsIntent.putExtra("address" , new String("0123456789;3393993300"));
smsIntent.putExtra("sms_body" , "Test SMS to some one");
Event Handling : Phone Call
You can use Android Intent to make phone call by calling built-in Phone Call
functionality of the Android.
Intent Object - Action to make Phone Call :You will use ACTION_CALL
object to trigger built-in phone call functionality available in Android device.
Intent phoneIntent = new Intent(Intent.ACTION_CALL);
You can use ACTION_DIAL object instead of ACTION_CALL
Intent Object - Data/Type to make Phone Call :To make a phone call at a
given number, you need to specify tel: as URI using setData() method as
follows:
setData(Uri.parse("tel:phoneNo"));
Event Handling : Email
Intent Object - Action to send Email : You will use
ACTION_SEND object to launch an email client installed on your
Android device.
Intent emailIntent = new Intent(Intent.ACTION_SEND);
Intent Object - Data/Type to send Email :To send an email you
need to specify mailto: as URI using setData() method and data type
will be to text/plain using setType() method as follows:
emailIntent.setData(Uri.parse("mailto:"));
emailIntent.setType("text/plain");
Intent Object - Extra to send Email :Android has built-in support to
add TO, SUBJECT, CC, TEXT etc. fields which can be attached to the
intent before sending the intent to a target email client.
You can use following extra fields in your email:
EXTRA_BCC
EXTRA_CC
Event Handling : Bluetooth
Bluetooth is a way to send or receive data between two different
devices.
Android platform includes support for the Bluetooth framework that
allows a device to wirelessly exchange data with other Bluetooth
devices.
Android provides Bluetooth API to perform these different operations.
1. Scan for other Bluetooth devices
2. Get a list of paired devices
3. Connect to other devices through service discovery
Event Handling :Bluetooth
Android provides BluetoothAdapter class to communicate with Bluetooth.
Create an object of BluetoothAdapter by calling the static method
getDefaultAdapter().
private BluetoothAdapter BA;
BA = BluetoothAdapter.getDefaultAdapter();
In order to enable the Bluetooth of your device, call the intent with the following
Bluetooth constant ACTION_REQUEST_ENABLE
Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOn, 0);
Event Handling :Bluetooth
Apart from the above constant , ther are other constanst provided the API , that
supports differnet tasks.
ACTION_REQUEST_DISCOVERABLE: This constant is used for turn on
discovering of bluetooth
ACTION_STATE_CHANGED: This constant will notify that Bluetooth state
has been changed
ACTION_FOUND: This constant is used for receiving information about
each device that is discovered
Once you enable the Bluetooth , you can get a list of paired devices by calling
getBondedDevices() method. It returns a set of bluetooth devices.
private Set<BluetoothDevice>pairedDevices;
pairedDevices = BA.getBondedDevices();
Event Handling : Bluetooth
There are other methods in the API that gives more control over Bluetooth.
enable(): This method enables the adapter if not enabled
isEnabled() :This method returns true if adapter is enabled
disable():This method disables the adapter
getName():This method returns the name of the Bluetooth adapter
setName(String name) This method changes the Bluetooth name
getState() :This method returns the current state of the Bluetooth Adapter.
startDiscovery(): This method starts the discovery process of the Bluetooth for
120 seconds.
Event Handling :Camera
There are 2 basic ways to implement camera in your android
application.
1. Using existing android camera in your device
2. Directly using Camera API provided by android architecture
Event Handling :Camera
Using existing android camera in your device
MediaStore.ACTION_IMAGE_CAPTURE is used to launch an existing camera application installed on
your phone.
Syntax:
Additional intents provided by MediaStore
ACTION_VIDEO_CAPTURE : It calls the existing video application in android to capture video
EXTRA_SCREEN_ORIENTATION : It is used to set the orientation of the screen to vertical or
landscape
EXTRA_FULL_SCREEN : It is used to control the user interface of the ViewImage
INTENT_ACTION_VIDEO_CAMERA: This intent is used to launch the camea in the video
mode
EXTRA_SIZE_LIMIT : It is used to specify the size limit of video or image capture size
startActivityForResult() is used to launch the intent and wait for its result.
Syntax:
Event Handling :Camera
Directly using Camera API provided by android architecture.
Camera.open is used to intialize the camera object using the static method provide by the API.
Syntax:
Additional methods provide by the Camera class
getCameraInfo(int cameraId, Camera.CameraInfo cameraInfo) : It returns the information about a
particular camera
getNumberOfCameras() : It returns an integer number defining of cameras availaible on device
lock() : It is used to lock the camera , so no other application can access it
release() : It is used to release the lock on camera , so other applications can access it
open(int cameraId) : It is used to open particular camera when multiple cameras are supported
enableShutterSound(boolean enabled) : It is used to enable/disable default shutter sound of image
capture
Event Handling : MediaPlayer
Android is providing MediaPlayer class to access built-in mediaplayer services for playing
audio,video.
A static Method create() is used to launch MediaPlayer object
Syntax:
Once you have created the Mediaplayer object you can call some methods to start or stop the
music.
mediaPlayer.start();
 mediaPlayer.pause();
On call to start() method, the music will start playing from the begininning. If this method is
called again after the pause() method , the music would start playing from where it is left and
not from the beginning. In order to start music from the beginning , you have to call reset()
method.
Syntax:
Event Handling : MediaPlayer
Additional methods provided by MediaPlayer
isPlaying(): This method just returns true/false indicating the song is playing or not
seekTo(positon): This method takes an integer, and move song to that particular
second
getCurrentDuration(): This method returns the current position of song in
milliseconds
getDuration() : This method returns the total time duration of song in milliseconds
Event Handling :Audio recorder
Android has a built in microphone through which you can capture audio and store
it , or play it in your phone.
Android provides MediaRecorder class to record audio or video.
In order to use MediaRecorder class ,you will first create an instance of
MediaRecorder class.
Syntax:
Now you will set the source , output and encoding format and output file. Their
syntax is given below.
Event Handling :Audio recorder
After specifying the audio source, format and its output file, you can then call the two
basic methods to perpare and start recording.
Additional methods provided by MediaRecorder class
setAudioSource(): This method specifies the source of audio to be recorded
setVideoSource() : This method specifies the source of video to be recorded
setOutputFormat() : This method specifies the audio format in which audio to be
stored
setAudioEncoder() :This method specifies the audio encoder to be used
 setOutputFile(): This method configures the path to the file into which the recorded
audio is to be stored
stop(): This method stops the recording process.
Android application componenets for android app development
Ad

More Related Content

Similar to Android application componenets for android app development (20)

Activity
ActivityActivity
Activity
NikithaNag
 
Activity
ActivityActivity
Activity
NikithaNag
 
Activity
ActivityActivity
Activity
roopa_slide
 
Activity
ActivityActivity
Activity
roopa_slide
 
MAD Unit 5.pptxxxxxxxxxxxxxxxxxxxxxxxxxx
MAD Unit 5.pptxxxxxxxxxxxxxxxxxxxxxxxxxxMAD Unit 5.pptxxxxxxxxxxxxxxxxxxxxxxxxxx
MAD Unit 5.pptxxxxxxxxxxxxxxxxxxxxxxxxxx
34ShreyaChauhan
 
Android application fundamentals
Android application fundamentalsAndroid application fundamentals
Android application fundamentals
John Smith
 
Android apps development
Android apps developmentAndroid apps development
Android apps development
Monir Zzaman
 
Unit 5 Activity and Activity Life Cycle.pptx
Unit 5 Activity and Activity Life Cycle.pptxUnit 5 Activity and Activity Life Cycle.pptx
Unit 5 Activity and Activity Life Cycle.pptx
ShantanuDharekar
 
ANDROID LAB MANUAL.doc
ANDROID LAB MANUAL.docANDROID LAB MANUAL.doc
ANDROID LAB MANUAL.doc
Palakjaiswal43
 
Android application development
Android application developmentAndroid application development
Android application development
Md. Mujahid Islam
 
11.11.2020 - Unit 5-3 ACTIVITY, MENU AND SQLITE DATABASE.pptx
11.11.2020 - Unit 5-3  ACTIVITY, MENU AND SQLITE DATABASE.pptx11.11.2020 - Unit 5-3  ACTIVITY, MENU AND SQLITE DATABASE.pptx
11.11.2020 - Unit 5-3 ACTIVITY, MENU AND SQLITE DATABASE.pptx
MugiiiReee
 
App Fundamentals and Activity life cycle.pptx
App Fundamentals and Activity life cycle.pptxApp Fundamentals and Activity life cycle.pptx
App Fundamentals and Activity life cycle.pptx
ridzah12
 
Lab1-android
Lab1-androidLab1-android
Lab1-android
Lilia Sfaxi
 
Day 3: Getting Active Through Activities
Day 3: Getting Active Through ActivitiesDay 3: Getting Active Through Activities
Day 3: Getting Active Through Activities
Ahsanul Karim
 
Day 3: Getting Active Through Activities
Day 3: Getting Active Through ActivitiesDay 3: Getting Active Through Activities
Day 3: Getting Active Through Activities
Ahsanul Karim
 
iOS Development (Part 2)
iOS Development (Part 2)iOS Development (Part 2)
iOS Development (Part 2)
Asim Rais Siddiqui
 
Multiple Activity and Navigation Primer
Multiple Activity and Navigation PrimerMultiple Activity and Navigation Primer
Multiple Activity and Navigation Primer
Ahsanul Karim
 
Mobile testing android
Mobile testing   androidMobile testing   android
Mobile testing android
Basant Dewangan
 
Mobile Application Guideline | Mobile App Development Company
Mobile Application Guideline | Mobile App Development Company Mobile Application Guideline | Mobile App Development Company
Mobile Application Guideline | Mobile App Development Company
Arna Softech Private Limited
 
Android Training (Services)
Android Training (Services)Android Training (Services)
Android Training (Services)
Khaled Anaqwa
 
MAD Unit 5.pptxxxxxxxxxxxxxxxxxxxxxxxxxx
MAD Unit 5.pptxxxxxxxxxxxxxxxxxxxxxxxxxxMAD Unit 5.pptxxxxxxxxxxxxxxxxxxxxxxxxxx
MAD Unit 5.pptxxxxxxxxxxxxxxxxxxxxxxxxxx
34ShreyaChauhan
 
Android application fundamentals
Android application fundamentalsAndroid application fundamentals
Android application fundamentals
John Smith
 
Android apps development
Android apps developmentAndroid apps development
Android apps development
Monir Zzaman
 
Unit 5 Activity and Activity Life Cycle.pptx
Unit 5 Activity and Activity Life Cycle.pptxUnit 5 Activity and Activity Life Cycle.pptx
Unit 5 Activity and Activity Life Cycle.pptx
ShantanuDharekar
 
ANDROID LAB MANUAL.doc
ANDROID LAB MANUAL.docANDROID LAB MANUAL.doc
ANDROID LAB MANUAL.doc
Palakjaiswal43
 
Android application development
Android application developmentAndroid application development
Android application development
Md. Mujahid Islam
 
11.11.2020 - Unit 5-3 ACTIVITY, MENU AND SQLITE DATABASE.pptx
11.11.2020 - Unit 5-3  ACTIVITY, MENU AND SQLITE DATABASE.pptx11.11.2020 - Unit 5-3  ACTIVITY, MENU AND SQLITE DATABASE.pptx
11.11.2020 - Unit 5-3 ACTIVITY, MENU AND SQLITE DATABASE.pptx
MugiiiReee
 
App Fundamentals and Activity life cycle.pptx
App Fundamentals and Activity life cycle.pptxApp Fundamentals and Activity life cycle.pptx
App Fundamentals and Activity life cycle.pptx
ridzah12
 
Day 3: Getting Active Through Activities
Day 3: Getting Active Through ActivitiesDay 3: Getting Active Through Activities
Day 3: Getting Active Through Activities
Ahsanul Karim
 
Day 3: Getting Active Through Activities
Day 3: Getting Active Through ActivitiesDay 3: Getting Active Through Activities
Day 3: Getting Active Through Activities
Ahsanul Karim
 
Multiple Activity and Navigation Primer
Multiple Activity and Navigation PrimerMultiple Activity and Navigation Primer
Multiple Activity and Navigation Primer
Ahsanul Karim
 
Mobile Application Guideline | Mobile App Development Company
Mobile Application Guideline | Mobile App Development Company Mobile Application Guideline | Mobile App Development Company
Mobile Application Guideline | Mobile App Development Company
Arna Softech Private Limited
 
Android Training (Services)
Android Training (Services)Android Training (Services)
Android Training (Services)
Khaled Anaqwa
 

Recently uploaded (20)

AI-proof your career by Olivier Vroom and David WIlliamson
AI-proof your career by Olivier Vroom and David WIlliamsonAI-proof your career by Olivier Vroom and David WIlliamson
AI-proof your career by Olivier Vroom and David WIlliamson
UXPA Boston
 
An Overview of Salesforce Health Cloud & How is it Transforming Patient Care
An Overview of Salesforce Health Cloud & How is it Transforming Patient CareAn Overview of Salesforce Health Cloud & How is it Transforming Patient Care
An Overview of Salesforce Health Cloud & How is it Transforming Patient Care
Cyntexa
 
Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Wonjun Hwang
 
Cybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and MitigationCybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and Mitigation
VICTOR MAESTRE RAMIREZ
 
Artificial_Intelligence_in_Everyday_Life.pptx
Artificial_Intelligence_in_Everyday_Life.pptxArtificial_Intelligence_in_Everyday_Life.pptx
Artificial_Intelligence_in_Everyday_Life.pptx
03ANMOLCHAURASIYA
 
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier VroomAI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
UXPA Boston
 
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptxReimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
John Moore
 
Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...
Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...
Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...
Mike Mingos
 
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdfKit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Wonjun Hwang
 
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Markus Eisele
 
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Raffi Khatchadourian
 
Slack like a pro: strategies for 10x engineering teams
Slack like a pro: strategies for 10x engineering teamsSlack like a pro: strategies for 10x engineering teams
Slack like a pro: strategies for 10x engineering teams
Nacho Cougil
 
IT488 Wireless Sensor Networks_Information Technology
IT488 Wireless Sensor Networks_Information TechnologyIT488 Wireless Sensor Networks_Information Technology
IT488 Wireless Sensor Networks_Information Technology
SHEHABALYAMANI
 
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à GenèveUiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPathCommunity
 
machines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdfmachines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdf
AmirStern2
 
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
Ivano Malavolta
 
Mastering Testing in the Modern F&B Landscape
Mastering Testing in the Modern F&B LandscapeMastering Testing in the Modern F&B Landscape
Mastering Testing in the Modern F&B Landscape
marketing943205
 
IT484 Cyber Forensics_Information Technology
IT484 Cyber Forensics_Information TechnologyIT484 Cyber Forensics_Information Technology
IT484 Cyber Forensics_Information Technology
SHEHABALYAMANI
 
fennec fox optimization algorithm for optimal solution
fennec fox optimization algorithm for optimal solutionfennec fox optimization algorithm for optimal solution
fennec fox optimization algorithm for optimal solution
shallal2
 
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
Lorenzo Miniero
 
AI-proof your career by Olivier Vroom and David WIlliamson
AI-proof your career by Olivier Vroom and David WIlliamsonAI-proof your career by Olivier Vroom and David WIlliamson
AI-proof your career by Olivier Vroom and David WIlliamson
UXPA Boston
 
An Overview of Salesforce Health Cloud & How is it Transforming Patient Care
An Overview of Salesforce Health Cloud & How is it Transforming Patient CareAn Overview of Salesforce Health Cloud & How is it Transforming Patient Care
An Overview of Salesforce Health Cloud & How is it Transforming Patient Care
Cyntexa
 
Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Wonjun Hwang
 
Cybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and MitigationCybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and Mitigation
VICTOR MAESTRE RAMIREZ
 
Artificial_Intelligence_in_Everyday_Life.pptx
Artificial_Intelligence_in_Everyday_Life.pptxArtificial_Intelligence_in_Everyday_Life.pptx
Artificial_Intelligence_in_Everyday_Life.pptx
03ANMOLCHAURASIYA
 
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier VroomAI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
UXPA Boston
 
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptxReimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
John Moore
 
Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...
Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...
Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...
Mike Mingos
 
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdfKit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Wonjun Hwang
 
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Markus Eisele
 
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Raffi Khatchadourian
 
Slack like a pro: strategies for 10x engineering teams
Slack like a pro: strategies for 10x engineering teamsSlack like a pro: strategies for 10x engineering teams
Slack like a pro: strategies for 10x engineering teams
Nacho Cougil
 
IT488 Wireless Sensor Networks_Information Technology
IT488 Wireless Sensor Networks_Information TechnologyIT488 Wireless Sensor Networks_Information Technology
IT488 Wireless Sensor Networks_Information Technology
SHEHABALYAMANI
 
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à GenèveUiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPathCommunity
 
machines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdfmachines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdf
AmirStern2
 
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
Ivano Malavolta
 
Mastering Testing in the Modern F&B Landscape
Mastering Testing in the Modern F&B LandscapeMastering Testing in the Modern F&B Landscape
Mastering Testing in the Modern F&B Landscape
marketing943205
 
IT484 Cyber Forensics_Information Technology
IT484 Cyber Forensics_Information TechnologyIT484 Cyber Forensics_Information Technology
IT484 Cyber Forensics_Information Technology
SHEHABALYAMANI
 
fennec fox optimization algorithm for optimal solution
fennec fox optimization algorithm for optimal solutionfennec fox optimization algorithm for optimal solution
fennec fox optimization algorithm for optimal solution
shallal2
 
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
Lorenzo Miniero
 
Ad

Android application componenets for android app development

  • 1. Chapter Two ANDROID - APPLICATION COMPONENTS
  • 2. Application Components Android apps are built using components Application components are the essential building blocks of an Android application. Android applications are comprised of one or more of the following main “building block” components: Activity Service Broadcast Receiver Content Provider In addition, there are a number of additional components used by these main components: Views, layout, Fragment, Intent, Manifest and Resources.
  • 3. Activity An activity represents a single screen in your app with an interface the user can interact with. An application has one or more activities plus a Linux process to contain them. For example, an email app might have one activity that shows a list of new emails, another activity to compose an email, and another activity for reading individual messages. Typically, one activity in an app is specified as the "main" activity, which is presented to the user when launching the application for the first time. Each activity can then start other activities in order to perform different actions. An activity is implemented as a subclass of activity. Android has an activity stack or back stack to keep navigation history of activities the user has visited. Each time a new activity starts, the previous activity is stopped, but the system preserves the activity in a stack (the "back stack"). When the user is done with the current activity and presses the Back button, it is popped from the stack (and destroyed) and the previous activity resumes. An activity has different lifecycles to handle the state changes for your app.
  • 4. Back Navigation and Back Stack
  • 5. Back Navigation and Back Stack Back navigation allows users to return to the previous activity by tapping the device back button . Back navigation is also called temporal navigation because the back button navigates the history of recently viewed screens, in reverse chronological order. The back stack keeps the set of activities that the user has visited and that can be returned to by the user with the back button. Each time a new activity starts, it is pushed onto the back stack and takes user focus. The previous activity is stopped but is still available in the back stack. The back stack operates on a "last in, first out" mechanism, so when the user is done with the current activity and presses the Back button, that activity is popped from the stack (and destroyed) and the previous activity resumes. Each time the user presses the Back button, each activity in the stack is popped off to reveal the previous one, until the user returns to the Home screen.
  • 6. Activity Lifecycle Activity Lifecycle: the set of states an activity can be in during its entire lifetime, from the time it is initially created to when it is destroyed and the system reclaims that activity's resources. When an activity transitions into and out of the different lifecycle states as it runs, the Android system calls several lifecycle callback methods at each stage. This figure shows each of the activity states and the callback methods that occur as the activity transitions between different states:
  • 7. Activity Lifecycle onCreate(): When an activity is first created the system calls the onCreate() method to initialize that activity. The activity is being created. The onCreate() method is the only required callback you must implement in your activity class. onStart():After your activity is initialized with onCreate(), the system calls the onStart() method, and the activity is in the started state. The activity is about to become visible. onResume():Your activity is in the resumed state when it is initialized, visible on screen, and ready to use. The resumed state is often called the running state, because it is in this state that the user is actually interacting with your app. The activity has become visible (it is now "resumed"). The activity remains in the resumed state as long as the activity is in the foreground and the user is interacting with it.
  • 8. Activity Lifecycle onPause():The activity is going into the background, but has not yet been fully stopped. Another activity is taking focus onStop():An activity is in the stopped state when the user has started another activity, or returned to the home screen. The activity is no longer visible (it is now "stopped") onDestroy():When your activity is destroyed it is shut down completely, and the Activity instance is reclaimed by the system. The activity is about to be destroyed. onRestart():The restarted state is a transient state that only occurs if a stopped activity is started again. The activity is about to be restarted.
  • 9. Service A service is a component that runs in the background to perform long-running operations, like Alarm and calendar A service doesn’t provide a user interface A service can be started and stopped by any component A service can be started or bound A started service is a service that an application component starts by calling startService() . Use started services for tasks that run in the background to perform long-running operations. A bound service is a service that an application component binds to itself by calling bindService() . Use bound services for tasks that another app component interacts with to perform interprocess communication (IPC). A service is implemented as a subclass of Service.
  • 10. Service Lifecycle The diagram below shows a comparison between the started and bound service lifecycles.
  • 11. Service Lifecycle The lifecycle of a service is simpler than that of an activity. However, it's even more important that you pay close attention to how your service is created and destroyed.  Because a service has no UI, services can continue to run in the background with no way for the user to know, even if the user switches to another application. This consumes resources and drains battery. Like an activity, a service has lifecycle callback methods that you can implement to monitor changes in the service's state and perform work at the appropriate times.  The following are the common callback methods for managing the Service lifecycle onCreate(): The service is being created onStartCommand(): The service is starting, due to a call to startService() onBind(): A client is binding to the service with bindService() onUnbind(): All clients have unbound with unbindService() onDestroy(): The service is no longer used and is being destroyed
  • 12. Broadcast Receiver A broadcast receiver is a component that responds to system-wide broadcast announcements. A broadcast receiver listens for relevant broadcast messages to trigger an event. Some examples of broadcasted events already sent from the OS are: The camera button was pressed. The battery is low. A new application was installed. A user-generated component can also send a broadcast, such as:  A calculation was finished. A particular thread has started. A broadcast receiver is implemented as a subclass of Broadcast Receiver.
  • 13. Content provider A Content Provider is a component that interacts with a repository. The app doesn't need to know where or how the data is stored, formatted, or accessed. A content provider: Separates data from the app interface code Provides a standard way of accessing the data Makes it possible for apps to share data with other apps A content provider is implemented as a subclass of ContentProvider.
  • 14. Additional Components Views : The basic building block for user interface is a View object which is created from the View class and occupies a rectangular area on the screen and is responsible for drawing and event handling. View is the base class for widgets, which are used to create interactive UI components like buttons, text fields, etc. Most commonly used android views Text View EditText:An editable text view. Button:A push-button control. ImageView ImageButton:A button that displays an image instead of text. CheckBox:A two-state button for a multiple choice list. Radio button:A single selection two-state button. RadioGroup ListView:Shows items in a vertically scrolling list. Spinner AutoCompleteTextView Toast
  • 15. Identifying a view To uniquely identify a view and reference it from your code, you must give it an id. The android:id attribute lets you specify a unique id — a resource identifier for a view. For example: android:id="@+id/button_add" The "@+id/button_add" part of the above attribute creates a new id called button_add for the view. We use the plus ( + ) symbol to indicate that you are creating a new id . “@” means we’re referring to something already defined elsewhere.
  • 16. Referencing a view To refer to an existing resource identifier, omit the plus ( + ) symbol. For example, to refer to a view by its id in another attribute, such as android:layout_toLeftOf to control the position of a view, you would use: android:layout_toLeftOf="@id/show_count" In the above attribute, "@id/show_count" refers to the view with the resource identifier show_count .  The attribute positions the view to be "to the left of" the show_count view.
  • 17. Additional Components cont.… Layout :View hierarchies that control screen format and appearance of the views. Most commonly used layout types to develop android apps Linear Layout Relative Layout Table Layout Frame Layout Absolute Layout
  • 18. Linear Layout Linear Layout: A box model in which view components are lined up in a column or row ,one after the next. Linear layout controls Orientation Fill model Gravity Weight Padding Margin
  • 19. Linear Layout: Orientation Orientation : indicates whether the Linear Layout represents a row(HORIZONTAL) or a column (VERTICAL) . Add the android:orientation property to your Linear Layout element in your XML layout, setting the value to be horizontal for a row or vertical for a column. The orientation can be modified at runtime by invoking setOrientation()
  • 20. Linear Layout: Fill Model Fill Model :Widgets have a "natural" size based on their accompanying text. When their combined sizes does not exactly match the width of the Android device's screen, we may have the issue of what to do with the remaining space. All widgets inside a LinearLayout must supply dimensional attributes android:layout_width and android:layout_height to help address the issue of empty space. Values used in defining height and width are: 1. Specific a particular dimension, such as 125dip (device independent pixels) or 125dp, 125 px(device dependent pixels) 2. wrap_content: which means the widget should fill up its natural space, unless that is too big, in which case Android can use word-wrap as needed to make it fit. 3. fill_parent: which means the widget should fill up all available space in its enclosing container.
  • 21. Linear Layout: Gravity Gravity: gravity is used to indicate how a control will align on the screen. By default widgets are left and top aligned. You may use the XML property android:layout_gravity=“” to set other possible arrangments like center, bottom, right etc. The difference between: android:gravity specifies how to place the content of view both on x- and y-axis with in the view itself android:layout_gravity specifies the positions f the view with respect to its parent. Example: android:gravity=“center” Android:layout_gravity=“center”
  • 22. Linear Layout: Weight Weight: weight is used to proportionally assign space to widgets in a view. You set android:layout_weight to a value (1, 2, 3, …) to indicates what proportion of the free space should go to that widget. Default value is 0 Linear Layout: Padding and Margin The padding specifies how much space there is between the boundaries of the widget's "cell" and the actual widget contents. The margin specifies how much space there is between the boundaries of the widget’s and its parent or other widget.
  • 23. Relative Layout Relative layout: Places view components based on their relationship. The attributes we can use with RelativeLayout include the following: android:layout_above: indicates that the widget should be placed above the widget referenced in the properity. android:layout_below: indicates that the widget should be placed below the widget referenced in the properity. android:layout_toLeftOf: Positions the right edge of this view to the left of another view (identified by its ID ). android:layout_toRightOf: Positions the left edge of this view to the right of another view (identified by its ID ). android:layout_centerHorizontal: Centers this view horizontally within its parent. android:layout_centerVertical: Centers this view vertically within its parent. android:layout_alignParentTop: Positions the top edge of this view to match the top edge of the parent. android:layout_alignParentBottom: Positions the bottom edge of this view to match the bottom edge of the parent.
  • 24. Table Layout Table Layout allows to position widgets in a grid made of identifiable rows and columns. Columns might shrink or stretch to accommodate their contents. TableLayout works in conjunction with Table Row. <TableRow> element is used to build a row in the table. Each row has zero or more cells; each cell can hold one View object. TableLayout controls the overall behavior of the container, with the widgets themselves positioned into one or more Table Row containers, one per row in the grid. Following are the important attributes specific to TableLayout android:collapseColumns :This specifies the zero-based index of the columns to collapse. The column indices must be separated by a comma: 1, 2, 5. android:collapseColumns :The zero-based index of the columns to shrink. The column indices must be separated by a comma: 1, 2, 5. android:stretchColumns :The zero-based index of the columns to stretch. The column indices must be separated by a comma: 1, 2, 5.
  • 28. Additional Components cont.… Intent :Intents are asynchronous messages which allow Android components to request functionality from other components of the Android system. For example, an Activity can send an Intents to the Android system which starts another Activity. An Intent can also contain data. This data can be used by the receiving component. There are two types of Intents: Explicit and Implicit. Explicit Intents explicitly defines the component which should be called by the Android system, by using the Java class as identifie For example the following explicit intent tells the Android system to open the activity name called ActivityTwo Implicit Intents do not directly specify the Android components which should be called. For example the following implicit intent tells the Android system to the camera Intent i=new Intent(this, ActivityTwo.class); startActivity(i); Intent i=new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); startActivity(i);
  • 29. Sending and Receiving data to and from Intents To send data from one intent to another, we need to use the putExtra method. This method takes a key and a value as an argument. The following shows how to send data to an intent: The component which receives the Intent can use the getIntent().getExtras() method call to get the extra data. The following shows how to receive data from an intent: Intent i=new Intent(this, ActivityTwo.class) i.putExtra(“key1”,1); i.putExtra(“key2”, “Hello”); i.putExtra(“key3”, new char[] {‘a’ , ‘b’}); startActivity(i); Bundle extras=getIntent.getExtras(); If(extras!=null){ int val1=extras.getInt(“key1”); int val2=extras.getString(“key2”); char [] val3=extras.getCharArray(“key3”);
  • 30. Additional Components cont.… Manifest :Configuration file for the application. Defines the basic building blocks of application Defines details about permissions
  • 31. Additional Components cont.… Fragment : A Fragment is a piece of an activity which enable more modular activity design. It represents a portion of user interface in an Activity. Think of a fragment as a modular section of an activity which has its own lifecycle, receives its own input events, and which we can add or remove while the activity is running. we can combine multiple fragments in a single activity. Use PagerAdapter to manage page views in fragments. As fragments can be added, shown, hidden, and removed at any time during the lifecycle of an activity, their existence is much more short-lived than that of other components. Similar to an activity, a fragment has onPause(), onResume(),onDestroy(), and onCreate() methods. onCreate(Bundle) is the second method called on a fragment; the first one is onAttach(Activity), which signals that there is a connection to the hosting activity now. Only after onActivityCreated() is called is the activity passed through its own onCreate() method.
  • 32. Additional Components cont.… Resources:Any static data that can be externalized from code.  XML files Images Video and audio files Strings Animation etc.  Android IDE allows you to maintain them independently Default vs. Alternative Resources For any type of resource, you can specify default and multiple alternative resources for your application  Default resources are those that should be used regardless of the device configuration.  Alternative resources are those that you’ve designed for use with a specific configuration.
  • 33. Organizing Resources You should place each type of resource in a specific subdirectory of your project's res/ directory, including: drawable: For images and icons layout: For layout resource files menu: For menu items values: For colors, dimensions, strings, and styles (theme attributes) Once you provide a resource in your application you can apply it by referencing its resource ID. All resource IDs are defined in your project’s R class, which the jdk tool automatically generates Resources ID is composed of: Resources type : Each resource is grouped into a type such as string, layout, drawable, … Resources name: The filename, excluding the extension
  • 34. Accessing Resources There are two ways to access your resources: in code – for example, R.drawable.imageName in xml – for example, @drawable/imageName You can access a resource in code by passing a resource ID as a method parameter. For example, you can set an ImageView to use the res/drawable/myImage.png using setImageResource . ImageView imageView=(ImageView) findViewById(R.id.referenceId); imageView.setImageResource(R.drawable.ImageName); You can access a resource in XML by using a reference to an existing resource. For example, if you add an ImageButton to your layout, you should use drawable resource for the image <ImageButton android:id="@+id/referenceId" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/imageName"
  • 35. Android Event Management The reason we develop an app is to provide services to a user, and in order to use it, there must be a way for the user to interact with it. For an Android app, interaction typically includes tapping, pressing, typing, or talking and listening. Events are the messages which are generated by controls such as buttons, checkbox, radio buttons etc. Following are the three concepts related to Android Event Management 1. Event Listener contains a single callback method. 2.Event Handler is the method that handles the event. 3. Event Listener Registration is a process, where an Event Handler gets registered with an Event Listener. Event Handler is called when the Event Listener fires the event.
  • 36. Event Handlers & Event Listeners Event Handlers Event Listeners & Description onClick() OnClickListener(): This is called when the user either clicks or touches or focuses upon any widget like button, text, image etc. onLongClick() OnLongClickListener(): This is called when the user either clicks or touches or focuses upon any widget like button, text, image etc. for some seconds onFocusChange() OnFocusChangeListener(): This is called when the widget looses its focus ie. user goes away from the view item. onKey() OnFocusChangeListener():This is called when the user is focused on the item and presses or releases a hardware key on the device.
  • 37. Event Handlers & Event Listeners Event Handlers Event Listeners & Description onTouch() OnTouchListener(): This is called when the user presses the key, releases the key, or any movement gesture on the screen. onMenuItemClick() OnMenuItemClickListener(): This is called when the user selects a menu item. onCreateContextMenu() OnFocusChangeListener(): This is called when the context menu is being built(as the result of a sustained "long click)
  • 38. Event Listener Registration Event Registration is the process by which an Event Handler gets registered with an Event Listener so that the handler is called when the Event Listener fires the event. The three commonly used ways to register events Using an Anonymous Inner Class Activity class implements the Listener interface. Using Layout xml file to specify event handler directly.
  • 39. Event Listener Registration Using an Anonymous Inner Class In this approach event handler methods can access private data of Activity No reference is needed to call to Activity. b1 = (Button) findViewById(R.id.button1); b1.setOnClickListener(new View. OnClickListener() { @Override public void onClick(View v) { // You can handle your events } });
  • 40. Event Listener Registration by Implementing listener Interface from the activity Class If the application has only a single control of Listener type, this is the shortest and simplest of the approaches. public class EventActivity extends Activity implements OnClickListener{ Button b1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_event_ex1); b1 = (Button) findViewById(R.id.button1); b1.setOnClickListener(this); } @Override public void onClick(View v) { // You can handle your events } }
  • 41. Event Listener Registration Using layout XML file If you specify the handler method in layout file (.xml) via the android:onClick attribute we do not need to implement a Listener interface or call setOnClickListener, just put the handler method in the main Activity. <Button android:id="@+id/button1" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Save" android:onClick="chooseAction"/>
  • 42. Event Listener Registration Using layout XML file public class EventActivity extends Activity{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_event_ex2); } @Override public void chooseAction(View v) { // You can handle your events } }
  • 43. Event Handling : SMS There are two ways to send SMS using android devices. Using SmsManager to send SMS Using Built-in Intent to send SMS
  • 44. Using SmsManager to send SMS The SmsManager manages SMS operations such as sending data to the given mobile device. You can create this object by calling the static method SmsManager.getDefault() as follows: SmsManager smsManager = SmsManager.getDefault(); Once you have SmsManager object, you can use sendDataMessage() method to send SMS at the specified mobile number as follows: smsManager.sendTextMessage("phoneNo", null, "SMS text", null, null); getDefault(): to get the default instance of the SmsManager sendTextMessage(String destinationAddress, String scAddress, String text, PendingIntent sentIntent, PendingIntent deliveryIntent)
  • 45. Using Built-in Intent to send SMS You can use Android Intent to send SMS by calling built-in SMS functionality of the Android. The following are the different Intent objects required to send an SMS. Intent Object - Action to send SMS:You will use ACTION_VIEW object to launch an SMS client installed on your Android device. Intent smsIntent = new Intent(Intent.ACTION_VIEW); Intent Object - Data/Type to send SMS :To send an SMS you need to specify smsto: as URI using setData() method and data type will be to vnd.android-dir/mms-sms using setType() method as follows: smsIntent.setData(Uri.parse("smsto:")); smsIntent.setType("vnd.android-dir/mms-sms"); Intent Object - Extra to send SMS Android has built-in support to add phone number and text message to send an SMS as follows: smsIntent.putExtra("address" , new String("0123456789;3393993300")); smsIntent.putExtra("sms_body" , "Test SMS to some one");
  • 46. Event Handling : Phone Call You can use Android Intent to make phone call by calling built-in Phone Call functionality of the Android. Intent Object - Action to make Phone Call :You will use ACTION_CALL object to trigger built-in phone call functionality available in Android device. Intent phoneIntent = new Intent(Intent.ACTION_CALL); You can use ACTION_DIAL object instead of ACTION_CALL Intent Object - Data/Type to make Phone Call :To make a phone call at a given number, you need to specify tel: as URI using setData() method as follows: setData(Uri.parse("tel:phoneNo"));
  • 47. Event Handling : Email Intent Object - Action to send Email : You will use ACTION_SEND object to launch an email client installed on your Android device. Intent emailIntent = new Intent(Intent.ACTION_SEND); Intent Object - Data/Type to send Email :To send an email you need to specify mailto: as URI using setData() method and data type will be to text/plain using setType() method as follows: emailIntent.setData(Uri.parse("mailto:")); emailIntent.setType("text/plain"); Intent Object - Extra to send Email :Android has built-in support to add TO, SUBJECT, CC, TEXT etc. fields which can be attached to the intent before sending the intent to a target email client. You can use following extra fields in your email: EXTRA_BCC EXTRA_CC
  • 48. Event Handling : Bluetooth Bluetooth is a way to send or receive data between two different devices. Android platform includes support for the Bluetooth framework that allows a device to wirelessly exchange data with other Bluetooth devices. Android provides Bluetooth API to perform these different operations. 1. Scan for other Bluetooth devices 2. Get a list of paired devices 3. Connect to other devices through service discovery
  • 49. Event Handling :Bluetooth Android provides BluetoothAdapter class to communicate with Bluetooth. Create an object of BluetoothAdapter by calling the static method getDefaultAdapter(). private BluetoothAdapter BA; BA = BluetoothAdapter.getDefaultAdapter(); In order to enable the Bluetooth of your device, call the intent with the following Bluetooth constant ACTION_REQUEST_ENABLE Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(turnOn, 0);
  • 50. Event Handling :Bluetooth Apart from the above constant , ther are other constanst provided the API , that supports differnet tasks. ACTION_REQUEST_DISCOVERABLE: This constant is used for turn on discovering of bluetooth ACTION_STATE_CHANGED: This constant will notify that Bluetooth state has been changed ACTION_FOUND: This constant is used for receiving information about each device that is discovered Once you enable the Bluetooth , you can get a list of paired devices by calling getBondedDevices() method. It returns a set of bluetooth devices. private Set<BluetoothDevice>pairedDevices; pairedDevices = BA.getBondedDevices();
  • 51. Event Handling : Bluetooth There are other methods in the API that gives more control over Bluetooth. enable(): This method enables the adapter if not enabled isEnabled() :This method returns true if adapter is enabled disable():This method disables the adapter getName():This method returns the name of the Bluetooth adapter setName(String name) This method changes the Bluetooth name getState() :This method returns the current state of the Bluetooth Adapter. startDiscovery(): This method starts the discovery process of the Bluetooth for 120 seconds.
  • 52. Event Handling :Camera There are 2 basic ways to implement camera in your android application. 1. Using existing android camera in your device 2. Directly using Camera API provided by android architecture
  • 53. Event Handling :Camera Using existing android camera in your device MediaStore.ACTION_IMAGE_CAPTURE is used to launch an existing camera application installed on your phone. Syntax: Additional intents provided by MediaStore ACTION_VIDEO_CAPTURE : It calls the existing video application in android to capture video EXTRA_SCREEN_ORIENTATION : It is used to set the orientation of the screen to vertical or landscape EXTRA_FULL_SCREEN : It is used to control the user interface of the ViewImage INTENT_ACTION_VIDEO_CAMERA: This intent is used to launch the camea in the video mode EXTRA_SIZE_LIMIT : It is used to specify the size limit of video or image capture size startActivityForResult() is used to launch the intent and wait for its result. Syntax:
  • 54. Event Handling :Camera Directly using Camera API provided by android architecture. Camera.open is used to intialize the camera object using the static method provide by the API. Syntax: Additional methods provide by the Camera class getCameraInfo(int cameraId, Camera.CameraInfo cameraInfo) : It returns the information about a particular camera getNumberOfCameras() : It returns an integer number defining of cameras availaible on device lock() : It is used to lock the camera , so no other application can access it release() : It is used to release the lock on camera , so other applications can access it open(int cameraId) : It is used to open particular camera when multiple cameras are supported enableShutterSound(boolean enabled) : It is used to enable/disable default shutter sound of image capture
  • 55. Event Handling : MediaPlayer Android is providing MediaPlayer class to access built-in mediaplayer services for playing audio,video. A static Method create() is used to launch MediaPlayer object Syntax: Once you have created the Mediaplayer object you can call some methods to start or stop the music. mediaPlayer.start();  mediaPlayer.pause(); On call to start() method, the music will start playing from the begininning. If this method is called again after the pause() method , the music would start playing from where it is left and not from the beginning. In order to start music from the beginning , you have to call reset() method. Syntax:
  • 56. Event Handling : MediaPlayer Additional methods provided by MediaPlayer isPlaying(): This method just returns true/false indicating the song is playing or not seekTo(positon): This method takes an integer, and move song to that particular second getCurrentDuration(): This method returns the current position of song in milliseconds getDuration() : This method returns the total time duration of song in milliseconds
  • 57. Event Handling :Audio recorder Android has a built in microphone through which you can capture audio and store it , or play it in your phone. Android provides MediaRecorder class to record audio or video. In order to use MediaRecorder class ,you will first create an instance of MediaRecorder class. Syntax: Now you will set the source , output and encoding format and output file. Their syntax is given below.
  • 58. Event Handling :Audio recorder After specifying the audio source, format and its output file, you can then call the two basic methods to perpare and start recording. Additional methods provided by MediaRecorder class setAudioSource(): This method specifies the source of audio to be recorded setVideoSource() : This method specifies the source of video to be recorded setOutputFormat() : This method specifies the audio format in which audio to be stored setAudioEncoder() :This method specifies the audio encoder to be used  setOutputFile(): This method configures the path to the file into which the recorded audio is to be stored stop(): This method stops the recording process.
  翻译: