0% found this document useful (0 votes)
2 views

Android Menu

The document provides an overview of Android navigation components, including the Navigation graph, NavHost, and NavController, which facilitate user navigation within apps. It also discusses RecyclerView for efficiently displaying large datasets and outlines the implementation of styles and themes in Android to enhance UI consistency and reduce code duplication. Key concepts include back-button navigation, hierarchical navigation patterns, and the creation and application of styles through XML resource files.

Uploaded by

nayanbiradar14
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Android Menu

The document provides an overview of Android navigation components, including the Navigation graph, NavHost, and NavController, which facilitate user navigation within apps. It also discusses RecyclerView for efficiently displaying large datasets and outlines the implementation of styles and themes in Android to enhance UI consistency and reduce code duplication. Key concepts include back-button navigation, hierarchical navigation patterns, and the creation and application of styles through XML resource files.

Uploaded by

nayanbiradar14
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

Android Options Menu

Program for Android Options Menu


Program for Android Popup Menu
Program for Android Context Menu
Screen Navigation

Navigation

Navigation refers to the interactions that allow users to navigate across, into, and back out
from the different pieces of content within your app. Android Jetpack's Navigation
component helps you implement navigation, from simple button clicks to more complex
patterns, such as app bars and the navigation drawer. The Navigation component also
ensures a consistent and predictable user experience by adhering to an established set of
principles.

The Navigation component consists of three key parts that are described below:

● Navigation graph: An XML resource that contains all navigation-related


information in one centralized location. This includes all of the individual content
areas within your app, called destinations, as well as the possible paths that a user
can take through your app.
● NavHost: An empty container that displays destinations from your navigation
graph. The Navigation component contains a default NavHost implementation,
NavHostFragment, that displays fragment destinations.
● NavController: An object that manages app navigation within a NavHost. The
NavController orchestrates the swapping of destination content in the NavHost as
users move throughout your app.

As you navigate through your app, you tell the NavController that you want to navigate
either along a specific path in your navigation graph or directly to a specific destination.
The NavController then shows the appropriate destination in the NavHost.

The Navigation component provides a number of other benefits, including the following:

● Handling fragment transactions.


● Handling Up and Back actions correctly by default.
● Providing standardized resources for animations and transitions.
● Implementing and handling deep linking.
● Including Navigation UI patterns, such as navigation drawers and bottom
navigation, with minimal additional work.
● Safe Args - a Gradle plugin that provides type safety when navigating and passing
data between destinations.
● ViewModel support - you can scope a ViewModel to a navigation graph to share
UI-related data between the graph's destinations.

Providing users with a path through


your app
In the early stages of developing an app, you should determine the paths users should take
through your app in order to do something, such as placing an order or browsing through
content. Each path enables users to navigate across, into, and back out from the different
tasks and pieces of content within the app.
In many cases you will need several different paths through your app that offer the
following types of navigation:
● Back navigation: Users can navigate back to the previous screen using the Back
button.
● Hierarchical navigation: Users can navigate through a hierarchy of screens
organized with a parent screen for every set of child screens.

Back-button navigation
Back-button navigation—navigation back through the history of screens—is deeply rooted
in the Android system. Android users expect the Back button in the bottom left corner of
every screen to take them to the previous screen. The set of historical screens always starts
with the user's Launcher (the device's Home screen), as shown in the figure below. Pressing
Back enough times should return the user back to the Launcher.

In the above figure:


1. Starting from Launcher.
2. Clicking the Back button to navigate to the previous screen.

You don't have to manage the Back button in your app. The system handles tasks and the
back stack—the list of previous screens—automatically. The Back button by default simply
traverses this list of screens, removing the current screen from the list as the user presses it.
There are, however, cases where you may want to override the behavior for the Back
button. For example, if your screen contains an embedded web browser in which users can
interact with page elements to navigate between web pages, you may wish to trigger the
embedded browser's default back behavior when users press the device's Back button.
The onBackPressed() method of the Activity class is called whenever the activity detects the
user's press of the Back key. The default implementation simply finishes the current
activity, but you can override this to do something else:
@Override
public void onBackPressed() {
// Add the Back key handler here.
return;
}

If your code triggers an embedded browser with its own behavior for the Back key, you
should return the Back key behavior to the system's default behavior if the user uses the
Back key to go beyond the beginning of the browser's internal history.

Hierarchical navigation patterns


To give the user a path through the full range of an app's screens, the best practice is to use
some form of hierarchical navigation. An app's screens are typically organized in a
parent-child hierarchy, as shown in the figure below:

In the figure above:


1. Parent screen. A parent screen (such as a news app's home screen) enables
navigation down to child screens.
○ The main activity of an app is usually the parent screen.
○ Implement a parent screen as an Activity with descendant navigation to one
or more child screens.
2. First-level child screen siblings. Siblings are screens in the same position in the
hierarchy that share the same parent screen (like brothers and sisters).
○ In the first level of siblings, the child screens may be collection screens that
collect the headlines of stories, as shown above.
○ Implement each child screen as an Activity or Fragment.
○ Implement lateral navigation to navigate from one sibling to another on the
same level.
○ If there is a second level of screens, the first level child screen is the parent to
the second level child screen siblings. Implement descendant navigation to the
second-level child screens.
3. Second-level child screen siblings. In news apps and others that offer multiple levels
of information, the second level of child screen siblings might offer content, such as
stories.
○ Implement a second-level child screen sibling as another Activity or
Fragment.
○ Stories at this level may include embedded story elements such as videos,
maps, and comments, which might be implemented as fragments.

You can enable the user to navigate up to and down from a parent, and sideways among
siblings:
● Descendant navigation: Navigating down from a parent screen to a child screen.
● Ancestral navigation: Navigating up from a child screen to a parent screen.
● Lateral navigation: Navigating from one sibling to another sibling (at the same
level).

You can use a main activity (as a parent screen) and then other activities or fragments to
implement a hierarchy of screens within an app.

RecyclerView

RecyclerView makes it easy to efficiently display large sets of data. You supply the data and
define how each item looks, and the RecyclerView library dynamically creates the elements
when they're needed.

As the name implies, RecyclerView recycles those individual elements. When an item scrolls
off the screen, RecyclerView doesn't destroy its view. Instead, RecyclerView reuses the view
for new items that have scrolled onscreen. RecyclerView improves performance and your
app's responsiveness, and it reduces power consumption.

Note: RecyclerView is the name of both the class and the library that contains it. On this page,
RecyclerView in code font always means the class in the RecyclerView library.

Key classes
Several classes work together to build your dynamic list.

● RecyclerView is the ViewGroup that contains the views corresponding to your data.
It's a view itself, so you add RecyclerView to your layout the way you would add any
other UI element.
● Each individual element in the list is defined by a view holder object. When the view
holder is created, it doesn't have any data associated with it. After the view holder is
created, the RecyclerView binds it to its data. You define the view holder by
extending RecyclerView.ViewHolder.
● The RecyclerView requests views, and binds the views to their data, by calling
methods in the adapter. You define the adapter by extending RecyclerView.Adapter.
● The layout manager arranges the individual elements in your list. You can use one of
the layout managers provided by the RecyclerView library, or you can define your
own. Layout managers are all based on the library's LayoutManager abstract class.

Steps for implementing your RecyclerView


If you're going to use RecyclerView, there are a few things you need to do. They are
explained in detail in the following sections.

1. Decide how the list or grid looks. Ordinarily, you can use one of the RecyclerView
library's standard layout managers.
2. Design how each element in the list looks and behaves. Based on this design, extend
the ViewHolder class. Your version of ViewHolder provides all the functionality for
your list items. Your view holder is a wrapper around a View, and that view is
managed by RecyclerView.
3. Define the Adapter that associates your data with the ViewHolder views.

Plan your layout


The items in your RecyclerView are arranged by a LayoutManager class. The
RecyclerView library provides three layout managers, which handle the most common
layout situations:

● LinearLayoutManager arranges the items in a one-dimensional list.


● GridLayoutManager arranges the items in a two-dimensional grid:
○ If the grid is arranged vertically, GridLayoutManager tries to make all the
elements in each row have the same width and height, but different rows can
have different heights.
○ If the grid is arranged horizontally, GridLayoutManager tries to make all the
elements in each column have the same width and height, but different
columns can have different widths.
● StaggeredGridLayoutManager is similar to GridLayoutManager, but it does not
require that items in a row have the same height (for vertical grids) or items in the
same column have the same width (for horizontal grids). The result is that the items
in a row or column can end up offset from each other.

You also need to design the layout of the individual items. You need this layout when you
design the view holder, as described in the next section.

Implement your adapter and view holder


Once you determine your layout, you need to implement your Adapter and ViewHolder.
These two classes work together to define how your data is displayed. The ViewHolder is a
wrapper around a View that contains the layout for an individual item in the list. The
Adapter creates ViewHolder objects as needed and also sets the data for those views. The
process of associating views to their data is called binding.

When you define your adapter, you override three key methods:

● onCreateViewHolder(): RecyclerView calls this method whenever it needs to create


a new ViewHolder. The method creates and initializes the ViewHolder and its
associated View, but does not fill in the view's contents—the ViewHolder has not yet
been bound to specific data.
● onBindViewHolder(): RecyclerView calls this method to associate a ViewHolder
with data. The method fetches the appropriate data and uses the data to fill in the
view holder's layout. For example, if the RecyclerView displays a list of names, the
method might find the appropriate name in the list and fill in the view holder's
TextView widget.
● getItemCount(): RecyclerView calls this method to get the size of the dataset. For
example, in an address book app, this might be the total number of addresses.
RecyclerView uses this to determine when there are no more items that can be
displayed.

Here's a typical example of a simple adapter with a nested ViewHolder that displays a list
of data. In this case, the RecyclerView displays a simple list of text elements. The adapter is
passed an array of strings containing the text for the ViewHolder elements.

Android Styles and Themes with


Examples
In android, Styles and Themes are used to change the look and feel of Views and appearance of application
based on our requirements. By using Styles and Themes we can reduce the code duplication and make our
app light & responsive.

Generally, the style is a combination of multiple attributes such as background color, font color, font size, font
style, height, width, padding, margin, etc. and it is used to change the look and feel of View or window.

In android, the style is defined in a separate XML resource file and we can use that defined style for the
Views in XML that specifies the layout. The Styles in android are similar to CSS styles in web design.

Following is the example of defining a TextView control with required style attributes in an XML layout file.

<TextView

android:id="@+id/txtResult"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:textColor="#86AD33"

android:textSize="20dp"
android:textStyle="bold" />

If you observe above code snippet, we defined a TextView control with required style attributes directly in
XML layout file.

Suppose if we use same or similar TextView styles in multiple places of our application, then the duplication
of code will increase and in future, if we want to change the style of our application, we need to update the
same style in all the places and it’s a time-consuming process.

We can overcome this problem by defining a style for the particular view and use the same style in all the
places wherever it is required in our application.

If we use style attribute we can move all style attributes related to particular view to a separate XML
resource file and refer that file in XML layout like shown below

<TextView

android:id="@+id/txtResult"

style="@style/TextviewStyle"/>

If you observe above code snippet, we removed all style attributes from XML layout and moved those
attributes to a style definition called TextviewStyle. In following sections we will see the definition of
TextviewStyle attribute.

In android, theme is a style that is applied to an entire activity or app, instead of an individual View like as
mentioned above. When we applied a style as a theme, the views in activity or app apply to the all style
attributes that supports. For example. If we apply TextviewStyle as a theme for an activity, then the text of all
the views in activity appears in the same style.

In simple words, if we use an entry from a resource file to style a view, then we can call it a style. In case if we
use an entry from a resource file to style activity or app, then we can call it a theme.

Android Defining Styles

As we discussed, we need to define a style in a separate XML resource file and use that defined style for the
Views in XML that specifies the layout.

To define a set of styles, we need to create a new XML file in /res/values directory of our project and the root
node of XML file must be a <resources>.

To create a style in the XML file, we need to follow the below steps.

● We need to add <style> element in the XML file with a name attribute to uniquely identify the style.
● To define attributes of style, we need to add an <item> elements with a name that defines a style
attribute and we need to add appropriate value to each <item> element.
In android, we can define multiple styles using <style> element with a name attribute to uniquely identify the
style in an XML file.

Following is the example of defining a style in separate XML file using <style> element.

<resources>

<style name="TextviewStyle">

<item name="android:textColor">#86AD33</item>

<item name="android:textStyle">bold</item>

<item name="android:textSize">20dp</item>

<item name="android:padding">10dp</item>

</style>

</resources>

If you observe above code snippet, we created a style “TextviewStyle” with all required style attributes and
we can use same style for multiple views instead of writing the same code multiple times.

Android Apply a Style to View

Once we are done with the creation of style, we can use it for the views which are defined in the XML layout
file with style attribute.

Following is the example of setting a style for the views in the XML layout.

<TextView

android:id="@+id/txtResult"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

style="@style/TextviewStyle"

android:text="Welcome to Tutlane"/>

If you observe above code snippet, the style (TextviewStyle) whatever we defined in XML is applied to
TextView control using style attribute and we can use the same style for other TextView’s also based on our
requirements.
Android Style Inheritance

In android, by using parent attribute in <style> element we can inherit the properties from an existing style
and define only the attributes that we want to change or add. We can inherit the styles that we created
ourselves or from the styles that are built into the platform.

Following is the example to inherit the android platform’s default TextView style
(@android:style/Widget.TextView) and modify it.

<style name="TextviewStyle" parent="@android:style/Widget.TextView">

<item name="android:textColor">#86AD33</item>

<item name="android:textStyle">bold</item>

<item name="android:textSize">20dp</item>

</style>

If you observe above code snippet, we are inheriting built-in platform style Widget.TextView using parent
attribute in <style> element.

In android, we can inherit the styles that we defined our self. To inherit our styles we don’t need to use parent
attribute instead, we can use dot notation by prefixing the name of the style that we want to inherit to the
name of our new style, separated by a period.

Following is the example of inheriting the style (TextviewStyle) which we defined above and create a new style
like as shown below.

<style name="TextviewStyle" parent="@android:style/Widget.TextView">

<item name="android:layout_width">wrap_content</item>

<item name="android:layout_height">wrap_content</item>

<item name="android:textColor">#86AD33</item>

<item name="android:textStyle">bold</item>

<item name="android:textSize">20dp</item>

<item name="android:layout_marginTop">12dp</item>

<item name="android:layout_marginLeft">100dp</item>

</style>

<style name="TextviewStyle.Blue">
<item name="android:textColor">#0088CC</item>

<item name="android:textStyle">italic</item>

</style>

If you observe above code snippet, we didn’t used any parent attribute in <style> tag, we used style name
TextviewStyle to inherit all the style attributes. The TextviewStyle.Blue style will inherit all the properties
from TextviewStyle and overrides the android:textColor and android:textStyle attributes to make the text
italic and Blue. The newly created style referenced from Textview as @style/TextviewStyle.Blue.

We can continue inheriting the styles like this as many times by chaining names with periods.

Following is the example to extend Textviewstyle.Blue style to further.

<style name="TextviewStyle" parent="@android:style/Widget.TextView">

<item name="android:layout_width">wrap_content</item>

<item name="android:layout_height">wrap_content</item>

<item name="android:textColor">#86AD33</item>

<item name="android:textStyle">bold</item>

<item name="android:textSize">20dp</item>

<item name="android:layout_marginTop">12dp</item>

<item name="android:layout_marginLeft">100dp</item>

</style>

<style name="TextviewStyle.Blue">

<item name="android:textColor">#0088CC</item>

<item name="android:textStyle">italic</item>

</style>

<style name="TextviewStyle.Blue.Background">

<item name="android:background">#FBBC09</item>

</style>

The TextviewStyle.Blue.Background style will inherit the properties from TextviewStyle and
TextviewStyle.Blue styles and it will add a new android:background attribute.
Android Defining Themes

In android, theme is a style that is applied to an entire activity or app, instead of an individual View like as
mentioned above. When we applied a style as a theme, the views in activity or app apply to the all style
attributes that supports. For example. If we apply TextviewStyle as a theme for an activity, then the text of all
the views in activity appears in the same style.

Following is the example of defining a theme in the android application.

<color name="custom_theme_color">#b0b0ff</color>

<style name="CustomTheme" parent="Theme.AppCompat.Light">

<item name="android:windowBackground">@color/custom_theme_color</item>

<item name="android:colorBackground">@color/custom_theme_color</item>

</style>

The above code overrides windowBackground and colorBackground properties of Theme.AppCompat.Light


theme.

To set a theme for a particular activity, open AndroidManifest.xml file and write the code like as shown
below

<activity android:theme="@android:style/CustomTheme">

In case, if we want to set the theme for all the activities in android application, open AndroidManifest.xml file
and write the code like as shown below.

<application android:theme="@android:style/CustomTheme">

Android Styling Color Palette

In android, we can customize the application basic theme colors based on our requirements.

Following is the example of basic material design in the android application.


Generally, the above layout defined in styles.xml file like as shown below and it resides in res/values folder.

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">

<!-- Customize your theme here. -->

<item name="colorPrimary">@color/colorPrimary</item>

<item name="colorPrimaryDark">@color/colorPrimaryDark</item>

<item name="colorAccent">@color/colorAccent</item>

</style>

We can customize the application basic theme colors based on our requirements. Now we will see how to use
these styles and themes in android applications with examples.

Android Styles and Themes Example


Following is the example of defining a custom style for controls in LinearLayout to apply different styles for
controls in the android application.

Create a new android application using android studio and give names as StylesThemesExample. In case if
you are not aware of creating an app in android studio check this article Android Hello World App.

Now we need to define our styles in styles.xml file, for that open styles.xml file from \res\values folder and
write the code like as shown below.

styles.xml

<resources>

<!-- Base application theme. -->

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">

<!-- Customize your theme here. -->

<item name="colorPrimary">@color/colorPrimary</item>

<item name="colorPrimaryDark">@color/colorPrimaryDark</item>

<item name="colorAccent">@color/colorAccent</item>

</style>

<style name="TextviewStyle" parent="@android:style/Widget.TextView">

<item name="android:layout_width">wrap_content</item>

<item name="android:layout_height">wrap_content</item>

<item name="android:layout_marginLeft">100dp</item>

<item name="android:layout_marginTop">10dp</item>

<item name="android:textColor">#86AD33</item>

<item name="android:textStyle">bold</item>

<item name="android:textSize">20dp</item>

</style>

<style name="ButtonStyle" parent="@android:style/Widget.Button">


<item name="android:layout_width">200dp</item>

<item name="android:layout_height">wrap_content</item>

<item name="android:layout_marginLeft">100dp</item>

<item name="android:layout_marginTop">10dp</item>

<item name="android:textColor">#FFFFFF</item>

<item name="android:background">#F1511B</item>

<item name="android:textStyle">bold</item>

<item name="android:textSize">15dp</item>

</style>

<string name="wlcmsg">welcome to Tutlane</string>

</resources>

If you observe above code, we defined a two styles (TextViewStyle, ButtonStyle) and we can apply these styles
for required controls in android application.

Now open an activity_main.xml file from \res\layout path and write the code like as shown below

activity_main.xml

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

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

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical" >

<TextView

android:id="@+id/TextView1"

android:layout_width="wrap_content"

android:layout_height="wrap_content"
android:layout_marginLeft="100dp"

android:layout_marginTop="200dp"

android:textColor="#00ADEF"

android:textSize="15dp"

android:text="@string/wlcmsg"/>

<TextView

android:id="@+id/TextView2"

style="@style/TextviewStyle"

android:text="Welcome to Tutlane"/>

<Button

android:id="@+id/btnShow"

android:text="Click on Button"

style="@style/ButtonStyle" />

</LinearLayout>

Material Design Components (MDC Android) offers designers and developers a way
to implement Material Design in their Android application. Developed by a core
team of engineers and UX designers at Google, these components enable a reliable
development workflow to build beautiful and functional Android applications.
Material design in Android is one of the key features that attracts and engages the
customer towards the application. This is a special type of design, which is guided by
Google. So in this article, it has been introduced to the basic things that need to be
considered before designing or developing any Materialistic Android Application.
The topics covered in these articles are
1. Color and theming
2. Typography (Choosing the right font)
3. Material design components
4. Shaping the material design components
1. Colors and Theming

By choosing the right kind of color combination reflects the application’s brand and
style. For example, the application’s main or primary color is the Green, then in the
whole application, the green color will be frequently shown. Choosing the color for
the application, there are three types of colors to be chosen for developing the
android application.
● Primary Color: This color should be chosen very cautiously because this
color is frequently visible in the application components like high
emphasis buttons or the button ripple color, and also the top and bottom
navigation bar.
● Secondary Color: This color should be chosen only when there is a low
complexity level of the application. This color will be applied to those
elements which need a little color accent like the. background color for the
Floating Action Buttons (FAB), sliders, toggle buttons, chips (Active
State), progress bars, etc.
● Light and Dark variants: These colors are the variants of the primary
color. The dark variant of the primary color is set for the status bar and
the light variant of the primary color is set for the Floating action button,
outline for the edit texts, and where the elements need some color accents
the light variant of the primary colors will be set for them. Have a look at
the following image when only the primary color is set for the application
theme looks like.
But according to the complexity of the application, there are various types of color
can be chosen.

● Have a look at the following image, having selected the primary color, with
that the Complementary color can be chosen or Analogous color can be
chosen or Triadic color can be chosen or Secondary color can be chosen to
meet the required style.

2. Typography (Choosing the Right Font)


● In android, however, the Roboto font meets all the requirements. But too, if
the developer wants to customize the application more with the font, the
font needs to be chosen where it has all its variants. The variants are the
light face, regular face, medium face, and sometimes the dark face.
● Choosing the font from Google Font is recommended. As it offers a variety
of font families, and almost all the fonts have contained all the variants.
● There are some guidelines that need to be followed by having the font
chosen. In this case, the Roboto is chosen for demonstration purposes only.
Looking at the following image which is the type scale chart for applying
the styles of the fonts for various contexts.
● The various contexts include captions, Body, Subtitles, Button, captions,
etc.
● In the below image left side column contains the font is chosen, font style,
and the font size. The second column contains the preview of the selected
context of the font.
3. Material Design Components

● Material design components are the components that allow a lot of


features for the users and easy to implement for the developers.
● Have a look at the following image on how material design components
stand out in terms of the customization, styling, and look, from the normal
UI components.

● The features offered by the material design components can be


implemented in various contexts. One can notice in the above image how
the normal button and edit text has adapted to the application’s theme and
how the material design button has adapted to the application’s theme.
● These components can even adapt to the dark theme and change their
styles when it is toggled by the user. Have look at the following image to
differentiate the behaviors between the material design components and
normal UI components.

● For step-by-step implementations of some of the material design


components and their theming can be found in the following articles.

4. Shaping the Components

● In material design, there are three types of shaping methods.


1. Cut corner
2. Rounded corner
3. Triangle edge
● These methods are also can be applied for the material design buttons, text
fields, chips, floating action buttons, cards, navigation bars, bottom sheets,
etc.
● These features are available with the Material design components out of
the proverbial box. Just need to add the dependency of the material design
components and start implementing the styling for material design
components.

AsyncTask and AsyncTaskLoader

There are several ways to do background processing in Android. Two of those ways are:

● You can do background processing directly, using the AsyncTask class.


● You can do background processing indirectly, using the Loader framework and then
the AsyncTaskLoader class.

In most situations the Loader framework is a better choice, but it's important to know how
AsyncTask works.
Note: The Loader framework provides special-purpose classes that manage loading and
reloading updated data asynchronously in the background. You learn more about loaders
in a later lesson.

In this chapter you learn why it's important to process some tasks in the background, off
the UI thread. You learn how to use AsyncTask, when not to use AsyncTask, and the basics of
using loaders.

The UI thread

When an Android app starts, it creates the main thread, which is often called the UI thread.
The UI thread dispatches events to the appropriate user interface (UI) widgets. The UI
thread is where your app interacts with components from the Android UI toolkit
(components from the android.widget and android.view packages).

Android's thread model has two rules:

● Do not block the UI thread.


● Do UI work only on the UI thread.

The UI thread needs to give its attention to drawing the UI and keeping the app responsive
to user input. If everything happened on the UI thread, long operations such as network
access or database queries could block the whole UI. From the user's perspective, the app
would appear to hang. Even worse, if the UI thread were blocked for more than a few
seconds (about 5 seconds currently) the user would be presented with the "application not
responding" (ANR) dialog. The user might decide to quit your app and uninstall it.

To make sure your app doesn't block the UI thread:

● Complete all work in less than 16 ms for each UI screen.


● Don't run asynchronous tasks and other long-running tasks on the UI thread.
Instead, implement tasks on a background thread using AsyncTask (for short or
interruptible tasks) or AsyncTaskLoader (for tasks that are high-priority, or tasks that
need to report back to the user or UI).

Conversely, don't use a background thread to manipulate your UI, because the Android UI
toolkit is not thread-safe.

AsyncTask

A worker thread is any thread which is not the main or UI thread. Use the AsyncTask class to
implement an asynchronous, long-running task on a worker thread. AsyncTask allows you to
perform background operations on a worker thread and publish results on the UI thread
without needing to directly manipulate threads or handlers.

When AsyncTask is executed, it goes through four steps:

1. onPreExecute() is invoked on the UI thread before the task is executed. This step is
normally used to set up the task, for instance by showing a progress bar in the UI.
2. doInBackground(Params...) is invoked on the background thread immediately after
onPreExecute() finishes. This step performs a background computation, returns a
result, and passes the result to onPostExecute(). The doInBackground() method can also
call publishProgress(Progress...) to publish one or more units of progress.
3. onProgressUpdate(Progress...) runs on the UI thread after publishProgress(Progress...) is
invoked. Use onProgressUpdate() to report any form of progress to the UI thread while
the background computation is executing. For instance, you can use it to pass the
data to animate a progress bar or show logs in a text field.
4. onPostExecute(Result) runs on the UI thread after the background computation has
finished. The result of the background computation is passed to this method as a
parameter.
For complete details on these methods, see the AsyncTask reference. Below is a diagram of
their calling order.

AsyncTask usage

To use the AsyncTask class, define a subclass of AsyncTask that overrides the
doInBackground(Params...) method (and usually the onPostExecute(Result) method as well). This
section describes the parameters and usage of AsyncTask, then shows a complete example.

AsyncTask parameters

In your subclass of AsyncTask, provide the data types for three kinds of parameters:

● "Params" specifies the type of parameters passed to doInBackground() as an array.


● "Progress" specifies the type of parameters passed to publishProgress() on the
background thread. These parameters are then passed to the onProgressUpdate()
method on the main thread.
● "Result" specifies the type of parameter that doInBackground() returns. This
parameter is automatically passed to onPostExecute() on the main thread.
Specify a data type for each of these parameter types, or use Void if the parameter type will
not be used. For example:

● public class MyAsyncTask extends AsyncTask <String, Void, Bitmap>{}

In this class declaration:

● The "Params" parameter type is String, which means that MyAsyncTask takes one or
more strings as parameters in doInBackground(), for example to use in a query.
● The "Progress" parameter type is Void, which means that MyAsyncTask won't use the
publishProgress() or onProgressUpdate() methods.

● The "Result" parameter type is Bitmap. MyAsyncTask returns a Bitmap in


doInbackground(), which is passed into onPostExecute().

Android lets your application connect to the internet or any other local network and allows
you to perform network operations.

A device can have various types of network connections. This chapter focuses on using
either a Wi-Fi or a mobile network connection.

Checking Network Connection


Before you perform any network operations, you must first check that are you connected to
that network or internet e.t.c. For this android provides ConnectivityManager class. You
need to instantiate an object of this class by calling getSystemService() method. Its syntax is
given below −

ConnectivityManager check = (ConnectivityManager)


this.context.getSystemService(Context.CONNECTIVITY_SERVICE);
Once you instantiate the object of ConnectivityManager class, you can use
getAllNetworkInfo method to get the information of all the networks. This method returns
an array of NetworkInfo. So you have to receive it like this.

NetworkInfo[] info = check.getAllNetworkInfo();


The last thing you need to do is to check Connected State of the network. Its syntax is given
below −

for (int i = 0; i<info.length; i++){


if (info[i].getState() == NetworkInfo.State.CONNECTED){
Toast.makeText(context, "Internet is connected
Toast.LENGTH_SHORT).show();
}
}
Apart from this connected states, there are other states a network can achieve. They are
listed below −

Sr.No State

1 Connecting

2 Disconnected

3 Disconnecting

4 Suspended

5 Unknown

Performing Network Operations


After checking that you are connected to the internet, you can perform any network
operation. Here we are fetching the html of a website from a url.
Android provides HttpURLConnection and URL class to handle these operations. You
need to instantiate an object of URL class by providing the link of website. Its syntax is as
follows −

String link = "http://www.google.com";


URL url = new URL(link);
After that you need to call openConnection method of url class and receive it in a
HttpURLConnection object. After that you need to call the connect method of
HttpURLConnection class.

HttpURLConnection conn = (HttpURLConnection) url.openConnection();


conn.connect();
And the last thing you need to do is to fetch the HTML from the website. For this you will
use InputStream and BufferedReader class. Its syntax is given below −

InputStream is = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String webPage = "",data="";

while ((data = reader.readLine()) != null){


webPage += data + "\n";
}
Apart from this connect method, there are other methods available in HttpURLConnection
class. They are listed below −

Sr.N Method & description


o

1
disconnect()

This method releases this connection so that its resources may be either reused or
closed
2
getRequestMethod()

This method returns the request method which will be used to make the request
to the remote HTTP server

3
getResponseCode()

This method returns response code returned by the remote HTTP server

4
setRequestMethod(String method)

This method Sets the request command which will be sent to the remote HTTP
server

5
usingProxy()

This method returns whether this connection uses a proxy server or not

Example
The below example demonstrates the use of HttpURLConnection class. It creates a basic
application that allows you to download HTML from a given web page.

To experiment with this example, you need to run this on an actual device on which wifi
internet is connected .

Broadcast Receivers
Broadcast in android is the system-wide events that can occur when the device
starts, when a message is received on the device or when incoming calls are received,
or when a device goes to airplane mode, etc. Broadcast Receivers are used to
respond to these system-wide events. Broadcast Receivers allow us to register for the
system and application events, and when that event happens, then the register
receivers get notified. There are mainly two types of Broadcast Receivers:
● Static Broadcast Receivers: These types of Receivers are declared in the
manifest file and works even if the app is closed.
● Dynamic Broadcast Receivers: These types of receivers work only if the
app is active or minimized.

Since from API Level 26, most of the broadcast can only be caught by the dynamic
receiver, so we have implemented dynamic receivers in our sample project given
below. There are some static fields defined in the Intent class which can be used to
broadcast different events. We have taken a change of airplane mode as a broadcast
event, but there are many events for which broadcast register can be used.
Following are some of the important system-wide generated intents:-

Intent Description Of Event

Indicates low battery condition on


android.intent.action.BATTERY_LOW :
the device.
android.intent.action.BOOT_COMPLETE This is broadcast once after the
D system has finished booting

To perform a call to someone


android.intent.action.CALL
specified by the data

android.intent.action.DATE_CHANGED Indicates that the date has changed

Indicates that the device has been a


android.intent.action.REBOOT
reboot

android.net.conn.CONNECTIVITY_CHAN The mobile network or wifi


GE connection is changed(or reset)

android.intent.ACTION_AIRPLANE_MO This indicates that airplane mode


DE_CHANGED has been switched on or off.

The two main things that we have to do in order to use the broadcast receiver in our
application are:
Creating the Broadcast Receiver:
class AirplaneModeChangeReceiver:BroadcastReceiver() {

override fun onReceive(context: Context?, intent: Intent?) {


// logic of the code needs to be written here

Registering a BroadcastReceiver:
IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED).also {

// receiver is the broadcast receiver that we have registered

// and it is the intent filter that we have created

registerReceiver(receiver,it)

Example

Below is the sample project showing how to create the broadcast Receiver and how
to register them for a particular event and how to use them in the application.

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


<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
</androidx.constraintlayout.widget.ConstraintLayout>

Step 3: Working with the MainActivity file


Go to the MainActivity file and refer to the following code. Below is the code for the
MainActivity file. Comments are added inside the code to understand the code in
more detail.

● Java
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

AirplaneModeChangeReceiver airplaneModeChangeReceiver = new


AirplaneModeChangeReceiver();

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

@Override
protected void onStart() {
super.onStart();
IntentFilter filter = new
IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED);
registerReceiver(airplaneModeChangeReceiver, filter);
}

@Override
protected void onStop() {
super.onStop();
unregisterReceiver(airplaneModeChangeReceiver);
}
}

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.provider.Settings;
import android.widget.Toast;

public class AirplaneModeChangeReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {

if (isAirplaneModeOn(context.getApplicationContext())) {
Toast.makeText(context, "AirPlane mode is on",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "AirPlane mode is off",
Toast.LENGTH_SHORT).show();
}
}

private static boolean isAirplaneModeOn(Context context) {


return Settings.System.getInt(context.getContentResolver(),
Settings.Global.AIRPLANE_MODE_ON, 0) != 0;
}
}

Output:

Services in Android with Example


Services in Android are a special component that facilitates an application to run in
the background in order to perform long-running operation tasks. The prime aim of
a service is to ensure that the application remains active in the background so that
the user can operate multiple applications at the same time. A user-interface is not
desirable for android services as it is designed to operate long-running processes
without any user intervention. A service can run continuously in the background
even if the application is closed or the user switches to another application. Further,
application components can bind itself to service to carry out inter-process
communication(IPC). There is a major difference between android services and
threads, one must not be confused between the two. Thread is a feature provided by
the Operating system to allow the user to perform operations in the background.
While service is an android component that performs a long-running operation
about which the user might not be aware of as it does not have UI.
Types of Android Services

1. Foreground Services:

Services that notify the user about its ongoing operations are termed as Foreground
Services. Users can interact with the service by the notifications provided about the
ongoing task. Such as in downloading a file, the user can keep track of the progress
in downloading and can also pause and resume the process.

2. Background Services:
Background services do not require any user intervention. These services do not
notify the user about ongoing background tasks and users also cannot access them.
The process like schedule syncing of data or storing of data fall under this service.

3. Bound Services:

This type of android service allows the components of the application like activity to
bound themselves with it. Bound services perform their task as long as any
application component is bound to it. More than one component is allowed to bind
themselves with a service at a time. In order to bind an application component with
a service bindService() method is used.

The Life Cycle of Android Services

In android, services have 2 possible paths to complete its life cycle namely Started
and Bounded.

1. Started Service (Unbounded Service):

By following this path, a service will initiate when an application component calls
the startService() method. Once initiated, the service can run continuously in the
background even if the component is destroyed which was responsible for the start
of the service. Two option are available to stop the execution of service:
● By calling stopService() method,
● The service can stop itself by using stopSelf() method.

2. Bounded Service:

It can be treated as a server in a client-server interface. By following this path,


android application components can send requests to the service and can fetch
results. A service is termed as bounded when an application component binds itself
with a service by calling bindService() method. To stop the execution of this service,
all the components must unbind themselves from the service by using
unbindService() method.
To carry out a downloading task in the background, the startService() method will be
called. Whereas to get information regarding the download progress and to pause or
resume the process while the application is still in the background, the service must be
bounded with a component which can perform these tasks.

Fundamentals of Android Services

A user-defined service can be created through a normal class which is extending the
class Service. Further, to carry out the operations of service on applications, there
are certain callback methods which are needed to be overridden. The following are
some of the important methods of Android Services:

Methods Description

The Android service calls this method when a


component(eg: activity)

onStartCommand
()
requests to start a service using startService(). Once the
service is started,
it can be stopped explicitly using stopService() or
stopSelf() methods.

This method is mandatory to implement in android


service and is invoked

whenever an application component calls the


bindService() method in order to

onBind() bind itself with a service. User-interface is also provided to


communicate

with the service effectively by returning an IBinder object.

If the binding of service is not required then the method


must return null.
The Android system invokes this method when all the
clients

onUnbind()

get disconnected from a particular service interface.

Once all clients are disconnected from the particular


interface of service and

onRebind()

there is a need to connect the service with new clients, the


system calls this method.

Whenever a service is created either using


onStartCommand() or onBind(),

onCreate()

the android system calls this method. This method is


necessary to perform
a one-time-set-up.

When a service is no longer in use, the system invokes this


method

just before the service destroys as a final clean up call.


Services must

onDestroy()

implement this method in order to clean up resources like


registered listeners,

threads, receivers, etc.

Android Notification
Android Notification provides short, timely information about the action happened in the
application, even it is not running. The notification displays the icon, title and some amount
of the content text.

Set Android Notification Properties

The properties of Android notification are set using NotificationCompat.Builder object.


Some of the notification properties are mention below:
● setSmallIcon(): It sets the icon of notification.

● setContentTitle(): It is used to set the title of notification.

● setContentText(): It is used to set the text message.

● setAutoCancel(): It sets the cancelable property of notification.

● setPriority(): It sets the priority of notification.

You might also like