0% found this document useful (0 votes)
14 views165 pages

Chapter-2 2

Uploaded by

samarthkumarpro
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views165 pages

Chapter-2 2

Uploaded by

samarthkumarpro
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 165

UNIVERSITY INSTITUTE OF

COMPUTING
Mobile Application Development.
CAH-655

Prepared By: Shefali Parihar

DISCOVER . LEARN .
EMPOWER
Importance
• Understanding different User Interface Controls.

• How Events can be handled?

• How to control style and themes in android.

• How mapping of .xml and .java works.

• To understand the need of Fragments.

• How Embedded Database used in android application.

11/28/2024
2
Topic Objectives
• To work with different User Interface Controls.

• To work with events on different UI controls.

• To implement programs based on intents and UI controls


together.
• To understand the need of findViewById.

• To work with Fragments and Database.

• To deploy android project.

11/28/2024
3
1.2 Layouts and resources for the UI

4
Contents
● Views, view groups, and view hierarchy
● The layout editor and ConstraintLayout
● Event handling
● Resources and measurements

5
Views

6
Everything you see is a view
If you look at your mobile device,
every user interface element that you see is
a View.

Views

7
What is a view?
View subclasses are basic user interface building blocks
● Display text (TextView class), edit text (EditText class)
● Buttons (Button class), menus, other controls
● Scrollable (ScrollView, RecyclerView)
● Show images (ImageView)
● Group views (ConstraintLayout and LinearLayout)

8
Examples of view subclasses

Button CheckBox

EditText RadioButton

Slider Switch

9
View attributes
● Color, dimensions, positioning
● May have focus (e.g., selected to receive user input)
● May be interactive (respond to user clicks)
● May be visible or not
● Relationships to other views

10
Create views and layouts

● Android Studio layout editor: visual representation of XML


● XML editor
● Java code

11
Android Studio layout editor
1. XML layout file
2. Design and Text tabs
3. Palette pane
4. Component Tree
5. Design and blueprint
panes
6. Attributes tab

12
View defined in XML
<TextView
android:id="@+id/show_count"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/myBackgroundColor"
android:text="@string/count_initial_value"
android:textColor="@color/colorPrimary"
android:textSize="@dimen/count_text_size"
android:textStyle="bold"
/>
13
View attributes in XML
android:<property_name>="<property_value>"
Example: android:layout_width="match_parent"

android:<property_name>="@<resource_type>/resource_id"
Example: android:text="@string/button_label_next"

android:<property_name>="@+id/view_id"
Example: android:id="@+id/show_count"

14
Create View in Java code
context
In an Activity:

TextView myText = new TextView(this);


myText.setText("Display this text!");

15
What is the context?
● Context is an interface to global information about an
application environment
● Get the context:
Context context = getApplicationContext();
● An Activity is its own context:
TextView myText = new TextView(this);

16
Custom views
● Over 100 (!) different types of views available from the Android
system, all children of the View class
● If necessary, create custom views by subclassing existing views
or the View class

17
ViewGroup and
View hierarchy

18
ViewGroup contains "child" views
● ConstraintLayout: Positions UI elements using constraint
connections to other elements and to the layout edges
● ScrollView: Contains one element and enables scrolling
● RecyclerView: Contains a list of elements and enables
scrolling by adding and removing elements dynamically

19
ViewGroups for layouts

Layouts
● are specific types of ViewGroups (subclasses of ViewGroup
)
● contain child views
● can be in a row, column, grid, table, absolute

20
Common Layout Classes

LinearLayout ConstraintLayo GridLayou TableLayout


ut t

21
Common Layout Classes
● ConstraintLayout: Connect views with constraints
● LinearLayout: Horizontal or vertical row
● RelativeLayout: Child views relative to each other
● TableLayout: Rows and columns
● FrameLayout: Shows one child of a stack of children

22
Class hierarchy vs. layout hierarchy
● View class-hierarchy is standard object-oriented class
inheritance
○ For example, Button is-a TextView is-a View is-an Object
○ Superclass-subclass relationship

● Layout hierarchy is how views are visually arranged


○ For example, LinearLayout can contain Buttons arranged in a row
○ Parent-child relationship

23
Hierarchy of viewgroups and views

ViewGroup Root view is always a ViewGroup

ViewGroup View View

View View View

24
View hierarchy and screen layout

25
View hierarchy in the layout editor

26
Layout created in XML
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
... />
<TextView
... />
<Button
... />
</LinearLayout
27
Layout created in Java Activity code
LinearLayout linearL = new LinearLayout(this);
linearL.setOrientation(LinearLayout.VERTICAL);

TextView myText = new TextView(this);


myText.setText("Display this text!");

linearL.addView(myText);
setContentView(linearL);

28
Set width and height in Java code
Set the width and height of a view:
LinearLayout.LayoutParams layoutParams =
new Linear.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_CONTENT);
myView.setLayoutParams(layoutParams);

29
Best practices for view hierarchies
● Arrangement of view hierarchy affects app
performance
● Use smallest number of simplest views possible
● Keep the hierarchy flat—limit nesting of views and
view groups

30
The layout
editor and
Constraint
Layout

31
The layout editor with ConstraintLayout

● Connect UI elements to parent layout


● Resize and position elements
● Align elements to others
● Adjust margins and dimensions
● Change attributes

32
What is ConstraintLayout?

● Default layout for new Android Studio project


● ViewGroup that offers flexibility for layout design
● Provides constraints to determine positions and alignment of UI
elements
● Constraint is a connection to another view, parent layout, or
invisible guideline

33
Layout editor main toolbar

1. Select Design Surface: Design and Blueprint panes


2. Orientation in Editor: Portrait and Landscape
3. Device in Editor: Choose device for preview
4. API Version in Editor: Choose API for preview
5. Theme in Editor: Choose theme for preview
6. Locale in Editor: Choose language/locale for preview

34
ConstraintLayout toolbar in layout editor

1. Show: Show Constraints and Show Margins


2. Autoconnect: Enable or disable
3. Clear All Constraints: Clear all constraints in layout
4. Infer Constraints: Create constraints by inference
5. Default Margins: Set default margins
6. Pack: Pack or expand selected elements
7. Align: Align selected elements
8. Guidelines: Add vertical or horizontal guidelines
9. Zoom controls: Zoom in or out

35
Autoconnect

● Enable Autoconnect in
toolbar if disabled
● Drag element to any part of
a layout
● Autoconnect generates
constraints against parent
layout
36
ConstraintLayout handles

1. Resizing handle
2. Constraint line and
handle
3. Constraint handle
4. Baseline handle

37
Align elements by baseline
1. Click the baseline
constraint button
2. Drag from baseline to
other element's
baseline

38
Attributes pane
● Click the Attributes tab
● Attributes pane
includes:
○ Margin controls for
positioning
○ Attributes such as
layout_width

39
Attributes pane view inspector
1. Vertical view size control
specifies layout_height
2. Horizontal view size control
specifies layout_width
3. Attributes pane close button

40
Layout_width and layout_height
layout_width and layout_height change with size
controls
● match_constraint: Expands element to fill its
parent
● wrap_content: Shrinks element to enclose
content
● Fixed number of dp (density-independent
pixels)

41
Set attributes

To view and edit all attributes for element:


1. Click Attributes tab
2. Select element in design, blueprint, or Component Tree
3. Change most-used attributes
4. Click at top or View more attributes at bottom to see and
change more attributes

42
Set attributes example: TextView

43
Preview layouts

Preview layout with horizontal/vertical orientation:


1. Click Orientation in Editor button
2. Choose Switch to Landscape or Switch to Portrait
Preview layout with different devices:
3. Click Device in Editor button
4. Choose device

44
Create layout variant for landscape

1. Click Orientation in Editor button


2. Choose Create Landscape Variation
3. Layout variant created:
activity_main.xml (land)
4. Edit the layout variant as needed

45
Create layout variant for tablet

1. Click Orientation in Layout Editor


2. Choose Create layout x-large Variation
3. Layout variant created: activity_main.xml (xlarge)
4. Edit the layout variant as needed

46
Layouts

• Layout is the architecture for the user interface in an Activity


• Defines the layout structure and holds all the elements that appear to
the user
• express the view hierarchy
• layout is declared in two ways:
– Declare UI elements in XML
– Instantiate layout elements at runtime

• Each element in XML is either a View or ViewGroup object


• View objects are leaves in the tree
• ViewGroup objects are branches in the tree
• The name of an XML element is respective to the Java class that it
represents

47
Layout Example
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="…"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a TextView" />
<Button android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a Button" />
</LinearLayout>

48
Loading XML file

public void onCreate(Bundle savedInstanceState)


{
super.onCreate(savedInstanceState);
setContentView.(R.layout.main_layout);
}

49
Attributes

• Every View and ViewGroup object supports their own


variety of XML attributes
• Some attributes are specific to a View object , these
attributes are inherited by any View objects that extend
this class
• Some attributes are common to all View objects,
because they are inherited from the root View class
• Other attributes are considered "layout parameters"
that describe certain layout orientations of the View
object.
50
Id Attributes

• Any View object may have an integer ID


• uniquely identify the View within the tree
• the ID is typically assigned in the layout XML file as a
string
• This attribute is common to all View objects.

android:id="@+id/my_button"

51
Layout Managers

• It is a containers for views.


• manage the size and position of its children
– LinearLayout Organizes horizontally or vertically.
– TableLayout Organizes in tabular form
– RelativeLayout Organizes its children relative to one another
or to the parent
– AbsoluteLayout Positions based on exact coordinates
– FrameLayout Allows to dynamically change the control(s) in
the layout

52
Linear Layout

• manager organizes its children either


horizontally or vertically based on the value of
the orientation property
<LinearLayout xmlns:android=“…"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">

<!-- add children here-->

</LinearLayout>
53
Table Layout

• extension of LinearLayout
• This layout structures its child controls into
rows and columns
<TableLayout xmlns:android=“…"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TableRow>
<TextView … />
<EditText … />
</TableRow>
<TextView … />
<EditText … />
</TableRow>
</TableLayout>

54
Table Layout

• implements a policy where


the controls in the container
are laid out relative to
either the container or
another control in the
container.

55
Table Layout
<RelativeLayout xmlns:android=“…"
<TextView android:id="@+id/userNameLbl"
android:layout_alignParentTop="true" />
<EditText android:id="@+id/userNameText"
android:layout_below="@id/userNameLbl" />
<TextView android:id="@+id/pwdLbl"
android:layout_below="@id/userNameText" />
<EditText android:id="@+id/pwdText"
android:layout_below="@id/pwdLbl"/>
<TextView android:id="@+id/pwdHintLbl"
android:layout_below="@id/pwdText"/>
<TextView android:id="@+id/disclaimerLbl"
android:layout_alignParentBottom="true" />
</RelativeLayout>

56
Absolute Layout

• A portion of the user interface in an Activity.

Practically, a Fragment is a modular section of an Activity.

DESIGN PHILOSOPHY:

- Structure an Activity as a collection of Fragments.

- Reuse a Fragment on different Activities …

57
Input Controls
• Input controls are the interactive components in your app's
user interface.
• Android provides a wide variety of controls you can use in
your UI, such as buttons, text fields, seek bars, check box,
zoom buttons, toggle buttons, and many more.

58
Features of Android

Sr.No. UI Control & Description


TextView
1
This control is used to display text to the user.
EditText
2 EditText is a predefined subclass of TextView that includes rich
editing capabilities.
Button
3 A push-button that can be pressed, or clicked, by the user to
perform an action.
ImageButton
An ImageButton is an AbsoluteLayout which enables you to
4
specify the exact location of its children. This shows a button
with an image (instead of text) that can be pressed or clicked

59
Features of Android

Sr.No. UI Control & Description


CheckBox
5 An on/off switch that can be toggled by the user. You should use check box when
presenting users with a group of selectable options that are not mutually exclusive.
ToggleButton
6
An on/off button with a light indicator.
RadioButton
7
The RadioButton has two states: either checked or unchecked.
ProgressBar
8 The ProgressBar view provides visual feedback about some ongoing tasks, such as when
you are performing a task in the background.
Spinner
9
A drop-down list that allows users to select one value from a set.
TimePicker
10 The TimePicker view enables users to select a time of the day, in either 24-hour mode or
AM/PM mode.

60
TextView UI

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:orientation="vertical" >

<TextView android:id="@+id/text_id"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text=“Hello world!" />

</LinearLayout>

61
EditText UI

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:orientation="vertical" >

<EditText

android:layout_width="fill_parent"

android:layout_height="50dp"

android:layout_below="@+id/editInp"

android:id="@+id/editDig“ />

</LinearLayout>
62
Button UI

<Button

android:id="@+id/button"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_below="@+id/editText2"

android:layout_centerHorizontal="true"

android:layout_marginTop="109dp"

android:text="ADD"

tools:layout_editor_absoluteX="148dp"

tools:layout_editor_absoluteY="266dp" />

63
RadioButton UI
<RadioButton

android:id="@+id/radioButton1"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text=“Male"

android:layout_marginTop="20dp" />

<RadioButton

android:id="@+id/radioButton2"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text=“Female" />

64
CheckBox UI
<CheckBox

android:id="@+id/checkBox"

android:layout_width="wrap_content"

android:layout_height="wrap_content“

android:checked="true"

android:text="Dog" />

<CheckBox

android:id="@+id/checkBox2"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Cat" />

65
Spinner UI
<Spinner

android:id="@+id/spinner"

android:layout_width="149dp"

android:layout_height="40dp"

android:layout_marginBottom="8dp"

android:layout_marginEnd="8dp"

android:layout_marginStart="8dp" />

66
Dimension

• You could specify the dimensions in any of the


following units:
– px: Pixels
– in: Inches
– mm: Millimeters
– pt: Points
– dp: Density-independent pixels based on a 160-dpi
(pixel density per inch) screen (dimensions adjust
to screen density)
– sp: Scale-independent pixels (dimensions that
allow for user sizing; helpful for use in67 fonts)
What is an intent?
An Intent is a description of an operation to be performed.
An Intent is an object used to request an action from another
app component via the Android system.

Originator App component

Intent Action
Android
System

68
What can intents do?
● Start an Activity
○ A button click starts a new Activity for text entry
○ Clicking Share opens an app that allows you to post a photo

● Start an Service
○ Initiate downloading a file in the background

● Deliver Broadcast
○ The system informs everybody that the phone is now charging

69
Explicit and implicit intents
Explicit Intent
● Starts a specific Activity
○ Request tea with milk delivered by Nikita
○ Main activity starts the ViewShoppingCart Activity
Implicit Intent
● Asks system to find an Activity that can handle this request
○ Find an open store that sells green tea
○ Clicking Share opens a chooser with a list of apps

70
Starting
Activities

71
Start an Activity with an explicit intent
To start a specific Activity, use an explicit Intent
1. Create an Intent
○ Intent intent = new Intent(this, ActivityName.class);

2. Use the Intent to start the Activity


○ startActivity(intent);

72
Start an Activity with implicit intent
To ask Android to find an Activity to handle your request, use
an implicit Intent
1. Create an Intent
○ Intent intent = new Intent(action, uri);

2. Use the Intent to start the Activity


○ startActivity(intent);

73
Implicit Intents - Examples
Show a web page
Uri uri = Uri.parse("http://www.google.com");

Intent it = new
Intent(Intent.ACTION_VIEW,uri);
startActivity(it);
Dial a phone number
Uri uri = Uri.parse("tel:8005551234");
Intent it = new Intent(Intent.ACTION_DIAL, 74
How Activities Run
● All Activity instances are managed by the Android runtime
● Started by an "Intent", a message to the Android runtime to run an
activity

User clicks MainActivity FoodListActivity OrderActivity


launcher icon What do you want to do? Choose food items...Next Place order

Intent: Start Start Intent: Start Intent: Start finish


app Android Android choose food order Android order activity
System
main Shop System System
activity activity

75
Sending and
Receiving Data

76
Two types of sending data with intents
● Data—one piece of information whose data location can
be represented by an URI

● Extras—one or more pieces of information as a collection


of key-value pairs in a Bundle

77
Sending and retrieving data
In the first (sending) Activity:
1. Create the Intent object
2. Put data or extras into that Intent
3. Start the new Activity with startActivity()

In the second (receiving) Activity:


4. Get the Intent object, the Activity was started with
5. Retrieve the data or extras from the Intent object

78
Putting a URI as intent data
// A web page URL
intent.setData(
Uri.parse("http://www.google.com"));

// a Sample file URI


intent.setData(
Uri.fromFile(new
File("/sdcard/sample.jpg")));
79
Put information into intent extras
● putExtra(String name, int value)
⇒ intent.putExtra("level", 406);
● putExtra(String name, String[] value)
⇒ String[] foodList = {"Rice", "Beans",
"Fruit"};
intent.putExtra("food", foodList);
● putExtras(bundle);
⇒ if lots of data, first create a bundle and pass the bundle.
● See documentation for all 80
Sending data to an activity with extras
public static final String EXTRA_MESSAGE_KEY =

"com.example.android.twoactivities.extra.MESSAGE"
;

Intent intent = new Intent(this,


SecondActivity.class);
String message = "Hello Activity!";
intent.putExtra(EXTRA_MESSAGE_KEY, message);
startActivity(intent); 81
Get data from intents
● getData();
⇒ Uri locationUri = intent.getData();
● int getIntExtra (String name, int
defaultValue)
⇒ int level = intent.getIntExtra("level", 0);
● Bundle bundle = intent.getExtras();
⇒ Get all the data at once as a bundle.
● See documentation for all
82
Returning data to the starting activity
1. Use startActivityForResult() to start the second Activity
2. To return data from the second Activity:
● Create a new Intent
● Put the response data in the Intent using putExtra()
● Set the result to Activity.RESULT_OK
or RESULT_CANCELED, if the user cancelled out
● call finish() to close the Activity
1. Implement onActivityResult() in first Activity

83
startActivityForResult()
startActivityForResult(intent, requestCode);
● Starts Activity (intent), assigns it identifier (requestCode)
● Returns data via Intent extras
● When done, pop stack, return to previous Activity, and execute
onActivityResult() callback to process returned data
● Use requestCode to identify which Activity has "returned"

84
1. startActivityForResult() Example

public static final int CHOOSE_FOOD_REQUEST = 1;

Intent intent = new Intent(this,


ChooseFoodItemsActivity.class);
startActivityForResult(intent, CHOOSE_FOOD_REQUEST);

85
2. Return data and finish second activity
// Create an intent
Intent replyIntent = new Intent();

// Put the data to return into the extra


replyIntent.putExtra(EXTRA_REPLY, reply);

// Set the activity's result to RESULT_OK


setResult(RESULT_OK, replyIntent);

// Finish the current activity


finish();

86
3. Implement onActivityResult()
public void onActivityResult(int requestCode,
int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == TEXT_REQUEST) { // Identify activity
if (resultCode == RESULT_OK) { // Activity succeeded
String reply =
data.getStringExtra(SecondActivity.EXTRA_REPLY);
// … do something with the data
}}}

87
Contents

● Intent—recap
● Implicit Intent overview
● Sending an implicit Intent
● Receiving an implicit Intent

88
Implicit Intent
overview

89
What you do with an implicit Intent

● Start an Activity in another app by describing an action you


intend to perform, such as "share an article", "view a map", or
"take a picture"
● Specify an action and optionally provide data with which to
perform the action
● Don't specify the target Activity class, just the intended action

90
What system does with implicit Intent
● Android runtime matches the implicit intent request with
registered intent handlers
● If there are multiple matches, an App Chooser will open to let
the user decide

91
How does implicit Intent work?
1. The Android Runtime keeps a list of registered Apps
2. Apps have to register via AndroidManifest.xml
3. Runtime receives the request and looks for matches
4. Android runtime uses Intent filters for matching
5. If more than one match, shows a list of possible matches and
lets the user choose one
6. Android runtime starts the requested activity

92
App Chooser

When the Android runtime finds


multiple registered activities that
can handle an implicit Intent, it
displays an App Chooser to allow
the user to select the handler

93
Sending an
implicit Intent

94
Sending an implicit Intent
1. Create an Intent for an action
Intent intent = new Intent(Intent.ACTION_CALL_BUTTON);

User has pressed Call button — start Activity that


can make a call (no data is passed in or returned)

2. Start the Activity


if (intent.resolveActivity(getPackageManager()) != null)
{
startActivity(intent);
} 95
Avoid exceptions and crashes
Before starting an implicit Activity, use the package
manager to check that there is a package with an
Activity that matches the given criteria.

Intent myIntent = new Intent(Intent.ACTION_CALL_BUTTON);

if (intent.resolveActivity(getPackageManager()) !=
null) {
startActivity(intent);
}
96
Sending an implicit Intent with data URI
1. Create an Intent for action
Intent intent = new Intent(Intent.ACTION_DIAL);

2. Provide data as a URI


intent.setData(Uri.parse("tel:8005551234"));

3. Start the Activity


if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
97
Providing the data as URI

Create an URI from a string using Uri.parse(String


uri)

● Uri.parse("tel:8005551234")
● Uri.parse("geo:0,0?q=brooklyn%20bridge%2C%20brooklyn%2C
%20ny")
● Uri.parse("http://www.android.com");

Uri documentation
98
Implicit Intent examples
Show a web page
Uri uri = Uri.parse("http://www.google.com");

Intent it = new
Intent(Intent.ACTION_VIEW,uri);
startActivity(it);
Dial a phone number
Uri uri = Uri.parse("tel:8005551234");
Intent it = new Intent(Intent.ACTION_DIAL, 99
Sending an implicit Intent with extras
1. Create an Intent for an action
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);

2. Put extras
String query = edittext.getText().toString();
intent.putExtra(SearchManager.QUERY, query));

3. Start the Activity


if (intent.resolveActivity(getPackageManager()) != null)
{
startActivity(intent);
} 100
Category
Additional information about the kind of component
to handle the intent.
● CATEGORY_OPENABLE
Only allow URIs of files that are openable
● CATEGORY_BROWSABLE
Only an Activity that can start a web browser to
display data referenced by the URI

101
Sending an implicit Intent with type and
category
1. Create an Intent for an action
Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);

2. Set mime type and category for additional


information
intent.setType("application/pdf"); // set MIME type
intent.addCategory(Intent.CATEGORY_OPENABLE);

continued on next slide...


102
Sending an implicit Intent with type and
category
3. Start the Activity
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(myIntent,ACTIVITY_REQUEST_CREATE_F
ILE);
}

4. Process returned content URI in onActivityResult()

103
Common actions for an implicit Intent
Common actions include:
● ACTION_SET_ALARM
● ACTION_IMAGE_CAPTURE
● ACTION_CREATE_DOCUMENT
● ACTION_SENDTO
● and many more

104
Apps that handle common actions
Common actions are usually handled by installed
apps (both system apps and other apps), such as:

● Alarm Clock, Calendar, Camera, Contacts➔ List of commo


● Email, File Storage, Maps, Music/Video n actions for a
n implicit inten
● Notes, Phone, Search, Settings t

● Text Messaging and Web Browsing ➔ List of all avail


able actions

105
Receiving an
Implicit Intent

106
Register your app to receive an Intent
● Declare one or more Intent filters for the Activity in
AndroidManifest.xml
● Filter announces ability of Activity to accept an implicit Intent
● Filter puts conditions on the Intent that the Activity accepts

107
Intent filter in AndroidManifest.xml
<activity android:name="ShareActivity">
<intent-filter>
<action android:name="android.intent.action.SEND"/>
<category
android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="text/plain"/>
</intent-filter>
</activity>

108
Intent filters: action and category

● action — Match one or more action constants


○ android.intent.action.VIEW — matches any Intent with
ACTION_VIEW
○ android.intent.action.SEND — matches any Intent with
ACTION_SEND

● category — additional information (list of categories)


○ android.intent.category.BROWSABLE—can be started by web
browser
109
○ android.intent.category.LAUNCHER—Show activity as launcher
Intent filters: data

● data — Filter on data URIs, MIME type


○ android:scheme="https"—require URIs to be https protocol
○ android:host="developer.android.com"—only accept an Intent
from specified hosts
○ android:mimeType="text/plain"—limit the acceptable types of
documents

110
An Activity can have multiple filters
<activity android:name="ShareActivity">
<intent-filter>
<action android:name="android.intent.action.SEND"/>
...
</intent-filter>
<intent-filter>
<action
android:name="android.intent.action.SEND_MULTIPLE"/>
...
</intent-filter> An Activity can have several
</activity> filters 111
A filter can have multiple actions & data
<intent-filter>
<action android:name="android.intent.action.SEND"/>
<action
android:name="android.intent.action.SEND_MULTIPLE"/>
<category
android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="image/*"/>
<data android:mimeType="video/*"/>
</intent-filter>
112
Intent Types

113
Service and
Service Life
Cycle
114
Service

• One of the major components of Android.

• Used to perform long running tasks.

• E.g. download a large file

• Don’t have UI

• Implement by extending Service class.


Start and Stop Service

Fig. Start and Stop a Service


Service

• A service is a application component that can perform long


running operations in the background and does not provide any
user interface.
What are Services good for

• Network Transactions

• Play Music

• Perform File I/O

• Interact with Content Provider


Characteristics of Services

• Started with Intent

• Can stay running when user switch applications

• Lifecycle – which you must manage

• Other apps can use the service – manage permissions

• Runs in the main thread of its hosting process.


Forms of Service: Started
Started
startService()
startService() Service
• Started with startService()
onCreate()
onCreate()

• Runs indefinitely until it stops itself


onStart()
onStart()

• Usually does not update the UI Service


Service is
is running
running

stopService()
stopService()

onDestroy()
onDestroy()

Service
Servicefinished
finished
Fig. Started Service Lifecycle
Forms of Service: Bound
bindService()
Bounded
startService()
• Offers client-server interface that Service
onCreate()
onCreate()
allows components to interact with
onBind()
onStart()
the service
Service
Service is
is running
running onRebind()
• Client send requests and get results
onUnbind()
stopService()
• Started with bindService( )
onDestroy()
onDestroy()
• Ends when all clients end
Service
Servicefinished
finished

Fig. Bounded Service Lifecycle


Services and Threads

• Although services are separate from the UI, they still run on the
main thread by default. (except IntentService)
• Offload CPU-intensive work to a separate thread within the
service.
Updating the App

• If the service can’t access the UI, how do you update the app to
show the result?
• Use a broadcast receiver.
Foreground Services

• Runs in the background but requires that the user is actively


aware that it exists. E.g.: music player using music service.
– Higher priority than background services since user will notice its absence –
unlike to be killed by the system.
– Must provide a notification which the user can not dismiss; while the
service is running.
Creating a Service

• <service android:name=".ExampleService" />


• Manage permissions

• Subclass IntentService and Service class

• Implement lifecycle methods

• Start service from activity

• Make sure service is stoppable


Stopping a Service

• A started service must manage its own lifecycle


• If not stopped, will keep running and consuming resources

• The service must stop itself by calling stopSelf()

• Another component can stop it by calling stopService()

• Bound Service is destroyed when all clients unbound

• Intent Service is destroyed after onHandleIntent() returns


IntentService

• Simple service with simplified lifecycle


• Uses worker thread to fulfill requests

• Stop itself when done

• Ideal for one long task on a single background thread


IntentService Limitations

• Can not interact with the UI


• Can only run one request at a time

• Can not be interrupted


IntentService
Implementation
public class HelloIntentService extends IntentService{

public HelloIntentService() { super("HelloIntentService"); }

@override

protected void onHandleIntenet(Intent intent){

try{

// Do some work

} catch(InterruptedException e){ Thread.currentThread().interrupt(); }

} //When this method returns, IntentService stops the Service

}
Services

• Services execute background processing, no visual


interface
Ex: Downloads, Playing Music, TCP/UDP Server
• You can bind to an existing service, control its operation,
and run in background, play music, alarm clock, etc.
• Secured if using permissions.
• Callers may need to verify that service is the correct
one.
• Does not have a visual interface.

130
Content
Provider

131
Content

• Content Provider

• Content Resolver

• Implementation of Content Provider


Content Provider

• Content providers are data storage facilities which


supports data exchange between applications
• Make data available to other applications
• Transfer data between applications in Android
• Other applications use a ContentResolver object to
access the data provided via a ContentProvider.

133
Content Provider

• One of the fundamental components of Android

• Share the data between two applications

• Allows you to fetch the data that app requests from a repository

• Access the data with abstraction

• A content resolver is a component that you app uses to send


requests to a content provider.
Content Provider

• Content Resolver request to content provider by some content


which consist of a content URI and SQL like query
• The ContentResolver object provides query(), insert(), update()
and delete() methods
How they work together

Activity / Adapter • Activity/Adapter uses ContentResolver


Content Resolver
to query Content Provider

• ContentProvider gets data


Content Provider
• ContentResolver returns data as cursor.

Data • Activity/Adapter uses data


What it is good for?

• Securely make data available to other apps

• Manage access permissions to app data

• Store data or develop backend independently from UI

• Standardized way of accessing data

• Required to work with Cursor Loaders


Many apps can use one
content provider
App that sells Red Hats
App that manage Hats inventory Content Resolver
Get Red Hats
Content Resolver

Hat Store Content Provider


App that sells Fancy Hats
Content Resolver
Data Get Fancy Hats

Fig. Many apps using one content provider


Components of Content
Provider

Let’s look at each of these

Fig. components of content provider


Data Repository

• Data, commonly in SQLite


Database but can be any backend

• OpenHelper if you use SQLite


database

Fig. Data Repository


Contract

• Public class that exposes the


information about the content
provider to other apps
• Contract Specifies
• URIs
• Table Structure
• MIME type of returned data
• Constants Fig. Contract
Content Provider

• Public secure interface


• Permissions control access
• Subclass of ContentProvider
• query(), insert(), delete(), update()
API

Fig. Content Provider


Content Resolver

• Send requests to content provider


and return result

Fig. Content Resolver


Implementation of Content
Provider
• Data- commonly a SQLite database
• Write contract- Information about the content provider
• Subclass ContentProvider and implement methods
• Get data using ContentResolver
• Set permissions in Android Manifest
Broadcast Receivers

• Broadcast receivers act as mailboxes for messages from


other applications. It receives and reacts to broadcast
announcements
• If an app registered the receiver in adv., the event will
notify and call back the registered software
• Ex: Low battery, power connected, shutdown, time zone
changed, etc.
• Broadcast receivers also act as receivers for multiple
components.

145
Broadcast Receivers
Implementation
• A receiver can be registered via the AndroidManifest.xml
file.
• Alternatively to this static registration, you can also register
a receiver dynamically via the Context.registerReceiver()
method.
• The implementing class for a receiver extends the
BroadcastReceiver class.
• If the event for which the broadcast receiver has registered
happens, the onReceive() method of the receiver is called
by the Android system.
146
Broadcast
Intents
Broadcast vs. Activity

• Use implicit intents to send broadcasts or start activities

Sending broadcasts Starting activities


● Use sendBroadcast() ● Use startActivity()
● Can be received by any application ● Find a single activity to
registered for the intent accomplish a task
● Used to notify all apps of an event ● Accomplish a specific action
What is a broadcast
receiver?
• Listens for incoming intents sent by sendBroadcast()
– In the background

• Intents can be sent


– By the system, when an event occurs that might change the behavior of an
app
– By another application, including your own
Broadcast receiver always
responds
• Responds even when your app is closed

• Independent from any activity

• When a broadcast intent is received and delivered to


onReceive(), it has 5 seconds to execute, and then the receiver
is destroyed
System broadcasts

• Automatically delivered when certain events occur

• After the system completes a boot

android.intent.action.BOOT_COMPLETED
• When the wifi state changes

android.net.wifi.WIFI_STATE_CHANGED
Custom broadcasts

• Deliver any custom intent as a broadcast

sendBroadcast() method—asynchronous

sendOrderedBroadcast()—synchronously

android.example.com.CUSTOM_ACTION
Implementing Broadcast
Receivers
• Subclass BroadcastReceiver
• Implement onReceive() method
• Register to receive broadcast
• Statically, in AndroidManifest
• Dynamically, with registerReceiver()
File > New > Other >
BroadcastReceiver
public class CustomReceiver extends BroadcastReceiver {
public CustomReceiver() {
}

@Override
public void onReceive(Context context, Intent intent)
{
// TODO: This method is called when the
BroadcastReceiver
// is receiving an Intent broadcast.
throw new UnsupportedOperationException("Not yet
implemented");
}
Register in Manifest

● <receiver> element inside <application>


● <intent-filter> registers receiver for specific intents

<receiver
android:name=".CustomReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action
android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
Available Intents

● ACTION_TIME_TICK ● ACTION_PACKAGE_DATA_CLEARED
● ACTION_TIME_CHANGED ● ACTION_PACKAGES_SUSPENDED
● ACTION_TIMEZONE_CHANGED ● ACTION_PACKAGES_UNSUSPENDED
● ACTION_BOOT_COMPLETED ● ACTION_UID_REMOVED
● ACTION_PACKAGE_ADDED ● ACTION_BATTERY_CHANGED
● ACTION_PACKAGE_CHANGED ● ACTION_POWER_CONNECTED
● ACTION_PACKAGE_REMOVED ● ACTION_POWER_DISCONNECTED
● ACTION_PACKAGE_RESTARTED ● ACTION_SHUTDOWN
Custom Broadcast
● Sender and receiver must agree on unique name for intent (action
name)
● Define in activity and broadcast receiver

private static final String


ACTION_CUSTOM_BROADCAST =

"com.example.android.powerreceiver.ACTION_CUSTOM_
BROADCAST";
Send Custom Broadcast

Intent customBroadcastIntent =
new Intent(ACTION_CUSTOM_BROADCAST);

LocalBroadcastManager.getInstance(this)
.sendBroadcast(customBroadcastIntent);
Destroy

@Override
protected void onDestroy() {
LocalBroadcastManager.getInstance(this)
.unregisterReceiver(mReceiver);
super.onDestroy();
}
Implement onReceive()

@Override
public void onReceive(Context context, Intent intent) {
String intentAction = intent.getAction();
switch (intentAction){
case Intent.ACTION_POWER_CONNECTED:
break;
case Intent.ACTION_POWER_DISCONNECTED:
break;
}
}
References

• https://www.youtube.com/watch?v=XXVsL3njoCQ
• https://codelabs.developers.google.com/codelabs/android-training-
broadcast-receivers/index.html?index=..%2F..android-training#1
• https://www.tutorialspoint.com/android/android_broadcast_receivers.htm
References

• https://www.youtube.com/watch?v=ROk-
YrZKYCg&list=PLlyCyjh2pUe9wv-hU4my-
Nen_SvXIzxGB&index=46&t=0s
• https://developer.android.com/guide/components/fundamentals
• https://developer.android.com/courses/fundamentals-training/overview-v2
• https://www.tutorialspoint.com/
References

• https://www.youtube.com/watch?v=fNVMqACYPnQ&t=3s
• https://developer.android.com/guide/topics/providers/content-providers
• https://www.tutorialspoint.com/android/android_content_providers.htm
BIBLIOGRAPHY

Text Books-
• Android Programming for Beginners by John Horton
• Reto Meier, “Profesional Android 4 Aplication Development” ,
John Wiley& Sons, Inc, 2012.

Reference Material-
• Zigurd Mednieks, Laird Dornin, Blake Meike G, and Masumi
Nakamura, “Programming Android”, O’Reily boks

11/28/2024 164
Thank You

11/28/2024
165

You might also like