Android App Development Overview
Android App Development Overview
UNIT - I
Support different platform versions
While the latest versions of Android often provide great APIs for your app, you should continue to support older versions
of Android until more devices get updated. This lesson shows you how to take advantage of the latest APIs while
continuing to support older versions as well.
Use the Android Studio New Project wizard to find the distribution of active devices running each version of Android. This
distribution is based on the number of devices that visit the Google Play Store. Generally, we recommend supporting
about 90% of active devices, while targeting your app to the latest version.
Introduction to Android
Android is a complete set of software for mobile devices such as tablet computers, notebooks, smartphones, electronic
book readers, set-top boxes [Link] contains a linux-based Operating System, middleware and key mobile applications.
It can be thought of as a mobile operating system. But it is not limited to mobile only. It is currently used in various devices
such as mobiles, tablets, televisions etc.
History of Android
The history and versions of android are interesting to know. The code names of android ranges from A to J
currently,suchas Aestro, Blender, Cupcake, Donut, Eclair, Froyo, Gingerbread, Honeycomb, Ice Cream Sandwitch, Jelly
Bean, KitKat and Lollipop. Let's understand the android history in a sequence.
1) Initially, Andy Rubin founded Android Incorporation in Palo Alto, California, United States in October, 2003.
2) In 17th August 2005, Google acquired android Incorporation. Since then, it is in the subsidiary of Google Incorporation.
3) The key employees of Android Incorporation are Andy Rubin, Rich Miner, Chris White and Nick Sears.
4) Originally intended for camera but shifted to smart phones later because of low market for camera only.
5) Android is the nick name of Andy Rubin given by coworkers because of his love to robots.
6) In 2007, Google announces the development of android OS.
7) In 2008, HTC launched the first android mobile.
Android is a software package and linux based operating system for mobile devices such as
tablet computers and smartphones.
It is developed by Google and later the OHA (Open Handset Alliance). Java language is mainly
used to write the android code even though other languages can be used.
The goal of android project is to create a successful real-world product that improves the
mobile experience for end users.
properly clean your iPhone or Android to extend its life
There are many code names of android such as Lollipop, Kitkat, Jelly Bean, Ice cream Sandwich, Froyo, Ecliar, Donut etc
which is covered in next page.
Features of Android
The important features of android are given below:
1) It is open-source.
2) Anyone can customize the Android Platform.
3) There are a lot of mobile applications that can be chosen by the consumer.
4) It provides many interesting features like weather details, opening screen, live RSS (Really Simple Syndication) feeds etc.
It provides support for messaging services(SMS and MMS), web browser, storage (SQLite), connectivity (GSM, CDMA, Blue
Tooth, Wi-Fi etc.), media, handset layout etc.
Android APIs
The Google Fit APIs for Android are part of Google Play services. The Google Fit APIs are supported on Android 4.1 (API
level 16) and higher. Using these APIs, your app can do the following:
Read near-real-time and historic data, including data from Bluetooth Low Energy (BLE) devices.
Record activities.
Associate data with a session., Set fitness goals.
Read sensor data
If your app provides information about a user's activity, such as their daily steps, it
can be helpful to show near-real-time data about the user’s movements.
The Sensors API provides access to streams of raw data that contain this
information. The data can come from sensors available on the Android-powered
device as well as from sensors in companion devices, such as wearables.
Record data
If your app needs to gather, store, and sync data about a user's physical activity,
you can use the Recording API. This API stores health and wellness data using
subscriptions. Your app specifies one or more types of activities to record. Google
Fit then stores data of the specified types in the background even when your app
isn't running. It also restores these subscriptions when the system is restarted.
Sessions
Fitness data can be beneficial by itself, but the data is more useful when you combine it with additional information about
the user’s activity. The Sessions API bundles health and wellness data, along with some metadata, into units
called sessions. Sessions represent a time interval during which the user performs a fitness activity.
Android Architecture
android architecture or Android software stack is
categorized into five parts:
linux kernel
native libraries (middleware),
Android Runtime
Application Framework
Applications
Let's see the android architecture first.
1) Linux kernel
It is the heart of android architecture that exists at the
root of android architecture. Linux kernel is responsible
for device drivers, power management, memory
management, device management and resource
access.
2) Native Libraries
On the top of linux kernel, their are Native
libraries such as WebKit, OpenGL, FreeType, SQLite,
Media, C runtime library (libc) etc.
The WebKit library is responsible for browser support, SQLite is for database, FreeType for font support, Media for playing
and recording audio and video formats.
3) Android Runtime
In android runtime, there are core libraries and DVM (Dalvik Virtual Machine) which is responsible to run android
application. DVM is like JVM but it is optimized for mobile devices. It consumes less memory and provides fast
performance.
4) Android Framework
On the top of Native libraries and android runtime, there is android framework. Android framework includes Android
API's such as UI (User Interface), telephony, resources, locations, Content Providers (data) and package managers. It
provides a lot of classes and interfaces for android application development.
5) Applications
On the top of android framework, there are applications. All applications such as home, contact, settings, games, browsers
are using android framework that uses android runtime and libraries. Android runtime and native libraries are using linux
kernal.
Android Core Building Blocks
An android component is simply a piece of code that has a well defined life cycle e.g. Activity, Receiver, Service etc.
The core building blocks or fundamental components of android are activities, views, intents, services, content providers,
fragments and [Link].
Activity
An activity is a class that represents a single screen. It is like a Frame in AWT.
View
A view is the UI element such as button, label, text field etc. Anything
that you see is a view.
Intent
Intent is used to invoke components. It is mainly used to:
Start the service
Launch an activity
Display a web page
Display a list of contacts
Broadcast a message
Dial a phone call etc.
For example, you may write the following code to view the webpage.
Intent intent=new Intent(Intent.ACTION_VIEW);
[Link]([Link]("[Link]
startActivity(intent);
Service
Service is a background process that can run for a long time.
There are two types of services local and remote. Local service is accessed from within the application whereas remote
service is accessed remotely from other applications running on the same device.
Content Provider
Content Providers are used to share data between the applications.
Fragment
Fragments are like parts of activity. An activity can display one or more fragments on the screen at the same time.
[Link]
It contains informations about activities, content providers, permissions etc. It is like the [Link] file in Java EE.
Android Virtual Device (AVD)
It is used to test the android application without the need for mobile or tablet etc. It can be created in different
configurations to emulate different types of real devices.
Android Runtime (ART) is an application runtime environment used by the Android operating system. Replacing Dalvik,
the process virtual machine originally used by Android, ART performs the translation of the
application's bytecode into native instructions that are later executed by the device's runtime environment.[2]
Overviews
The javac tool compiles the java source file into the
class file.
Features of Android
The important features of android are given below:
1) It is open-source.
2) Anyone can customize the Android Platform.
3) There are a lot of mobile applications that can be chosen by the consumer.
4) It provides many interesting features like weather details, opening screen, live RSS (Really Simple Syndication) feeds etc.
It provides support for messaging services(SMS and MMS), web browser, storage (SQLite), connectivity (GSM, CDMA, Blue
Tooth, Wi-Fi etc.), media, handset layout etc.
setup Android for Eclipse IDE
install the android SDK and ADT plugin for Eclipse IDE. Let's see the list of software required to setup android for
eclipse IDE manually.
1) Install the Java Development Kit (JDK)
For creating android application, JDK must be installed if you are developing the android application with Java
language. download the JDK
2) Download and install the Eclipse IDE
For developing the android application using eclipse IDE, you need to install the Eclipse. you can download it from this
location download the Eclipse
. Eclipse classic version is recommended but we are using the Eclipse IDE for JavaEE Developers.
Android Emulator
The Android emulator is an Android Virtual Device (AVD), which represents a specific Android device. We can use the
Android emulator as a target device to execute and test our Android application on our PC. The Android emulator provides
almost all the functionality of a real device. We can get the incoming phone calls and text messages. It also gives the
location of the device and simulates different network speeds. Android emulator simulates rotation and other hardware
sensors. It accesses the Google Play store, and much moreTesting Android applications on emulator are sometimes faster
and easier than doing on a real device. For example, we can transfer data faster to the emulator than to a real device
connected through USB.
The Android emulator comes with predefined configurations for several Android phones, Wear OS, tablet, Android TV
devices.
1.2 Click on Create Virtual Device, at the bottom of the AVD Manager dialog. Then Select Hardware page appears.
1.3 Select a hardware profile and then click Next. If we don?t see the hardware profile we want, then we can create or
import a hardware profile. The System Image page appears.
1.4 Select the system image for the particular API level and click Next. This leads to open a Verify Configuration page.
1.5 Change AVD properties if needed, and then click Finish.
2. In the toolbar, choose the AVD, which we want to run our app from the target device from the drop-down menu.
3. Click Run.
Options
The following table lists the available options for the above commands.
Option Description
--sdk_root=path Use the specified SDK path instead of the SDK containing this tool
Include packages in channels up to and including channel_id. Available channels
--channel=channel_id are:
0 (Stable), 1 (Beta), 2 (Dev), and 3 (Canary).
Include obsolete packages in the package listing or package updates. For use
--include_obsolete
with --list and --update only.
--no_https Force all connections to use HTTP rather than HTTPS.
--verbose Verbose output mode. Errors, warnings and informational messages are printed.
Connect via a proxy of the given type: either http for high level protocols such as
--proxy={http | socks}
HTTP or FTP, or socks for a SOCKS (V4 or V5) proxy.
--
IP or DNS address of the proxy to use.
proxy_host={IP_address | DNS_address}
--proxy_port=port_number Proxy port number to connect to.
add & use accounts in the Google Play Store on your device
You can add a Google Account on your device to start downloading and buying items on the Google Play Store app. You
can add multiple Google Accounts to your device by repeating the steps below.
What is an APK?
Before discussing how to install an APK file on an Android smartphone, let's see the brief description of an APK file:
An APK is a short form of the Android Package Kit. It is a package file format used on Android OS to distribute and
install an app on Android devices. It is just like a .exe file used for installing software on Windows PC and a package
installer (PKG) for Mac. Downloading an app using APK are sometimes leaked apps that customize your Android
experience or some other Android apps which are not uploaded on Google Play Store due to any reason.
Downloading an APK file online or receiving it from other persons are getting an installer file of an app on an Android
device.
After you complete the preceding setup steps, you can then test Privacy Sandbox on Android. To do so, download a device
or emulator image.
ANDROID APPLICATION
UNIT - II
Set up your development environment
Follow the instructions on this page to set up the Privacy Sandbox on Android SDK in Android Studio.
SDKMANAGER
The sdkmanager is a command-line tool that lets you view, install, update, and uninstall packages for the Android SDK. If
you're using Android Studio, then you don't need to use this tool, and you can instead manage your SDK packages from the
IDE.
The sdkmanager tool is provided in the Android SDK Command-Line Tools package. To use the SDK Manager to install a
version of the command-line tools, follow these steps:
Download the latest "command line tools only" package from the Android Studio downloads page and unzip the package.
Move the unzipped cmdline-tools directory into a new directory of your choice, such as android_sdk. This new directory is
your Android SDK directory.
In the unzipped cmdline-tools directory, create a sub-directory called latest.
Move the original cmdline-tools directory contents, including the lib directory, bin directory, [Link] file,
and [Link] file, into the newly created latest directory. You can now use the command-line tools from this
location.
(Optional) To install a previous version of the command-line tools, run the following command:
android_sdk/cmdline-tools/latest/bin/sdkmanager --install "cmdline-tools;version"
Substitute version with the version you want to install, for example [Link]: For local usage, you can use
the latest packages. For scripts, choose a specific version instead to ensure stability.
Usage
You can use the sdkmanager to list installed and available packages, install packages, and update packages. For more
details, see the following sections.
List installed and available packages
To list installed and available packages, use the following syntax:
sdkmanager --list [options] \
[--channel=channel_id] // Channels: 0 (stable), 1 (beta), 2 (dev), or 3 (canary)
Use the channel option to include a package from a channel up to and including channel_id. For example, specify the
canary channel to list packages from all channels.
Note: To list only stable packages, use --channel=0 or remove the --channel option entirely.
Install packages
To install packages, use the following syntax:
sdkmanagerpackages [options]
The packages argument is an SDK-style path, as shown with the --list command, wrapped in quotes. For example, "build-
tools;30.0.2" or "platforms;android-28".
You can pass multiple package paths, separated with a space, but they must each be wrapped in their own set of quotes.
For example, here's how to install the latest platform tools and the SDK tools for API level 28:
sdkmanager "platform-tools" "platforms;android-28"
Alternatively, you can pass a text file that specifies all packages:
sdkmanager --package_file=package_file [options]
The package_file argument is the location of a text file in which each line is an SDK-style path of a package to install
(without quotes).
To uninstall, add the --uninstall flag:
sdkmanager --uninstall packages [options]
sdkmanager --uninstall --package_file=package_file [options]
To install CMake or the NDK, use the following syntax:
sdkmanager--install
["ndk;[Link][suffix]"|"cmake;[Link]"]
[--channel=channel_id]// NDK channels: 0 (stable), 1 (beta), or 3 (canary)
For example, use the following command to install the specified NDK version regardless of which channel it is currently on:
sdkmanager--install "ndk;21.3.6528147"--channel=3// Install the NDK from the canary channel (or below)
sdkmanager--install "cmake;10.24988404"// Install a specific version of CMake
Option Description
--sdk_root=path Use the specified SDK path instead of the SDK containing this tool.
--channel=channel_id Include packages in channels up to and including channel_id. Available channels are:
0 (Stable), 1 (Beta), 2 (Dev), and 3 (Canary).
--include_obsolete Include obsolete packages in the package listing or package updates. For use with --
list and --update only.
--no_https Force all connections to use HTTP rather than HTTPS.
--verbose Verbose output mode. Errors, warnings and informational messages are printed.
--proxy={http | socks} Connect via a proxy of the given type: either http for high level protocols such as
HTTP or FTP, or socks for a SOCKS (V4 or V5) proxy.
-- IP or DNS address of the proxy to use.
proxy_host={IP_address | DNS_address}
At the end of the build process, you have either a debug or release APK or AAB of your app that you can use to deploy,
test, or release to external users.
Android build glossary
Gradle and the Android plugin help you configure the following aspects of your build:
Build types
Build types define certain properties that Gradle uses when building and packaging your app, and are typically
configured for different stages of your development lifecycle. For example, the debug build type enables debug
options and signs the app with the debug key, while the release build type may shrink, obfuscate, and sign your
app with a release key for distribution. You must define at least one build type in order to build your app—Android
Studio creates the debug and release build types by default. To start customizing packaging settings for your app,
learn how to Configure build types.
Product flavors
Product flavors represent different versions of your app that you may release to users, such as free and paid
versions of your app. You can customize product flavors to use different code and resources, while sharing and
reusing the parts that are common to all versions of your app. Product flavors are optional and you must create
them manually. To start creating different versions of your app, learn how to Configure product flavors.
Build variants
A build variant is a cross product of a build type and product flavor, and is the configuration Gradle uses to build
your app. Using build variants, you can build the debug version of your product flavors during development, or
signed release versions of your product flavors for distribution. Although you do not configure build variants
directly, you do configure the build types and product flavors that form them. Creating additional build types or
product flavors also creates additional build variants. To learn how to create and manage build variants, read
the Configure build variants overview.
Manifest entries
You can specify values for some properties of the manifest file in the build variant configuration. These build
values override the existing values in the manifest file. This is useful if you want to generate multiple variants of
your app with a different application name, minimum SDK version, or target SDK version. When multiple manifests
are present, Gradle merges manifest settings.
Dependencies
The build system manages project dependencies from your local filesystem and from remote repositories. This
prevents you from having to manually search, download, and copy binary packages of your dependencies into your
project directory. To find out more, see Add build dependencies.
Signing
The build system enables you to specify signing settings in the build configuration, and it can automatically sign
your app during the build process. The build system signs the debug version with a default key and certificate using
known credentials to avoid a password prompt at build time. The build system does not sign the release version
unless you explicitly define a signing configuration for this build. If you do not have a release key, you can generate
one as described in Sign your app.
Code and resource shrinking
The build system enables you to specify a different ProGuard rules file for each build variant. When building your
app, the build system applies the appropriate set of rules to shrink your code and resources using its built-in
shrinking tools, such as R8.
Multiple APK support
The build system enables you to automatically build different APKs that each contain only the code and resources
needed for a specific screen density or Application Binary Interface (ABI). For more information see Build multiple
APKs. Please note that releasing a single AAB instead is the recommended approach, as it offers splitting by
language in addition to screen density and ABI, while reducing the complexity of having to upload multiple
artifacts to Google Play.
There are a few Gradle build configuration files that are a part of the
standard project structure for an Android app. Before you can start
configuring your build, it is important to understand the scope and
purpose of each of these files, and the basic DSL elements they should
define.
GROOVYKOTLIN
pluginManagement{
/**
* The pluginManagement {repositories {...}} block configures the
* repositories Gradle uses to search or download the Gradle plugins and
* their transitive dependencies. Gradle pre-configures support for remote
* repositories such as JCenter, Maven Central, and Ivy. You can also use
* local repositories or define your own remote repositories. The code below
* defines the Gradle Plugin Portal, Google's Maven repository,
* and the Maven Central Repository as the repositories Gradle should use to look for its dependencies.
*/
repositories {
gradlePluginPortal()
google()
mavenCentral()
}
}
dependencyResolutionManagement{
/**
* The dependencyResolutionManagement { repositories {...}}
* block is where you configure the repositories and dependencies used by
* all modules in your project, such as libraries that you are using to
* create your application. However, you should configure module-specific
* dependencies in each module-level [Link] file. For new projects,
* Android Studio includes Google's Maven repository
* and the Maven Central Repository by
* default, but it does not configure any dependencies (unless you select a
* template that requires some).
*/
[Link](RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
mavenCentral()
}
}
[Link] ="My Application"
include ‘:app’
Multi-module projects need to specify each module that should go into the final build.
plugins {
/**
* You should use `apply false` in the top-level [Link] file
* to add a Gradle plugin as a build dependency, but not apply it to the
* current (root) project. You should not use `apply false` in sub-projects.
* For more information, see
* Applying external plugins with same version to subprojects.
*/
id '[Link]' version '7.3.0' apply false
id '[Link]' version '7.3.0' apply false
id '[Link]' version '1.7.20' apply false
}
task clean(type:Delete){
[Link]
}
Configure project-wide properties
For Android projects that include multiple modules, it may be useful to define certain properties at the project level and
share them across all the modules. You can do this by adding extra properties to the ext block in the top-
level [Link] file.
GroovyKotlin
// This block encapsulates custom properties and makes them available to all
// modules in the project. The following are only a few examples of the types
// of properties you can define.
ext{
sdkVersion=28
// You can also create properties to specify versions for dependencies.
// Having consistent versions between modules can avoid conflicts with behavior.
supportLibVersion="28.0.0"
...
}
...
To access these properties from a module in the same project, use the following syntax in the
module's [Link] file (you can learn more about this file in the section below).
GroovyKotlin
android {
// Use the following syntax to access properties you defined at the project level:
// [Link].property_name
[Link]
...
}
...
dependencies {
implementation "[Link]:appcompat-v7:${[Link]}"
...
}
Note: Although Gradle allows you to define project-wide properties at the module level, you should avoid doing so
because it causes the modules that share those properties to be coupled. Module coupling makes it more difficult to later
export a module as a stand-alone project and effectively prevents Gradle from utilizing parallel project execution to speed
up multi-module builds.
The module-level build file
The module-level [Link] file, located in each project/module/ directory, allows you to configure build settings for the
specific module it is located in. Configuring these build settings allows you to provide custom packaging options, such as
additional build types and product flavors, and override settings in the main/ app manifest or top-level [Link] file.
This sample Android app module [Link] file outlines some of the basic DSL elements and settings that you should
know.
GroovyKotlin
/**
* The first line in the build configuration applies the Android plugin for
* Gradle to this build and makes the android block available to specify
* Android-specific build options.
*/
plugins {
id '[Link]'
}
/**
* The android block is where you configure all your Android-specific
* build options.
*/
android {
/**
* The app's namespace. Used primarily to access app resources.
*/
namespace'[Link]'
/**
* compileSdkVersion specifies the Android API level Gradle should use to
* compile your app. This means your app can use the API features included in
* this API level and lower.
*/
compileSdkVersion28
/**
* The defaultConfig block encapsulates default settings and entries for all
* build variants, and can override some attributes in main/[Link]
* dynamically from the build system. You can configure product flavors to override
* these values for different versions of your app.
*/
defaultConfig{
// Uniquely identifies the package for publishing.
applicationId'[Link]'
// Defines the minimum API level required to run the app.
minSdkVersion15
// Specifies the API level used to test the app.
targetSdkVersion28
// Defines the version number of your app.
versionCode1
// Defines a user-friendly version name for your app.
versionName"1.0"
}
/**
* The buildTypes block is where you can configure multiple build types.
* By default, the build system defines two build types: debug and release. The
* debug build type is not explicitly shown in the default build configuration,
* but it includes debugging tools and is signed with the debug key. The release
* build type applies Proguard settings and is not signed by default.
*/
buildTypes{
/**
* By default, Android Studio configures the release build type to enable code
* shrinking, using minifyEnabled, and specifies the default Proguard rules file.
*/
release {
minifyEnabledtrue// Enables code shrinking for the release build type.
proguardFilesgetDefaultProguardFile('[Link]'),'[Link]'
}
}
/**
* The productFlavors block is where you can configure multiple product flavors.
* This allows you to create different versions of your app that can
* override the defaultConfig block with their own settings. Product flavors
* are optional, and the build system does not create them by default.
* This example creates a free and paid product flavor. Each product flavor
* then specifies its own application ID, so that they can exist on the Google
* Play Store, or an Android device, simultaneously.
* If you declare product flavors, you must also declare flavor dimensions
* and assign each flavor to a flavor dimension.
*/
flavorDimensions"tier"
productFlavors{
free {
dimension "tier"
applicationId'[Link]'
}
paid {
dimension "tier"
applicationId'[Link]'
}
}
}
/**
* The dependencies block in the module-level build configuration file
* specifies dependencies required to build only the module itself.
* To learn more, go to Add build dependencies.
*/
dependencies {
implementation project(":lib")
implementation '[Link]:appcompat-v7:28.0.0'
implementation fileTree(dir:'libs', include:['*.jar'])
}
Figure 3. Syncing the project with build configuration files in Android Studio.
Source sets
Android Studio logically groups source code and resources for each module into source sets. A module’s main/ source
set includes the code and resources used by all its build variants. Additional source set directories are optional, and
Android Studio does not automatically create them for you when you configure new build variants. However, creating
source sets, similar to main/, helps organize files and resources that Gradle should only use when building certain
versions of your app:
src/main/
This source set includes code and resources common to all build variants.
src/buildType/
Create this source set to include code and resources only for a specific build type.
src/productFlavor/
Create this source set to include code and resources only for a specific product flavor.
Note: If you configure your build to combine multiple product flavors, you can create source set directories for
each combination of product flavors between the flavor dimensions: src/productFlavor1ProductFlavor2/
src/productFlavorBuildType/
Create this source set to include code and resources only for a specific build variant.
For example, to generate the "fullDebug" version of your app, the build system merges code, settings, and resources
from following source sets:
src/fullDebug/ (the build variant source set)
src/debug/ (the build type source set)
src/full/ (the product flavor source set)
src/main/ (the main source set)
Note: When you create a new file or directory in Android Studio, using the File > New menu options, you can create it
for a specific source set. The source sets you can choose from are based on your build configurations, and Android
Studio automatically creates the required directories if they don't already exist.
If different source sets contain different versions of the same file, Gradle uses the following priority order when
deciding which file to use (source sets on the left override the files and settings of source sets to the right):
build variant > build type > product flavor> main source set > library dependencies
This allows Gradle to use files that are specific to the build variant you are trying to build while reusing activities,
application logic, and resources that are common to other versions of your app. When merging multiple manifests,
Gradle uses the same priority order, so each build variant can define different components or permissions in the final
manifest. To learn more about creating custom source sets, go to Create Source Sets for Build Variants.
After finishing the Activity configuration, Android Studio auto generates the activity class and other required configuration
files.
Now an android project has been created. You can explore the android project and see the simple program, it looks like this:
The Pair devices over Wi-Fi window pops up, as shown below.
Figure 1. Run configurations dropdown menu Figure 2. Popup window to pair devices using QR code or pairing code. Figure 3. Screenshot of the Wireless debugging
Acer [Link]
Alcatel Mobile [Link]
Asus [Link]
Blackberry [Link]
Dell [Link]
Fujitsu [Link]
HTC [Link]
Huawei [Link]
Intel [Link]
Kyocera [Link]
Lenovo [Link]
LGE [Link]
Motorola [Link]
MTK [Link] (ZIP download)
Samsung [Link]
Sharp [Link]
Sony Mobile [Link]
Communications
Toshiba [Link]
Xiaomi [Link]
ZTE [Link]
Click Run. The emulator might take a minute or so to launch for the first time, but
subsequent launches will use a snapshot and should launch faster. If you experience
issues at this point, see Troubleshoot the emulator.
Once your app is installed on your AVD, you can run it from the device as you would
run any app on a device. Any time you want to deploy new changes though, you
need to click Run or Apply Changes again.
Feature Description
Swipe the screen Point to the screen, press and hold the primary mouse button, swipe across the screen, and then
release.
Drag an item Point to an item on the screen, press and hold the primary mouse button, move the item, and then
release.
Tap Point to the screen, press the primary mouse button, and then release. For example, you could click a
(touch) text field to start typing in it, select an app, or press a button.
Double tap Point to the screen, press the primary mouse button quickly twice, and then release.
Touch and hold Point to an item on the screen, press the primary mouse button, hold, and then release. For example,
you could open options for an item.
Type You can type in the emulator by using your computer keyboard, or using a keyboard that pops up on the
emulator screen. For example, you could type in a text field after you selected it.
Pinch and spread Pressing Control (Command on Mac) brings up a pinch gesture multi-touch interface. The mouse acts as
the first finger, and across the anchor point is the second finger. Drag the cursor to move the first point.
Clicking the left mouse button acts like touching down both points, and releasing acts like picking both
up.
Vertical swipe Open a vertical menu on the screen and use the scroll wheel (mouse wheel) to scroll through the menu
items until you see the one you want. Click the menu item to select it.
Perform common actions using the emulator panel
To perform common actions with the emulator, use the emulator toolbar (if you're running the emulator within Android
Studio) or the panel on the right side (if you're running the emulator in a window outside of Android Studio). Table 2
describes the common emulator actions and associated buttons.
You can use keyboard shortcuts to perform many common actions in the emulator. For a complete list of shortcuts in the
emulator, press F1 (Command + / on Mac) to open the Help pane in the Extended controls window.
Table 2. Common actions in the emulator
Feature Description
Resize Resize the emulator as you would any other operating system window. The emulator maintains an
aspect ratio appropriate for your device.
Power Click to turn the screen on or off.
Click and hold to turn the device on or off.
Volume up Click to view a slider control and turn the volume up. Click again to turn it up more, or use the slider
control to change the volume.
Volume down Click to view a slider control and turn the volume down. Click again to turn it down more, or use the
slider control to change the volume.
Take screenshot Click to take a screenshot of the device. For details, see Screenshots.
Enter zoom mode Click so the cursor changes to the zoom icon. To exit zoom mode, click the button again.
Zoom in and out in zoom mode:
Left-click the screen to zoom in by 25%, up to a maximum of about twice the screen resolution of the
virtual device.
Right-click to zoom out.
Left-click and drag to select a box-shaped area to zoom in on.
Right-click and drag a selection box to reset to default zoom.
To pan in zoom mode, hold Control (Command on Mac) while pressing the arrow keys on the keyboard.
To tap the device screen in zoom mode, Control-click (Command-click on Mac).
Back Return to the previous screen, or close a dialog box, an options menu, the Notifications panel, or the
onscreen keyboard.
Overview Tap to open a list of thumbnail images of apps you’ve worked with recently. To open an app, tap it. To
remove a thumbnail from the list, swipe it left or right. This button isn't supported for Wear OS.
(Recent Apps)
Fold For foldable devices, fold the device to display its smaller screen configuration.
Unfold For foldable devices, unfold the device to display its larger screen configuration.
Button 1 For Wear devices, press Button 1 on the device. Only available on Wear devices running API level 28 or
higher.
Button 2 For Wear devices, press Button 2 on the device. Only available on Wear devices running API level 30 or
higher.
Palm For Wear devices, press your palm on the device screen. This sets your device to ambient mode. Only
available on Wear devices running API level 28 or higher.
Tilt For Wear devices, tilt the device. This exits ambient mode. Only available on Wear devices running API
level 28 or higher.
Komponen
Android Device Fitur yang seharusnyadigunakan
Monitor
Dalvik Debug Alatinitidakdigunakanlagi. Sebagaigantinya, gunakan Android Profiler di Android Studio 3.0 dan yang
Monitor Server lebihbaruuntukmemprofilkanpenggunaan CPU, memori, dan jaringanaplikasi Anda.
(DDMS)
Jikainginmenjalankantugas-tugas proses debug lainnya, sepertimengirimperintahkeperangkat yang
terhubunguntukmenyiapkanpenerusan port, mentransfer file, ataumengambil screenshot,
makagunakan Android Debug Bridge (adb), Android Emulator, Device File Explorer, atau jendela
Debugger.
Traceview Alatinitidakdigunakanlagi. Untukmemeriksa file .trace yang diambildengan melengkapiaplikasi
Anda dengan class Debug, merekamaktivitasmetodebaru, mengekspor file .trace, dan
memeriksapenggunaan CPU real-time dari proses aplikasi Anda, gunakan CPU Profiler Android Studio.
Systrace Jikaperlumemeriksa proses sistem native dan mengatasijank UI yang disebabkan oleh frame yang hilang,
gunakan systrace dari command line atau System Trace yang disederhanakan pada CPU Profiler. CPU
Profiler menyediakanbanyakfituruntukmemprofilkan proses aplikasi Anda.
Tracer for Gunakan Android GPU Inspector.
OpenGL ES
Hierarchy Jikainginmemeriksahierarkitampilanaplikasi Anda selama runtime, gunakan Layout Inspector.
Viewer
Jikainginmemprofilkankecepatan rendering tata letakaplikasi Anda,
gunakan [Link] seperti yang dijelaskandalam postingan blog ini.
Pixel Perfect Gunakan Layout Inspector.
Alat Traffic Jikaperlumelihatbagaimana dan kapanaplikasi Anda mentransfer data melaluijaringan, gunakan Network
Jaringan Profiler.
Memulai Android Device Monitor
Untukmemulaiaplikasi Device Monitor mandiri di Android Studio 3.1 dan yang lebih lama, masukkankodeberikut
pada command line di direktori android-sdk/ tools/:monitor
Kemudian, Anda dapatmenautkanalattersebutkeperangkat yang terhubungdenganmemilihperangkatdari
panel Device. Jikamengalamikesulitanuntukmelihat panel ataujendela, pilih Window > Reset Perspective dari
panel menu.
When exploring a device's files, the following directories are particularly useful:
data/data/app_name/
Contains data files for your app stored on internal storage
sdcard/
Figure 1. The Device File Explorer tool window Contains user files stored on external user storage (pictures, etc.)
onResume called when activity will start interacting with the user.
File: activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<[Link] xmlns:android="[Link]
/res/android"
xmlns:app="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="[Link]">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</[Link]>
Now click on the back button. Now you will see onPause methods is invoked.
After a while, you will see onStop and onDestroy methods are invoked.
ANDROID INTENT
Android Intent is the message that is passed between components such as activities, content providers, broadcast
receivers, services etc.
It is generally used with startActivity() method to invoke activity, broadcast receivers etc.
The dictionary meaning of intent is intention or purpose. So, it can be described as the intention to do action.
The LabeledIntent is the subclass of [Link] class.
Android intents are mainly used to:
o Start the service
o Launch an activity
o Display a web page
o Display a list of contacts
o Broadcast a message
o Dial a phone call etc.
Activity class
Now let's write the code that invokes another activity and get result from that activity.
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class MainActivity extends Activity {
TextView textView1;
Button button1;
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
textView1=(TextView)findViewById([Link].textView1);
button1=(Button)findViewById([Link].button1);
[Link](new OnClickListener() {
@Override
public void onClick(View arg0) {
Intent intent=new Intent([Link],[Link]);
startActivityForResult(intent, 2);// Activity is started with requestCode 2
}
});
}
// Call Back method to get the Message form other Activity
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
[Link](requestCode, resultCode, data);
// check if the request code is same as what is passed here it is 2
if(requestCode==2)
{
String message=[Link]("MESSAGE");
[Link](message);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate([Link], menu);
return true;
}
}
SecondActivity class
Let's write the code that displays the content of second activity layout file.
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class SecondActivity extends Activity {
EditText editText1;
Button button1;
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_second);
editText1=(EditText)findViewById([Link].editText1);
button1=(Button)findViewById([Link].button1);
[Link](new OnClickListener() {
@Override
public void onClick(View arg0) {
String message=[Link]().toString();
Intent intent=new Intent();
[Link]("MESSAGE",message);
setResult(2,intent);
finish();//finishing activity
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate([Link], menu);
return true;
}
}
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class MainActivity extends AppCompatActivity {
Button sharebutton;
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
sharebutton=(Button)findViewById([Link]);
[Link](new [Link]() {
@Override
public void onClick(View v) {
Intent shareIntent = new Intent([Link].ACTION_SEND);
[Link]("text/plain");
[Link](Intent.EXTRA_SUBJECT,"Insert Subject here");
String app_url = " [Link]
[Link]([Link].EXTRA_TEXT,app_url);
startActivity([Link](shareIntent, "Share via"));
}
});
}
}
Application Fundamentals
Android apps can be written using Kotlin, Java, and C++ languages. The Android SDK tools compile your code along with
any data and resource files into an APK or an Android App Bundle.
An Android package, which is an archive file with an .apk suffix, contains the contents of an Android app that are required
at runtime and it is the file that Android-powered devices use to install the app.
An Android App Bundle, which is an archive file with an .aab suffix, contains the contents of an Android app project
including some additional metadata that is not required at runtime. An AAB is a publishing format and is not installable on
Android devices, it defers APK generation and signing to a later stage. When distributing your app through Google Play for
example, Google Play's servers generate optimized APKs that contain only the resources and code that are required by a
particular device that is requesting installation of the app.
Each Android app lives in its own security sandbox, protected by the following Android security features:
The Android operating system is a multi-user Linux system in which each app is a different user.
By default, the system assigns each app a unique Linux user ID (the ID is used only by the system and is unknown
to the app). The system sets permissions for all the files in an app so that only the user ID assigned to that app can
access them.
Each process has its own virtual machine (VM), so an app's code runs in isolation from other apps.
By default, every app runs in its own Linux process. The Android system starts the process when any of the app's
components need to be executed, and then shuts down the process when it's no longer needed or when the system
must recover memory for other apps.
The Android system implements the principle of least privilege. That is, each app, by default, has access only to the
components that it requires to do its work and no more. This creates a very secure environment in which an app cannot
access parts of the system for which it is not given permission. However, there are ways for an app to share data with other
apps and for an app to access system services:
It's possible to arrange for two apps to share the same Linux user ID, in which case they are able to access each
other's files. To conserve system resources, apps with the same user ID can also arrange to run in the same Linux
process and share the same VM. The apps must also be signed with the same certificate.
An app can request permission to access device data such as the device's location, camera, and Bluetooth
connection. The user has to explicitly grant these permissions. For more information, see Working with System
Permissions.
The rest of this document introduces the following concepts:
The core framework components that define your app.
The manifest file in which you declare the components and the required device features for your app.
Resources that are separate from the app code and that allow your app to gracefully optimize its behavior for a
variety of device configurations.
App components
App components are the essential building blocks of an Android app. Each component is an entry point through which the
system or a user can enter your app. Some components depend on others.
There are four different types of app components:
Activities
Services
Broadcast receivers
Content providers
Each type serves a distinct purpose and has a distinct lifecycle that defines how the component is created and destroyed. The
following sections describe the four types of app components.
Activities
An activity is the entry point for interacting with the user. It represents a single screen with a user interface. 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 emails. Although the activities work together to form a cohesive user experience in
the email app, each one is independent of the others. As such, a different app can start any one of these activities if
the email app allows it. For example, a camera app can start the activity in the email app that composes new mail to
allow the user to share a picture. An activity facilitates the following key interactions between system and app:
Keeping track of what the user currently cares about (what is on screen) to ensure that the system keeps
running the process that is hosting the activity.
Knowing that previously used processes contain things the user may return to (stopped activities), and thus
more highly prioritize keeping those processes around.
Helping the app handle having its process killed so the user can return to activities with their previous state
restored.
Providing a way for apps to implement user flows between each other, and for the system to coordinate
these flows. (The most classic example here being share.)
You implement an activity as a subclass of the Activity class. For more information about the Activity class, see
the Activities developer guide.
Services
A service is a general-purpose entry point for keeping an app running in the background for all kinds of reasons. It is
a component that runs in the background to perform long-running operations or to perform work for remote
processes. A service does not provide a user interface. For example, a service might play music in the background
while the user is in a different app, or it might fetch data over the network without blocking user interaction with an
activity. Another component, such as an activity, can start the service and let it run or bind to it in order to interact
with it.
There are two types of services that tell the system how to manage an app: started services and bound services.
Started services tell the system to keep them running until their work is completed. This could be to sync some data
in the background or play music even after the user leaves the app. Syncing data in the background or playing music
also represent two different types of started services that modify how the system handles them:
Music playback is something the user is directly aware of, so the app tells the system this by saying it wants
to be foreground with a notification to tell the user about it; in this case the system knows that it should try
really hard to keep that service's process running, because the user will be unhappy if it goes away.
A regular background service is not something the user is directly aware as running, so the system has more
freedom in managing its process. It may allow it to be killed (and then restarting the service sometime later)
if it needs RAM for things that are of more immediate concern to the user.
Bound services run because some other app (or the system) has said that it wants to make use of the service. This is
basically the service providing an API to another process. The system thus knows there is a dependency between
these processes, so if process A is bound to a service in process B, it knows that it needs to keep process B (and its
service) running for A. Further, if process A is something the user cares about, then it also knows to treat process B
as something the user also cares about.
Because of their flexibility (for better or worse), services have turned out to be a really useful building block for all
kinds of higher-level system concepts. Live wallpapers, notification listeners, screen savers, input methods,
accessibility services, and many other core system features are all built as services that applications implement and
the system binds to when they should be running.
A service is implemented as a subclass of Service. For more information about the Service class, see
the Services developer guide.
Note: If your app targets Android 5.0 (API level 21) or later, use the JobScheduler class to schedule actions.
JobScheduler has the advantage of conserving battery by optimally scheduling jobs to reduce power consumption,
and by working with the Doze API. For more information about using this class, see the JobScheduler reference
documentation.
Broadcast receivers
A broadcast receiver is a component that enables the system to deliver events to the app outside of a regular user
flow, allowing the app to respond to system-wide broadcast announcements. Because broadcast receivers are
another well-defined entry into the app, the system can deliver broadcasts even to apps that aren't currently running.
So, for example, an app can schedule an alarm to post a notification to tell the user about an upcoming event... and
by delivering that alarm to a BroadcastReceiver of the app, there is no need for the app to remain running until the
alarm goes off. Many broadcasts originate from the system—for example, a broadcast announcing that the screen
has turned off, the battery is low, or a picture was captured. Apps can also initiate broadcasts—for example, to let
other apps know that some data has been downloaded to the device and is available for them to use. Although
broadcast receivers don't display a user interface, they may create a status bar notification to alert the user when a
broadcast event occurs. More commonly, though, a broadcast receiver is just a gateway to other components and is
intended to do a very minimal amount of work. For instance, it might schedule a JobService to perform some work
based on the event with JobScheduler
A broadcast receiver is implemented as a subclass of BroadcastReceiver and each broadcast is delivered as
an Intent object. For more information, see the BroadcastReceiver class.
Content providers
A content provider manages a shared set of app data that you can store in the file system, in a SQLite database, on
the web, or on any other persistent storage location that your app can access. Through the content provider, other
apps can query or modify the data if the content provider allows it. For example, the Android system provides a
content provider that manages the user's contact information. As such, any app with the proper permissions can
query the content provider, such as [Link], to read and write information about a particular person.
It is tempting to think of a content provider as an abstraction on a database, because there is a lot of API and support
built in to them for that common case. However, they have a different core purpose from a system-design
perspective. To the system, a content provider is an entry point into an app for publishing named data items,
identified by a URI scheme. Thus an app can decide how it wants to map the data it contains to a URI namespace,
handing out those URIs to other entities which can in turn use them to access the data. There are a few particular
things this allows the system to do in managing an app:
Assigning a URI doesn't require that the app remain running, so URIs can persist after their owning apps
have exited. The system only needs to make sure that an owning app is still running when it has to retrieve
the app's data from the corresponding URI.
These URIs also provide an important fine-grained security model. For example, an app can place the URI
for an image it has on the clipboard, but leave its content provider locked up so that other apps cannot freely
access it. When a second app attempts to access that URI on the clipboard, the system can allow that app to
access the data via a temporary URI permission grant so that it is allowed to access the data only behind that
URI, but nothing else in the second app.
Content providers are also useful for reading and writing data that is private to your app and not shared.
A content provider is implemented as a subclass of ContentProvider and must implement a standard set of APIs that
enable other apps to perform transactions. For more information, see the Content Providers developer guide.
A unique aspect of the Android system design is that any app can start another app‟s component. For example, if
you want the user to capture a photo with the device camera, there's probably another app that does that and your
app can use it instead of developing an activity to capture a photo yourself. You don't need to incorporate or even
link to the code from the camera app. Instead, you can simply start the activity in the camera app that captures a
photo. When complete, the photo is even returned to your app so you can use it. To the user, it seems as if the
camera is actually a part of your app.
When the system starts a component, it starts the process for that app if it's not already running and instantiates the
classes needed for the component. For example, if your app starts the activity in the camera app that captures a
photo, that activity runs in the process that belongs to the camera app, not in your app's process. Therefore, unlike
apps on most other systems, Android apps don't have a single entry point (there's no main() function).
Because the system runs each app in a separate process with file permissions that restrict access to other apps, your
app cannot directly activate a component from another app. However, the Android system can. To activate a
component in another app, deliver a message to the system that specifies your intent to start a particular component.
The system then activates the component for you.
Activating components
Three of the four component types—activities, services, and broadcast receivers—are activated by an asynchronous
message called an intent. Intents bind individual components to each other at runtime. You can think of them as the
messengers that request an action from other components, whether the component belongs to your app or another.
An intent is created with an Intent object, which defines a message to activate either a specific component (explicit
intent) or a specific type of component (implicit intent).
For activities and services, an intent defines the action to perform (for example, to view or send something) and may
specify the URI of the data to act on, among other things that the component being started might need to know. For
example, an intent might convey a request for an activity to show an image or to open a web page. In some cases,
you can start an activity to receive a result, in which case the activity also returns the result in an Intent. For
example, you can issue an intent to let the user pick a personal contact and have it returned to you. The return intent
includes a URI pointing to the chosen contact.
For broadcast receivers, the intent simply defines the announcement being broadcast. For example, a broadcast to
indicate the device battery is low includes only a known action string that indicates battery is low.
Unlike activities, services, and broadcast receivers, content providers are not activated by intents. Rather, they are
activated when targeted by a request from a ContentResolver. The content resolver handles all direct transactions
with the content provider so that the component that's performing transactions with the provider doesn't need to and
instead calls methods on the ContentResolver object. This leaves a layer of abstraction between the content provider
and the component requesting information (for security).
There are separate methods for activating each type of component:
You can start an activity or give it something new to do by passing
an Intent to startActivity() or startActivityForResult() (when you want the activity to return a result).
With Android 5.0 (API level 21) and later, you can use the JobScheduler class to schedule actions. For
earlier Android versions, you can start a service (or give new instructions to an ongoing service) by passing
an Intent to startService(). You can bind to the service by passing an Intent to bindService().
You can initiate a broadcast by passing an Intent to methods such
as sendBroadcast(), sendOrderedBroadcast(), or sendStickyBroadcast().
You can perform a query to a content provider by calling query() on a ContentResolver.
For more information about using intents, see the Intents and Intent Filters document. The following documents
provide more information about activating specific components: Activities, Services, BroadcastReceiver,
and Content Providers.
The manifest file
Before the Android system can start an app component, the system must know that the component exists by reading
the app's manifest file, [Link]. Your app must declare all its components in this file, which must be at
the root of the app project directory.
The manifest does a number of things in addition to declaring the app's components, such as the following:
Identifies any user permissions the app requires, such as Internet access or read-access to the user's contacts.
Declares the minimum API Level required by the app, based on which APIs the app uses.
Declares hardware and software features used or required by the app, such as a camera, bluetooth services,
or a multitouch screen.
Declares API libraries the app needs to be linked against (other than the Android framework APIs), such as
the Google Maps library.
Declaring components
The primary task of the manifest is to inform the system about the app's components. For example, a manifest file
can declare an activity as follows:
<?xml version="1.0" encoding="utf-8"?>
<manifest ... >
<application android:icon="@drawable/app_icon.png" ... >
<activity android:name="[Link]"
android:label="@string/example_label" ... >
</activity>
...
</application>
</manifest>
In the <application> element, the android:icon attribute points to resources for an icon that identifies the app.
In the <activity> element, the android:name attribute specifies the fully qualified class name of the Activity subclass
and the android:label attribute specifies a string to use as the user-visible label for the activity.
You must declare all app components using the following elements:
<activity> elements for activities.
<service> elements for services.
<receiver> elements for broadcast receivers.
<provider> elements for content providers.
Activities, services, and content providers that you include in your source but do not declare in the manifest are not visible to
the system and, consequently, can never run. However, broadcast receivers can be either declared in the manifest or
created dynamically in code as BroadcastReceiver objects and registered with the system by calling registerReceiver().
For more about how to structure the manifest file for your app, see The [Link] File documentation.
With the declarations shown in these examples, devices that do not have a camera or have an Android
version lower than 8.0 cannot install your app from Google Play. However, you can declare that your app uses the
camera, but does not require it. In that case, your app must set the required attribute to false and check at runtime
whether the device has a camera and disable any camera features as appropriate.
More information about how you can manage your app's compatibility with different devices is provided in
the Device Compatibility document.
App resources
An Android app is composed of more than just code—it requires resources that are separate from the source code,
such as images, audio files, and anything relating to the visual presentation of the app. For example, you can define
animations, menus, styles, colors, and the layout of activity user interfaces with XML files. Using app resources
makes it easy to update various characteristics of your app without modifying code. Providing sets of alternative
resources enables you to optimize your app for a variety of device configurations, such as different languages and
screen sizes.
For every resource that you include in your Android project, the SDK build tools define a unique integer ID, which
you can use to reference the resource from your app code or from other resources defined in XML. For example, if
your app contains an image file named [Link] (saved in the res/drawable/ directory), the SDK tools generate a
resource ID named [Link]. This ID maps to an app-specific integer, which you can use to reference the
image and insert it in your user interface.
One of the most important aspects of providing resources separate from your source code is the ability to provide
alternative resources for different device configurations. For example, by defining UI strings in XML, you can
translate the strings into other languages and save those strings in separate files. Then Android applies the
appropriate language strings to your UI based on a language qualifier that you append to the resource directory's
name (such as res/values-fr/ for French string values) and the user's language setting.
Android supports many different qualifiers for your alternative resources. The qualifier is a short string that you
include in the name of your resource directories in order to define the device configuration for which those
resources should be used. For example, you should create different layouts for your activities, depending on the
device's screen orientation and size. When the device screen is in portrait orientation (tall), you might want a layout
with buttons to be vertical, but when the screen is in landscape orientation (wide), the buttons could be aligned
horizontally. To change the layout depending on the orientation, you can define two different layouts and apply the
appropriate qualifier to each layout's directory name. Then, the system automatically applies the appropriate layout
depending on the current device orientation.
ANDROID APPLICATION
UNIT - III
Android - UI Layouts
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.
The ViewGroup is a subclass of View and provides invisible container that hold other Views or other ViewGroups and
define their layout properties.
At third level we have different layouts which are subclasses of ViewGroup class and a typical layout defines the visual
structure for an Android user interface and can be created either at run time using View/ViewGroup objects or you can
declare your layout using simple XML file main_layout.xml which is located in the res/layout folder of your project.
Layout params
This tutorial is more about creating your GUI based on layouts defined in XML file.
A layout may contain any type of widgets such as buttons, labels, textboxes, and so
on. Following is a simple example of XML file having LinearLayout −
<?xml version="1.0" encoding="utf-8"?>
<LinearLayoutxmlns:android="[Link]
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextViewandroid:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is a TextView"/>
<Buttonandroid:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is a Button"/>
<!-- More GUI components go here -->
</LinearLayout>
Once your layout has created, you can load the layout resource from your application code, in
your [Link]() callback implementation as shown below −
publicvoidonCreate(BundlesavedInstanceState){
[Link](savedInstanceState);
setContentView([Link].activity_main);
}
Android Layout Types
There are number of Layouts provided by Android which you will use in almost all the Android applications to provide
different view, look and feel.
[Link] Layout & Description
1 Linear Layout
LinearLayout is a view group that aligns all children in a single direction, vertically or horizontally.
2 Relative Layout
RelativeLayout is a view group that displays child views in relative positions.
3 Table Layout
TableLayout is a view that groups views into rows and columns.
4 Absolute Layout
AbsoluteLayout enables you to specify the exact location of its children.
5 Frame Layout
The FrameLayout is a placeholder on screen that you can use to display a single view.
6 List View
ListView is a view group that displays a list of scrollable items.
7 Grid View
GridView is a ViewGroup that displays items in a two-dimensional, scrollable grid.
Layout Attributes
Each layout has a set of attributes which define the visual properties of that layout. There are few common attributes among
all the layouts and their are other attributes which are specific to that layout. Following are common attributes and will be
applied to all the layouts:
1 android:id
This is the ID which uniquely identifies the view.
2 android:layout_width
This is the width of the layout.
3 android:layout_height
This is the height of the layout
4 android:layout_marginTop
This is the extra space on the top side of the layout.
5 android:layout_marginBottom
This is the extra space on the bottom side of the layout.
6 android:layout_marginLeft
This is the extra space on the left side of the layout.
7 android:layout_marginRight
This is the extra space on the right side of the layout.
8 android:layout_gravity
This specifies how child Views are positioned.
9 android:layout_weight
This specifies how much of the extra space in the layout should be allocated to the View.
10 android:layout_x
This specifies the x-coordinate of the layout.
11 android:layout_y
This specifies the y-coordinate of the layout.
12 android:layout_width
This is the width of the layout.
13 android:paddingLeft
This is the left padding filled for the layout.
14 android:paddingRight
This is the right padding filled for the layout.
15 android:paddingTop
This is the top padding filled for the layout.
16 android:paddingBottom
This is the bottom padding filled for the layout.
Here width and height are the dimension of the layout/view which can be specified in terms of dp (Density-independent
Pixels), sp( Scale-independent Pixels), pt ( Points which is 1/72 of an inch), px( Pixels), mm ( Millimeters) and finally in
(inches).
You can specify width and height with exact measurements but more often, you will use one of these constants to set the
width or height −
android:layout_width=wrap_content tells your view to size itself to the dimensions required by its content.
android:layout_width=fill_parent tells your view to become as big as its parent view.
Gravity attribute plays important role in positioning the view object and it can take one or more (separated by '|') of the
following constant values.
top 0x30 Push object to the top of its container, not changing its size.
bottom 0x50 Push object to the bottom of its container, not changing its size.
left 0x03 Push object to the left of its container, not changing its size.
right 0x05 Push object to the right of its container, not changing its size.
center_vertical 0x10 Place object in the vertical center of its container, not changing its size.
fill_vertical 0x70 Grow the vertical size of the object if needed so it completely fills its container.
center_horizontal 0x01 Place object in the horizontal center of its container, not changing its size.
fill_horizontal 0x07 Grow the horizontal size of the object if needed so it completely fills its container.
center 0x11 Place the object in the center of its container in both the vertical and horizontal axis, not
changing its size.
fill 0x77 Grow the horizontal and vertical size of the object if needed so it completely fills its
container.
clip_vertical 0x80 Additional option that can be set to have the top and/or bottom edges of the child
clipped to its container's bounds. The clip will be based on the vertical gravity: a top
gravity will clip the bottom edge, a bottom gravity will clip the top edge, and neither
will clip both edges.
clip_horizontal 0x08 Additional option that can be set to have the left and/or right edges of the child clipped
to its container's bounds. The clip will be based on the horizontal gravity: a left gravity
will clip the right edge, a right gravity will clip the left edge, and neither will clip both
edges.
start 0x00800003 Push object to the beginning of its container, not changing its size.
end 0x00800005 Push object to the end of its container, not changing its size.
View Identification
A view object may have a unique ID assigned to it which will identify the View uniquely within the tree. The syntax for an
ID, inside an XML tag is −
android:id="@+id/my_button"
Following is a brief description of @ and + signs −
The at-symbol (@) at the beginning of the string indicates that the XML parser should parse and expand the rest of
the ID string and identify it as an ID resource.
The plus-symbol (+) means that this is a new resource name that must be created and added to our resources. To
create an instance of the view object and capture it from the layout, use the following −
ButtonmyButton=(Button)findViewById([Link].my_button);
Android - UI 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.
UI Elements
A View is an object that draws something on the screen that the user can interact with and a ViewGroup is an object that
holds other View (and ViewGroup) objects in order to define the layout of the user interface.
You define your layout in an XML file which offers a human-readable structure for the layout, similar to HTML. For
example, a simple vertical layout with a text view and a button looks like this −
<?xml version="1.0" encoding="utf-8"?>
<LinearLayoutxmlns:android="[Link]
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextViewandroid:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I am a TextView"/>
<Buttonandroid:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I am a Button"/>
</LinearLayout>
Android UI Controls
There are number of UI controls provided by Android that allow you to build the graphical user interface for your app.
[Link]. UI Control & Description
1 TextView
This control is used to display text to the user.
2 EditText
EditText is a predefined subclass of TextView that includes rich editing capabilities.
3 AutoCompleteTextView
The AutoCompleteTextView is a view that is similar to EditText, except that it shows a list of completion
suggestions automatically while the user is typing.
4 Button
A push-button that can be pressed, or clicked, by the user to perform an action.
5 ImageButton
An ImageButton is an AbsoluteLayout which enables you to specify the exact location of its children. This
shows a button with an image (instead of text) that can be pressed or clicked by the user.
6 CheckBox
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.
7 ToggleButton
An on/off button with a light indicator.
8 RadioButton
The RadioButton has two states: either checked or unchecked.
9 RadioGroup
A RadioGroup is used to group together one or more RadioButtons.
10 ProgressBar
The ProgressBar view provides visual feedback about some ongoing tasks, such as when you are performing
a task in the background.
11 Spinner
A drop-down list that allows users to select one value from a set.
12 TimePicker
The TimePicker view enables users to select a time of the day, in either 24-hour mode or AM/PM mode.
13 DatePicker
The DatePicker view enables users to select a date of the day.
Create UI 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.
As explained in previous chapter, a view object may have a unique ID assigned to it which will identify the View uniquely
within the tree. The syntax for an ID, inside an XML tag is −
android:id="@+id/text_id"
To create a UI Control/View/Widget you will have to define a view/widget in the layout file and assign it a unique ID as
follows −
<?xml version="1.0" encoding="utf-8"?>
<LinearLayoutxmlns:android="[Link]
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextViewandroid:id="@+id/text_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I am a TextView"/>
</LinearLayout>
Then finally create an instance of the Control object and capture it from the layout, use the following −
TextViewmyText=(TextView)findViewById([Link].text_id);
}
}
Now after clicking the button in the first page the second page is opened.
Android - Intents and Filters
An Android Intent is an abstract description of an operation to be performed. It can be used with startActivity to launch an
Activity, broadcastIntent to send it to any interested BroadcastReceiver components,
and startService(Intent) or bindService(Intent, ServiceConnection, int) to communicate with a background Service.
The intent itself, an Intent object, is a passive data structure holding an abstract description of an operation to be performed.
For example, let's assume that you have an Activity that needs to launch an email client and sends an email using your
Android device. For this purpose, your Activity would send an ACTION_SEND along with appropriate chooser, to the
Android Intent Resolver. The specified chooser gives the proper interface for the user to pick how to send your email data.
Intent email = new Intent(Intent.ACTION_SEND, [Link]("[Link]
[Link](Intent.EXTRA_EMAIL, recipients);
[Link](Intent.EXTRA_SUBJECT, [Link]().toString());
[Link](Intent.EXTRA_TEXT, [Link]().toString());
startActivity([Link](email, "Choose an email client from..."));
Above syntax is calling startActivity method to start an email activity and result should be as
shown below −
For example, assume that you have an Activity that needs to open URL in a web browser on your
Android device. For this purpose, your Activity will send ACTION_WEB_SEARCH Intent to the
Android Intent Resolver to open given URL in the web browser. The Intent Resolver parses through a list of Activities and
chooses the one that would best match your Intent, in this case, the Web Browser Activity. The Intent Resolver then passes
your web page to the web browser and starts the Web Browser Activity.
String q = "tutorialspoint";
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH );
[Link]([Link], q);
startActivity(intent);
Above example will search as tutorialspoint on android search engine and it gives the result of tutorialspoint in your an
activity
There are separate mechanisms for delivering intents to each type of component − activities, services, and broadcast
receivers.
[Link] Method & Description
[Link]()
1 The Intent object is passed to this method to launch a new activity or get an existing activity to do something
new.
[Link]()
2
The Intent object is passed to this method to initiate a service or deliver new instructions to an ongoing service.
[Link]()
3
The Intent object is passed to this method to deliver the message to all interested broadcast receivers.
Intent Objects
An Intent object is a bundle of information which is used by the component that receives the intent as well as information
used by the Android system.
An Intent object can contain the following components based on what it is communicating or going to perform −
Action
This is mandatory part of the Intent object and is a string naming the action to be performed — or, in the case of broadcast
intents, the action that took place and is being reported. The action largely determines how the rest of the intent object is
structured . The Intent class defines a number of action constants corresponding to different intents. Here is a list of Android
Intent Standard Actions
The action in an Intent object can be set by the setAction() method and read by getAction().
Data
Adds a data specification to an intent filter. The specification can be just a data type (the mimeType attribute), just a URI, or
both a data type and a URI. A URI is specified by separate attributes for each of its parts −
These attributes that specify the URL format are optional, but also mutually dependent −
If a scheme is not specified for the intent filter, all the other URI attributes are ignored.
If a host is not specified for the filter, the port attribute and all the path attributes are ignored.
The setData() method specifies data only as a URI, setType() specifies it only as a MIME type, and setDataAndType()
specifies it as both a URI and a MIME type. The URI is read by getData() and the type by getType().
Some examples of action/data pairs are −
[Link]. Action/Data Pair & Description
ACTION_VIEW content://contacts/people/1
1
Display information about the person whose identifier is "1".
ACTION_DIAL content://contacts/people/1
2
Display the phone dialer with the person filled in.
ACTION_VIEW [Link]
3
Display the phone dialer with the given number filled in.
ACTION_DIAL [Link]
4
Display the phone dialer with the given number filled in.
ACTION_EDIT content://contacts/people/1
5
Edit information about the person whose identifier is "1".
6 ACTION_VIEW content://contacts/people/
Display a list of people, which the user can browse through.
ACTION_SET_WALLPAPER
7
Show settings for choosing wallpaper
ACTION_SYNC
8
It going to be synchronous the data,Constant Value is [Link]
ACTION_SYSTEM_TUTORIAL
9
It will start the platform-defined tutorial(Default tutorial or start up tutorial)
ACTION_TIMEZONE_CHANGED
10
It intimates when time zone has changed
ACTION_UNINSTALL_PACKAGE
11
It is used to run default uninstaller
Category
The category is an optional part of Intent object and it's a string containing additional information about the kind of
component that should handle the intent. The addCategory() method places a category in an Intent object, removeCategory()
deletes a category previously added, and getCategories() gets the set of all categories currently in the object. Here is a list
of Android Intent Standard Categories.
You can check detail on Intent Filters in below section to understand how do we use categories to choose appropriate
activity corresponding to an Intent.
Extras
This will be in key-value pairs for additional information that should be delivered to the component handling the intent. The
extras can be set and read using the putExtras() and getExtras() methods respectively. Here is a list of Android Intent
Standard Extra Data
Flags
These flags are optional part of Intent object and instruct the Android system how to launch an activity, and how to treat it
after it's launched etc.
FLAG_ACTIVITY_CLEAR_TASK
If set in an Intent passed to [Link](), this flag will cause any existing task that would be
1 associated with the activity to be cleared before the activity is started. That is, the activity becomes the new
root of an otherwise empty task, and any old activities are finished. This can only be used in conjunction with
FLAG_ACTIVITY_NEW_TASK.
FLAG_ACTIVITY_CLEAR_TOP
2 If set, and the activity being launched is already running in the current task, then instead of launching a new
instance of that activity, all of the other activities on top of it will be closed and this Intent will be delivered to
the (now on top) old activity as a new Intent.
FLAG_ACTIVITY_NEW_TASK
3 This flag is generally used by activities that want to present a "launcher" style behavior: they give the user a list
of separate things that can be done, which otherwise run completely independently of the activity launching
them.
Component Name
This optional field is an android ComponentName object representing either Activity, Service or BroadcastReceiver class. If
it is set, the Intent object is delivered to an instance of the designated class otherwise Android uses other information in the
Intent object to locate a suitable target.
The component name is set by setComponent(), setClass(), or setClassName() and read by getComponent().
Types of Intents
There are following two types of intents supported by Android
Explicit Intents
Explicit intent going to be connected internal world of application,suppose if you wants to
connect one activity to another activity, we can do this quote by explicit intent, below
image is connecting first activity to second activity by clicking button.
These intents designate the target component by its name and they are typically used for
application-internal messages - such as an activity starting a subordinate service or
launching a sister activity. For example −
// Explicit Intent by specifying its class name
Intent i = new Intent([Link], [Link]);
// Starts TargetActivity
startActivity(i);
Implicit Intents
These intents do not name a target and the field for the component name is left blank.
Implicit intents are often used to activate components in other applications. For example −
Intent read1=new Intent();
[Link]([Link].ACTION_VIEW);
[Link]([Link].CONTENT_URI);
startActivity(read1);
Above code will give result as shown below
The target component which receives the intent can use the getExtras() method to get the
extra data sent by the source component. For example −
// Get bundle object at appropriate place in your code
Bundle extras = getIntent().getExtras();
// Extract data using passed keys
String value1 = [Link]("Key1");
String value2 = [Link]("Key2");
Example
Following example shows the functionality of a Android Intent to launch various Android built-in applications.
Step Description
1 You will use Android studio IDE to create an Android application and name it as My Application under a
package [Link].saira_000.myapplication.
2 Modify src/main/java/[Link] file and add the code to define two listeners corresponding two buttons
ie. Start Browser and Start Phone.
3 Modify layout XML file res/layout/activity_main.xml to add three buttons in linear layout.
4 Run the application to launch Android emulator and verify the result of the changes done in the application.
Following is the content of the modified main activity file src/[Link] Application/[Link].
package [Link].saira_000.myapplication;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class MainActivity extends AppCompatActivity {
Button b1,b2;
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
b1=(Button)findViewById([Link]);
[Link](new [Link]() {
@Override
public void onClick(View v) {
Intent i = new Intent([Link].ACTION_VIEW,
[Link]("[Link]
startActivity(i);
}
});
b2=(Button)findViewById([Link].button2);
[Link](new [Link]() {
@Override
public void onClick(View v) {
Intent i = new Intent([Link].ACTION_VIEW,
[Link]("[Link]
startActivity(i);
}
});
}
}
Following will be the content of res/layout/activity_main.xml file −
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Intent Example"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point"
android:textColor="#ff87ff09"
android:textSize="30dp"
android:layout_below="@+id/textView1"
android:layout_centerHorizontal="true" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton"
android:src="@drawable/abc"
android:layout_below="@+id/textView2"
android:layout_centerHorizontal="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:layout_below="@+id/imageButton"
android:layout_alignRight="@+id/imageButton"
android:layout_alignEnd="@+id/imageButton" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Browser"
android:id="@+id/button"
android:layout_alignTop="@+id/editText"
android:layout_alignRight="@+id/textView1"
android:layout_alignEnd="@+id/textView1"
android:layout_alignLeft="@+id/imageButton"
android:layout_alignStart="@+id/imageButton" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Phone"
android:id="@+id/button2"
android:layout_below="@+id/button"
android:layout_alignLeft="@+id/button"
android:layout_alignStart="@+id/button"
android:layout_alignRight="@+id/textView2"
android:layout_alignEnd="@+id/textView2" />
</RelativeLayout>
Following will be the content of res/values/[Link] to define two new constants −
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">My Applicaiton</string>
</resources>
Following is the default content of [Link] −
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="[Link]
package="[Link].saira_000.myapplication">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="[Link]" />
<category android:name="[Link]" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your My Application application. I assume you had created your AVD while doing environment setup. To
run the app from Android Studio, open one of your project's activity files and click Run icon from the [Link]
Studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display
following Emulator window −
Now click on Start Browser button, which will start a browser configured and display [Link] as shown
below −
Similar way you can launch phone interface using Start Phone button, which will allow you to dial already given phone
number.
Intent Filters
You have seen how an Intent has been used to call an another activity. Android OS uses filters to pinpoint the set of
Activities, Services, and Broadcast receivers that can handle the Intent with help of specified set of action, categories, data
scheme associated with an Intent. You will use <intent-filter> element in the manifest file to list down actions, categories
and data types associated with any activity, service, or broadcast receiver.
Following is an example of a part of [Link] file to specify an activity [Link]
[Link] which can be invoked by either of the two mentioned actions, one category, and one data −
<activity android:name=".CustomActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="[Link]" />
<action android:name="[Link] [Link]" />
<category android:name="[Link]" />
<data android:scheme="http" />
</intent-filter>
</activity>
Once this activity is defined along with above mentioned filters, other activities will be able to invoke this activity using
either the [Link], or using the [Link] [Link] action provided their category
is [Link].
The <data> element specifies the data type expected by the activity to be called and for above example our custom activity
expects the data to start with the "[Link]
There may be a situation that an intent can pass through the filters of more than one activity or service, the user may be
asked which component to activate. An exception is raised if no target can be found.
There are following test Android checks before invoking an activity −
A filter <intent-filter> may list more than one action as shown above but this list cannot be empty; a filter must
contain at least one <action> element, otherwise it will block all intents. If more than one actions are mentioned then
Android tries to match one of the mentioned actions before invoking the activity.
A filter <intent-filter> may list zero, one or more than one categories. if there is no category mentioned then
Android always pass this test but if more than one categories are mentioned then for an intent to pass the category
test, every category in the Intent object must match a category in the filter.
Each <data> element can specify a URI and a data type (MIME media type). There are separate attributes
like scheme, host, port, and path for each part of the URI. An Intent object that contains both a URI and a data type
passes the data type part of the test only if its type matches a type listed in the filter.
Example
Following example is a modification of the above example. Here we will see how Android resolves conflict if one intent
is invoking two activities defined in , next how to invoke a custom activity using a filter and third one is an exception
case if Android does not file appropriate activity defined for an intent.
Step Description
1 You will use android studio to create an Android application and name it as My Application under a
package [Link];.
2 Modify src/Main/Java/[Link] file and add the code to define three listeners corresponding to
three buttons defined in layout file.
3 Add a new src/Main/Java/[Link] file to have one custom activity which will be invoked by
different intents.
4 Modify layout XML file res/layout/activity_main.xml to add three buttons in linear layout.
5 Add one layout XML file res/layout/custom_view.xml to add a simple <TextView> to show the passed data
through intent.
6 Modify [Link] to add <intent-filter> to define rules for your intent to invoke custom activity.
7 Run the application to launch Android emulator and verify the result of the changes done in the application.
Following is the content of the modified main activity file src/[Link].
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class MainActivity extends AppCompatActivity {
Button b1,b2,b3;
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
b1=(Button)findViewById([Link]);
[Link](new [Link]() {
@Override
public void onClick(View v) {
Intent i = new Intent([Link].ACTION_VIEW,
[Link]("[Link]
startActivity(i);
}
});
b2 = (Button)findViewById([Link].button2);
[Link](new [Link]() {
@Override
public void onClick(View v) {
Intent i = new Intent("[Link].
[Link].
LAUNCH",[Link]("[Link]
startActivity(i);
}
});
b3 = (Button)findViewById([Link].button3);
[Link](new [Link]() {
@Override
public void onClick(View v) {
Intent i = new Intent("[Link].
My [Link]",
[Link]("[Link]
startActivity(i);
}
});
}
}
Following is the content of the modified main activity file src/[Link] Application/[Link].
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
/**
* Created by TutorialsPoint7 on 8/23/2016.
*/
public class CustomActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].custom_view);
TextView label = (TextView) findViewById([Link].show_data);
Uri url = getIntent().getData();
[Link]([Link]());
}
}
Following will be the content of res/layout/activity_main.xml file −
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="[Link]">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Intent Example"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point"
android:textColor="#ff87ff09"
android:textSize="30dp"
android:layout_below="@+id/textView1"
android:layout_centerHorizontal="true" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton"
android:src="@drawable/abc"
android:layout_below="@+id/textView2"
android:layout_centerHorizontal="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:layout_below="@+id/imageButton"
android:layout_alignRight="@+id/imageButton"
android:layout_alignEnd="@+id/imageButton" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Browser"
android:id="@+id/button"
android:layout_alignTop="@+id/editText"
android:layout_alignLeft="@+id/imageButton"
android:layout_alignStart="@+id/imageButton"
android:layout_alignEnd="@+id/imageButton" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start browsing with launch action"
android:id="@+id/button2"
android:layout_below="@+id/button"
android:layout_alignLeft="@+id/button"
android:layout_alignStart="@+id/button"
android:layout_alignEnd="@+id/button" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Exceptional condition"
android:id="@+id/button3"
android:layout_below="@+id/button2"
android:layout_alignLeft="@+id/button2"
android:layout_alignStart="@+id/button2"
android:layout_toStartOf="@+id/editText"
android:layout_alignParentEnd="true" />
</RelativeLayout>
Following will be the content of res/layout/custom_view.xml file −
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="[Link]
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView android:id="@+id/show_data"
android:layout_width="fill_parent"
android:layout_height="400dp"/>
</LinearLayout>
Following will be the content of res/values/[Link] to define two new
constants −
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">My Application</string>
</resources>
Following is the default content of [Link] −
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="[Link]
package="[Link]">
<application
android:allowBackup = "true"
android:icon = "@mipmap/ic_launcher"
android:label = "@string/app_name"
android:supportsRtl = "true"
android:theme = "@style/AppTheme">
<activity android:name = ".MainActivity">
<intent-filter>
<action android:name = "[Link]" />
<category android:name = "[Link]" />
</intent-filter>
</activity>
<activity android:name="[Link]">
<intent-filter>
<action android:name = "[Link]" />
<action android:name = "[Link]" />
<category android:name = "[Link]" />
<data android:scheme = "http" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your My Application application. I assume you had created your AVD while doing environment setup.
To run the app from Android Studio, open one of your project's activity files and click Run icon from the toolbar.
Android Studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it
will display following Emulator window −
Now let's start with first button "Start Browser with VIEW Action". Here we have defined our custom activity with a
filter "[Link]", and there is already one default activity against VIEW action defined by Android
which is launching web browser, So android displays following two options to select the activity you want to launch.
Now if you select Browser, then Android will launch web browser and open [Link] website but if you select
IndentDemo option then Android will launch CustomActivity which does nothing but just
capture passed data and displays in a text view as follows −
Now go back using back button and click on "Start Browser with LAUNCH Action" button,
here Android applies filter to choose define activity and it simply launch your custom activity
Again, go back using back button and click on "Exception Condition" button, here Android
tries to find out a valid filter for the given intent but it does not find a valid activity defined
because this time we have used data as https instead of http though we are giving a correct
action, so Android raises an exception and shows following screen −
Android - Event Handling
Events are a useful way to collect data about a user's interaction with interactive components of Applications. Like button
presses or screen touch etc. The Android framework maintains an event queue as first-in, first-out (FIFO) basis. You can
capture these events in your program and take appropriate action as per requirements.
There are following three concepts related to Android Event Management −
Event Listeners − An event listener is an interface in the View class that contains a single callback method. These
methods will be called by the Android framework when the View to which the listener has been registered is
triggered by user interaction with the item in the UI.
Event Listeners 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.
Event Handlers − When an event happens and we have registered an event listener for the event, the event listener
calls the Event Handlers, which is the method that actually handles the event.
Event Listeners & Event Handlers
Event Handler Event Listener & Description
OnClickListener()
onClick() This is called when the user either clicks or touches or focuses upon any widget like button, text,
image etc. You will use onClick() event handler to handle such event.
OnLongClickListener()
This is called when the user either clicks or touches or focuses upon any widget like button, text,
onLongClick()
image etc. for one or more seconds. You will use onLongClick() event handler to handle such
event.
OnFocusChangeListener()
onFocusChange() This is called when the widget looses its focus ie. user goes away from the view item. You will
use onFocusChange() event handler to handle such event.
OnFocusChangeListener()
onKey() This is called when the user is focused on the item and presses or releases a hardware key on the
device. You will use onKey() event handler to handle such event.
OnTouchListener()
onTouch() This is called when the user presses the key, releases the key, or any movement gesture on the
screen. You will use onTouch() event handler to handle such event.
OnMenuItemClickListener()
onMenuItemClick(
This is called when the user selects a menu item. You will use onMenuItemClick() event handler
)
to handle such event.
onCreateContextM onCreateContextMenuItemListener()
enu() This is called when the context menu is being built(as the result of a sustained "long click)
There are many more event listeners available as a part of View class like OnHoverListener, OnDragListener etc which may
be needed for your application. So I recommend to refer official documentation for Android application development in case
you are going to develop a sophisticated apps.
Event Listeners 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. Though there are several tricky ways to register your event listener for any
event, but I'm going to list down only top 3 ways, out of which you can use any of them based on the situation.
Using an Anonymous Inner Class
Activity class implements the Listener interface.
Using Layout file activity_main.xml to specify event handler directly.
Below section will provide you detailed examples on all the three scenarios −
Touch Mode
Users can interact with their devices by using hardware keys or buttons or touching the [Link] the screen puts the
device into touch mode. The user can then interact with it by touching the on-screen virtual buttons, images, [Link] can
check if the device is in touch mode by calling the View class‟s isInTouchMode() method.
Focus
A view or widget is usually highlighted or displays a flashing cursor when it‟s in focus. This indicates that it‟s ready to
accept input from the user.
isFocusable() − it returns true or false
isFocusableInTouchMode() − checks to see if the view is focusable in touch mode. (A view may be focusable when
using a hardware key but not when the device is in touch mode)
android:foucsUp="@=id/button_l"
onTouchEvent()
public boolean onTouchEvent(motionEvent event){
switch([Link]()){
case TOUCH_DOWN:
[Link](this,"you have clicked down Touch button",Toast.LENTH_LONG).show();
break();
case TOUCH_UP:
[Link](this,"you have clicked up touch button",Toast.LENTH_LONG).show();
break;
case TOUCH_MOVE:
[Link](this,"you have clicked move touch button"Toast.LENTH_LONG).show();
break;
}
return [Link](event) ;
}
1 You will use Android studio IDE to create an Android application and name it as myapplication under a
package [Link] as explained in the Hello World Example chapter.
2 Modify src/[Link] file to add click event listeners and handlers for the two buttons defined.
4 No need to declare default string [Link] studio takes care default constants.
5 Run the application to launch Android emulator and verify the result of the changes done in the aplication.
Following is the content of the modified main activity file src/[Link]/[Link]. This file can
include each of the fundamental lifecycle methods.
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class MainActivity extends ActionBarActivity {
private ProgressDialog progress;
Button b1,b2;
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
progress = new ProgressDialog(this);
b1=(Button)findViewById([Link]);
b2=(Button)findViewById([Link].button2);
[Link](new [Link]() {
@Override
public void onClick(View v) {
TextView txtView = (TextView) findViewById([Link]);
[Link](25);
}
});
[Link](new [Link]() {
@Override
public void onClick(View v) {
TextView txtView = (TextView) findViewById([Link]);
[Link](55);
}
});
}
}
Following will be the content of res/layout/activity_main.xml file −
Here abc indicates about tutorialspoint logo
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Event Handling "
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp"/>
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point "
android:textColor="#ff87ff09"
android:textSize="30dp"
android:layout_above="@+id/imageButton"
android:layout_centerHorizontal="true"
android:layout_marginBottom="40dp" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton"
android:src="@drawable/abc"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Small font"
android:id="@+id/button"
android:layout_below="@+id/imageButton"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Large Font"
android:id="@+id/button2"
android:layout_below="@+id/button"
android:layout_alignRight="@+id/button"
android:layout_alignEnd="@+id/button" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:id="@+id/textView"
android:layout_below="@+id/button2"
android:layout_centerHorizontal="true"
android:textSize="25dp" />
</RelativeLayout>
Following will be the content of res/values/[Link] to define two new
constants −
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">myapplication</string>
</resources>
Following is the default content of [Link] −
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="[Link]
package="[Link]" >
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="[Link]"
android:label="@string/app_name" >
<intent-filter>
<action android:name="[Link]" />
<category android:name="[Link]" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your myapplication application. I assume you had created your AVD while doing environment setup. To run
the app from Android Studio, open one of your project's activity files and click Run icon from the toolbar. Android
Studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display
following Emulator window −
Now you try to click on two buttons, one by one and you will see that font of the Hello World text will change, which
happens because registered click event handler method is being called against each click event.
Exercise
I will recommend to try writing different event handlers for different event types and understand exact difference in different
event types and their handling. Events related to menu, spinner, pickers widgets are little different but they are also based on
the same concepts as explained above.
INTENTS
We use intents to pass messages within apps and between apps. Intents allow us to interact with components from the same
application as well as with components contributed by other applications. For example, an activity can start another
activity(camera) for taking a picture. Intents can be created as shown below:
Intent intent=new Intent(getApplicationContext(), [Link]);
if(intent != null)
{
startActivity(intent);
}
MainActivity2 is the class name where we want to send the data and startActivity() is a method which is used to start the
new activity described by the intent.
BUNDLES
Yes! you are right, we use this word in our day to day life. The data of intent is described as a bundle. The bundle activity is
used to exchange data between two activities. It maps keys to values, we will put our data into a bundle and pass it to
another activity using intent and then get the data out of the bundle.
Creating and putting data into bundle.
Bundle b = new Bundle();
[Link]("key1", value1);
[Link]("key2", value2);
[Link]("key_n", value_n);
Putting bundle into the intent.
[Link](b);
So, here we combined lots of data in a bundle and put that data into an Intent to send it to another activity. We are now done
with sending data to MainActivity2 class. Now as the data has been send from one of the activity(MainActivity), there must
be some procedure to receive the data in MainActivity2. The procedure for receiving the data is shown below:
This code is written in [Link](Just for understanding, don't copy it)
Bundle b = getIntent().getExtras();
int data=[Link]((String) [Link]("key"));//for integer type data
String data=(String) [Link]("key");//for string type data
//mention the key corresponding to value you want.
Now we have collected sufficient information to understand the application and its working. We will understand it through a
simple android application.
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@+id/txtview2_page2"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
Copy the below code in [Link] file. See the file structure if you are having difficulties in finding the file.
[Link]
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="[Link]
package="[Link]" >
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="[Link]" />
<category android:name="[Link]" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity2"
android:label="@string/title_activity_main2" >
</activity>
</application>
</manifest>
Android ActionBar
Android ActionBar is a menu bar that runs across the top of the activity screen in android. Android ActionBar can contain
menu items which become visible when the user clicks the “menu” button. In general an ActionBar consists of the following
four components:
App Icon: App branding logo or icon will be displayed here
View Control: A dedicated space to display Application title. Also provides option to switch between views by
adding spinner or tabbed navigation
Action Buttons: Some important actions of the app can be added here
Action Overflow: All unimportant action will be shown as a menu
Android ActionBar Setting Up
All activities that use the theme [Link] or a theme derived from [Link] will automatically contain an ActionBar.
Android ActionBar Menu
The simplest way to get toolbar icons and action overflow items into the action bar is by creating menu XML resource file
found in res/menu folder. We can add menu items in the raw xml file present in the folder as follows: menu_main.xml
<menu xmlns:android="[Link]
xmlns:app="[Link]
xmlns:tools="[Link] tools:context=".MainActivity">
<item
android:id="@+id/add" android:icon="@android:drawable/ic_menu_add" app:showAsAction="always"
android:title="@string/add"/>
<item
android:id="@+id/reset" android:icon="@android:drawable/ic_menu_revert" app:showAsAction="always|withText"
android:title="@string/reset"/>
<item
android:id="@+id/about" android:icon="@android:drawable/ic_dialog_info" app:showAsAction="never"
android:title="@string/about">
</item>
<item
android:id="@+id/exit" app:showAsAction="never" android:title="@string/exit">
</item>
</menu>
There are four things that are needed to be configured for every menu item.
android:id: attribute specifies the id of the menu item. This works like ids anywhere else in the Android app. An
android:id value starting with a @+id/ will create a constant in the [Link] constant collection
android:title: attribute value contains the title of the menu item
android:icon: attribute references an icon in the drawable directories
android:showAsAction: This attribute indicates how the given item should be portrayed in the action bar. We can
choose from any of the flags mentioned below:
always to keep it in the ActionBar at all times
ifRoom to keep it only if space is available
never this means that the menu item will not be placed in the ActionBar as an icon. It will only be visible when the
menu button is clicked, in the menu that‟s popping up
|withText : we can append this to either always or ifRoom, to indicate that the toolbar button to be both the icon and
the title, not just the icon
Note that always is not guaranteed to be a toolbar button - if you ask for 100 always items, you will not have room for all of
them. However, always items get priority for space in the action bar over ifRoom items.
Below is the code to place a search icon, refresh icon, and an overflow menu in the ActionBar.
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="[Link]
xmlns:android="[Link]
<!-- action button for search -->
<item android:title="search"
android:id="@+id/search"
android:orderInCategory="100"
app:showAsAction="ifRoom"
android:icon="@drawable/search_icon"/>
<!-- action button for refresh -->
<item android:title="refresh"
android:id="@+id/refresh"
android:orderInCategory="100"
app:showAsAction="ifRoom"
android:icon="@drawable/refresh_icon"/>
<!-- action button for copy -->
<item android:title="copy"
android:id="@+id/copy"
android:orderInCategory="100"
app:showAsAction="never"
android:icon="@drawable/copy_icon"/>
</menu>
Step 3: Working with the Activity File
The items of an ActionBar is designed with a purpose to perform some operations. Those operations/actions of the items
are declared in that Activity file for which the ActionBar has been designed. In this example, the target activity is
the MainActivity file. Further, the custom title, subtitle, and application logo are also defined in this file. Below is the
proper code to design all mentioned items and to display a toast message when a user clicks on the items of ActionBar.
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate( Bundle savedInstanceState ) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
// calling this activity's function to
// use ActionBar utility methods
ActionBar actionBar = getSupportActionBar();
// providing title for the ActionBar
[Link](" GfG | Action Bar");
// providing subtitle for the ActionBar
[Link](" Design a custom Action Bar");
// adding icon in the ActionBar
[Link]([Link].app_logo);
// methods to display the icon in the ActionBar
[Link](true);
[Link](true);
}
// method to inflate the options menu when
// the user opens the menu for the first time
@Override
public boolean onCreateOptionsMenu( Menu menu ) {
getMenuInflater().inflate([Link], menu);
return [Link](menu);
}
// methods to control the operations that will
// happen when user clicks on the action buttons
@Override
public boolean onOptionsItemSelected( @NonNull
MenuItem item ) {
switch ([Link]()){
case [Link]:
[Link](this, "Search Clicked",
Toast.LENGTH_SHORT).show();
break;
case [Link]:
[Link](this, "Refresh Clicked",
Toast.LENGTH_SHORT).show();
break;
case [Link]:
[Link](this, "Copy Clicked",
Toast.LENGTH_SHORT).show();
break;
}
return [Link](item);
}
}
Step 4: Color of the ActionBar
Head over to [Link] file located in the values directory of the res folder. To change the default color of the ActionBar, one has to
change the colorPrimary resource. Below is the code to make the ActionBar color „green‟.
<resources>
<!-- Base application theme. -->
<style name="AppTheme"
parent="[Link]">
<!-- Customize your theme here. -->
<!-- provided green color to the ActionBar -->
<item name="colorPrimary">#0F9D58</item>
<item
name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
</resources>
Step 5: Working with activity_main.xml file
Advantages of ActionBar
Provides a customized area to design the identity of an app
Specify the location of the user in the app by displaying the title of the current Activity.
Provides access to important and frequently used actions
Support tabs and a drop-down list for view switching and navigation.
Disadvantages of ActionBar
All features of the ActionaBar are not introduced at once but were introduced with the release of different API
levels such as API 15, 17, and 19.
The ActionBar behaves differently when it runs on different API levels.
The features that were introduced with a particular API does not provide backward compatibility.
ANDROID APPLICATION
UNIT - IV
Android Fragments
Android Fragment is the part of activity, it is also known as sub-
activity. There can be more than one fragment in an activity.
Fragments represent multiple screen inside one activity.
Android fragment lifecycle is affected by activity lifecycle because
fragments are included in activity.
Each fragment has its own life cycle methods that is affected by
activity life cycle because fragments are embedded in activity.
The FragmentManager class is responsible to make interaction
between fragment objects.
Android Fragment Lifecycle
The lifecycle of android fragment is like the activity lifecycle. There
are 12 lifecycle methods for fragment. Figure: Androi d Fragment Lifecycle
Android Fragment Lifecycle Methods
No. Method Description
5) onViewStateRestored(Bundle) It provides information to the fragment that all the saved state
of fragment view hierarchy has been restored.
File: fragment_fragment2.xml
<FrameLayout xmlns:android="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#F0FFFF"
tools:context="[Link].Fragment2">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/hello_blank_fragment" />
</FrameLayout>
MainActivity class
File: [Link]
package [Link];
import [Link];
import [Link];
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
}
}
File: [Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class Fragment1 extends Fragment {
@Override
public void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return [Link]([Link].fragment_fragment1, container, false);
}
}
File: [Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class Fragment2 extends Fragment {
@Override
public void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return [Link]([Link].fragment_fragment2, container, false);
}
}
IMAGE VIEW
In Android, ImageView class is used to display an image file in application. Image file is easy to use but hard to master in
Android, because of the various screen sizes in Android devices. An android is enriched with some of the best UI design
widgets that allows us to build good looking and attractive UI based application.
Important Note: ImageView comes with different configuration options to support different scale types. Scale type
options are used for scaling the bounds of an image to the bounds of the imageview. Some of them scaleTypes
configuration properties are center, center_crop, fit_xy, fitStart etc. You can read our ScaleType tutorial to learn all details
on it.
Below is an ImageView code in XML:
Make sure to save lion image in drawable folder
<ImageView
android:id="@+id/simpleImageView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:src="@drawable/lion"/>
Table Of Contents
1 Attributes of ImageView:
2 Example of ImageView:
Attributes of ImageView:
Now let’s we discuss some important attributes that helps us to configure a ImageView in your xml file.
1. id: id is an attribute used to uniquely identify a image view in android. Below is the example code in which we set the id
of a image view.
<ImageView
android:id="@+id/simpleImageView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
2. src: src is an attribute used to set a source file or you can say image in your imageview to make your layout attractive.
Below is the example code in which we set the source of aimageview lion which is saved in drawable folder.
<ImageView
android:id="@+id/simpleImageView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:src="@drawable/lion"/><!--set the source of an image view-->
In Java:
We can also set the source image at run time programmatically in java class. For that we use setImageResource()
method as shown in below example code.
/*Add in Oncreate() funtion after setContentView()*/
ImageViewsimpleImageView=(ImageView)findViewById([Link]);
[Link]([Link]);//set the source in java class
3. background: background attribute is used to set the background of aImageView. We can set a color or a drawable in the
background of aImageView.
Below is the example code in which we set the black color in the background and an image in the src attribute of image
view.
<ImageView
android:id="@+id/simpleImageView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:src="@drawable/lion"
android:background="#000"/><!--black color in background of a image view-->
In Java:
We can also set the background at run time programmatically in java class. In below example code we set the black color
in the background of a image view.
/*Add in Oncreate() funtion after setContentView()*/
ImageViewsimpleImageView=(ImageView)findViewById([Link]);
[Link]([Link]);//set black color in background of a image view in java class
4. padding: padding attribute is used to set the padding from left, right, top or bottom of the Imageview.
paddingRight: set the padding from the right side of the image view.
paddingLeft: set the padding from the left side of the image view.
paddingTop: set the padding from the top side of the image view.
paddingBottom: set the padding from the bottom side of the image view.
padding: set the padding from the all side’s of the image view.
Below is the example code of padding attribute in which we set the 30dp padding from all the side’s of a image view.
<ImageView
android:id="@+id/simpleImageView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#000"
android:src="@drawable/lion"
android:padding="30dp"/><!--set 30dp padding from all the sides-->
5. scaleType: scaleType is an attribute used to control how the image should be re-sized or moved to match the size of this
image view. The value for scale type attribute can be fit_xy, center_crop, fitStart etc.
Below is the example code of scale type in which we set the scale type of image view to fit_xy.
<ImageView
android:id="@+id/simpleImageView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:src="@drawable/lion"
android:scaleType="fitXY"/><!--set scale type fit xy-->
Let’s we take an another example of scale type to understand the actual working of scale type in a image view.
In below example code we set the value for scale type “fitStart” which is used to fit the image in the start of the image
view as shown below:
<ImageView
android:id="@+id/simpleImageView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:src="@drawable/lion"
android:scaleType="fitStart"/><!--set scale type fit start of image view-->
Example of ImageView:
Below is the example of imageview in which we display two animal images of Lion and Monkey. And whenever user click
on an image Animal name is displayed as toast on
screen. Below is the final output and code:
Step 1: Create a new project and name it ImageViewExample.
In this step we create a new project in android studio by filling all the necessary details of
the app like app name, package name, api versions etc.
SelectFile->New->NewProjectandFill the forms and click "Finish" button.
Step 2: Download two images lion and monkey from the web. Now save those images in the
drawable folder of your project.
Step 3: Now open res -> layout -> activity_main.xml (or) [Link] and add following code:
In this step we add the code for displaying an image view on the screen in a relative layout. Here make sure you have
already saved two images name lion and monkey in your drawable folder.
<RelativeLayoutxmlns:android="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<ImageView
android:id="@+id/simpleImageViewLion"
android:layout_width="fill_parent"
android:layout_height="200dp"
android:scaleType="fitXY"
android:src="@drawable/lion"/>
<ImageView
android:id="@+id/simpleImageViewMonkey"
android:layout_width="fill_parent"
android:layout_height="200dp"
android:layout_below="@+id/simpleImageViewLion"
android:layout_marginTop="10dp"
android:scaleType="fitXY"
android:src="@drawable/monkey"/>
</RelativeLayout>
Step 4: Now open app -> java -> package -> [Link] and add the following code:
In this step we add the code to initiate the image view’s and then perform click event on them.
[Link];
[Link];
import [Link];
[Link];
[Link];
[Link];
[Link];
[Link];
[Link];
publicclassMainActivityextendsAppCompatActivity{
@Override
protectedvoidonCreate(BundlesavedInstanceState){
[Link](savedInstanceState);
setContentView([Link].activity_main);
ImageViewsimpleImageViewLion=(ImageView)findViewById([Link]);//get the id of first image view
ImageViewsimpleImageViewMonkey=(ImageView)findViewById([Link]);//get the id of second
image view
[Link]([Link](){
@Override
publicvoidonClick(View view){
[Link](getApplicationContext(),"Lion",Toast.LENGTH_LONG).show();//display the text on image click event
}
});
[Link]([Link](){
@Override
publicvoidonClick(View view){
[Link](getApplicationContext(),"Monkey",Toast.LENGTH_LONG).show();//display the text on image click event
}
});
}
}
Exception Handling in Java
The Exception Handling in Java is one of the powerful mechanism to handle the runtime errors so that the normal flow of
the application can be maintained.
In this tutorial, we will learn about Java exceptions, it's types, and the difference between checked and unchecked
exceptions.
What is Exception in Java?
Dictionary Meaning: Exception is an abnormal condition.
In Java, an exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime.
What is Exception Handling?
Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException, IOException, SQLException,
RemoteException, etc.
Advantage of Exception Handling
The core advantage of exception handling is to maintain the normal flow of the application. An exception normally disrupts
the normal flow of the application; that is why we need to handle exceptions. Let's consider a scenario:
1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;
Suppose there are 10 statements in a Java program and an exception occurs at statement 5; the rest of the code will not
be executed, i.e., statements 6 to 10 will not be executed. However, when we perform exception handling, the rest of the
statements will be executed. That is why we use exception handling in Java
.Hierarchy of Java Exception classes
The [Link] class is the root class of Java Exception hierarchy
inherited by two subclasses: Exception and Error. The hierarchy of Java
Exception classes is given below:
Keyword Description
try The "try" keyword is used to specify a block where we should place an exception code. It means we can't
use try block alone. The try block must be followed by either catch or finally.
catch The "catch" block is used to handle the exception. It must be preceded by try block which means we can't
use catch block alone. It can be followed by finally block later.
finally The "finally" block is used to execute the necessary code of the program. It is executed whether an
exception is handled or not.
throws The "throws" keyword is used to declare exceptions. It specifies that there may occur an exception in the
method. It doesn't throw an exception. It is always used with method signature.
public void setDataSource(String path) sets the data source (file path or http url) to use.
public void setLooping(boolean looping) sets the player for looping or non-looping.
public void selectTrack(int index) it selects a track for the specified index.
Activity class
Let's write the code of to play the audio file. Here, we are going to play maine.mp3 file located inside the sdcard/Music
directory.
File: [Link]
package [Link].audiomediaplayer1;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
MediaPlayermp=new MediaPlayer();
try{
[Link]("/sdcard/Music/maine.mp3");//Write your location here
[Link]();
[Link]();
}catch(Exception e){[Link]();}
}
@Override
public booleanonCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate([Link].activity_main, menu);
return true;
}
}
Android MediaPlayer Example of controlling the audio
Let's see a simple example to start, stop and pause the audio play.
activity_main.xml
Drag three buttons from pallete to start, stop and pause the audio play. Now the xml file will look like this:
<RelativeLayoutxmlns:androclass="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="30dp"
android:text="Audio Controller" />
<Button
android:id="@+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView1"
android:layout_marginTop="48dp"
android:text="start" />
<Button
android:id="@+id/button2"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/button1"
android:layout_toRightOf="@+id/button1"
android:text="pause" />
<Button
android:id="@+id/button3"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/button2"
android:layout_toRightOf="@+id/button2"
android:text="stop" />
</RelativeLayout>
Activity class
Let's write the code to start, pause and stop the audio player.
File: [Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class MainActivity extends Activity {
Button start,pause,stop;
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
start=(Button)findViewById([Link].button1);
pause=(Button)findViewById([Link].button2);
stop=(Button)findViewById([Link].button3);
//creating media player
final MediaPlayermp=new MediaPlayer();
try{
//you can change the path, here path is external directory(e.g. sdcard) /Music/maine.mp3
[Link]([Link]().getPath()+"/Music/maine.mp3");
[Link]();
}catch(Exception e){[Link]();}
[Link](new OnClickListener() {
@Override
public void onClick(View v) {
[Link]();
}
});
[Link](new OnClickListener() {
@Override
public void onClick(View v) {
[Link]();
}
});
[Link](new OnClickListener() {
@Override
public void onClick(View v) {
[Link]();
}
});
}
}
Method Description
public void setMediaController(MediaController sets the media controller to the video view.
controller)
public void setVideoURI (Uri uri) sets the URI of the video file.
VideoView class
The [Link] class provides methods to play and control the video player. The commonly used methods
of VideoView class are as follows:
activity_main.xml
Drag the VideoView from the pallete, now the activity_main.xml file will like this:
Play Videox
File: activity_main.xml
<RelativeLayoutxmlns:androclass="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<VideoView
android:id="@+id/videoView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true" />
</RelativeLayout>
Activity class
Let's write the code of to play the video file. Here, we are going to play 1.mp4 file located inside the sdcard/media
directory.
File: [Link]
package [Link].video1;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
VideoViewvideoView =(VideoView)findViewById([Link].videoView1);
//Creating MediaController
MediaControllermediaController= new MediaController(this);
[Link](videoView);
//specify the location of media file
Uri uri=[Link]([Link]().getPath()+"/media/1.mp4");
//Setting MediaController and URI, then starting the videoView
[Link](mediaController);
[Link](uri);
[Link]();
[Link]();
}
@Override
public booleanonCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate([Link].activity_main, menu);
return true;
}
}
Play video Intent in android
In my App I want that when user clicks a button, an intent should start and shows list of video players in the phone. By
choosing one of them a video should start to play. I use this code:
Intent intent = new Intent(Intent.ACTION_VIEW, [Link]([Link](path)));
[Link]([Link]([Link](path)), "video/mp4");
startActivity(intent);
With this code when I click on the button, MXPlayer started directly and plays video. In the end of video, My App closes
entirely! but I want to see a list of players and after end of video back to my App! How can I do this?
EDIT(Whole Code):
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_menu);
l_video.setOnClickListener(new [Link]() {
@Override
public void onClick(View view) {
String file_name="34743773";
File path = new File([Link]() + [Link] + "AAAAA"+ [Link]
+file_name+".mp4");
Intent intent = new Intent(Intent.ACTION_VIEW, [Link]([Link](path)));
[Link]([Link]([Link](path)), "video/*");
startActivity(intent);
}
});
}
}
play Mp3 Intent Android Studio
I have callintent() method in MainActivity:
public void callintent (View view){
Intent i = new Intent (this, [Link]);
[Link]("string", "String Text");
[Link]("img", [Link]);
startActivity(i);
}
that method is set string and image for DetailActivity
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_detail);
Intent i = getIntent();
String string = [Link]("string");
TextViewtextview = (TextView) findViewById([Link]);
[Link](string);
ImageViewimageView = (ImageView) findViewById([Link]);
[Link](getResources().getDrawable(getIntent().getIntExtra("img",0)));
}
i was successfuly display text and image in DetailActivity but now i want add mp3 file for play in DetailActivity where the
file is set in MainActivity,
Please Help Me, Thank you
-- Edited --
i can play mp3 with add this in MainActivity
[Link]("selectedMp3",[Link]);
and add this in DetailActivity
int mp3 = getIntent().getIntExtra("selectedMp3", 0);
final MediaPlayermp = [Link](this, mp3);
[Link]();
but sound still playing when backpress or go to homescreen, how can i stop sound when backpress or go to homescreen,
ANDROID APPLICATION
UNIT - V
Android SQLite Tutorial
SQLite is an open-source relational database i.e. used to perform database operations on android devices such as storing,
manipulating or retrieving persistent data from the database.
It is embedded in android bydefault. So, there is no need to perform any database setup or administration task.
Here, we are going to see the example of sqlite to store and fetch the data. Data is displayed in the logcat. For displaying
data on the spinner or listview, move to the next page.
SQLiteOpenHelper class
The [Link] class is used for database creation and version management. For
performing any database operation, you have to provide the implementation of onCreate() and onUpgrade() methods of
SQLiteOpenHelper class.
Constructors of SQLiteOpenHelper class
There are two constructors of SQLiteOpenHelper class.
Constructor Description
SQLiteOpenHelper(Context context, String name, creates an object for creating, opening and managing the
[Link] factory, int version) database.
SQLiteOpenHelper(Context context, String name, creates an object for creating, opening and managing the
[Link] factory, int version, database. It specifies the error handler.
DatabaseErrorHandlererrorHandler)
Method Description
public abstract void onCreate(SQLiteDatabasedb) called only once when database is created for the first time.
public abstract void onUpgrade(SQLiteDatabasedb, int called when database needs to be upgraded.
oldVersion, int newVersion)
SQLiteDatabase class
It contains methods to be performed on sqlite database such as create, update, delete, select etc.
Methods of SQLiteDatabase class
There are many methods in SQLiteDatabase class. Some of them are as follows:
Method Description
void execSQL(String sql) executes the sql query not select query.
long insert(String table, String inserts a record on the database. The table specifies the table
nullColumnHack, ContentValues values) name, nullColumnHack doesn't allow completely null values. If
second argument is null, android will store null values if values
are empty. The third argument specifies the values to be stored.
import [Link];
import [Link];
import [Link];
import [Link];
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
DatabaseHandler db = new DatabaseHandler(this);
// Inserting Contacts
Log.d("Insert: ", "Inserting ..");
[Link](new Contact("Ravi", "9100000000"));
[Link](new Contact("Srinivas", "9199999999"));
[Link](new Contact("Tommy", "9522222222"));
[Link](new Contact("Karthik", "9533333333"));
// Reading all contacts
Log.d("Reading: ", "Reading all contacts..");
List<Contact> contacts = [Link]();
for (Contact cn : contacts) {
String log = "Id: " + [Link]() + " ,Name: " + [Link]() + " ,Phone: " +
[Link]();
// Writing Contacts to log
Log.d("Name: ", log);
}
}
}
How to view the data stored in sqlite in android studio?
Follow the following steps to view the database and its data stored in android sqlite:
o Open File Explorer.
o Go to data directory inside data directory.
o Search for your application package name.
o Inside your application package go to databases where you will found
your database (contactsManager).
o Save your database (contactsManager) anywhere you like.
o Download any SqLite browser plugins or tool (in my case DB Browser
for SQLite).
o Launch DB Browser for SQLite and open your database
(contactsManager).
o Go to Browse Data -> select your table (contacts) you will see the
data stored.
CREATE
Create allows you to add new rows to your table. You can do that using the command, INSERT INTO. The
command starts with the INSERT INTO keyword, followed by the table name, column names, and the values to be
inserted.
When using INSERT INTO, you have two options:
INSERT INTO table_name
VALUES (value1, value2, value3, ...);
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
In the example below, we will add data to our bakery table.
INSERT INTO menu
VALUES (1, 'croissant', 1, '2020-12-16');
If we want to add multiple rows, we do that using:
INSERT INTO menu
VALUES
(2, 'bread', 3, '2020-12-16' ),
(3, 'eclairs', 2, '2020-12-16' );
This will add new rows to the menu table, and each entry will have a unique id.
READ
The read function is similar to a search function, as it allows you to retrieve specific records and read their values. Read
refers to SELECT
For example, let’s take a look at the items we sell at our bakery. To do that, we have to display all the data in our menu
table using:
SELECT * FROM menu;
This will not make any changes to the menu table but will simply display all the records in that table.
Take a look at this example to see how SELECT retrieves desired data:
IF OBJECT_ID('cusp_CustomerRead') IS NOT NULL
BEGIN
DROP PROC cusp_CustomerRead
END
GO
CREATE PROC cusp_CustomerRead
@CustomerID int
AS
BEGIN
SELECT CustomerID, FirstName, LastName, Email, PhoneNumber
FROM Customer
WHERE (CustomerID = @CustomerID)
END
GO
UPDATE
Update is how we change an existing record in the table. We can use this to modify existing records that exist in the
database. When performing UPDATE, you need to define the target table and columns to be updated. You also need the
associated values and sometimes the rows.
To update an existing record, use the following:
UPDATE table_name
SET column 1= value1, column 2= value2, ...
WHERE condition;
Let’s say we want to update the item name and price. We would use:
Let’s say we want to update the item name and price. We would use:
UPDATE menu
SET item_name = 'chocolate croissant', price = 2.5
WHERE item_id = 1;
This will update the table so that the previous record with id 1 will now be replaced with chocolate croissant with price 2.5.
This will update the table so that the previous record with id 1 will now be replaced with chocolate croissant with price 2.5.\
DELETE
Delete is used to remove a record from the table. SQL and has a built-in delete function for deleting one or more
records from the database at a time. Some relational database applications may permit a hard delete
(permanent delete) or soft delete (update row status).
The delete command is as follows:
DELETE FROM table_name WHERE condition;
If we want to remove one item from the table, we use:
DELETE FROM menu WHERE item_name='bread';
This will remove the row with the item bread from the table. If you want to delete all the records from the table,
you can use:
SDKs
Each SDK powered by Google Play services necessary APIs to interact with its respective service. Other APIs allow you to
resolve any issues at runtime, such as missing, disabled, or out-of-date services. If you are using Android Studio 3.4 or
higher and enable code shrinking, the R8 optimizer can help further reduce the footprint of each SDK and its impact on
your app's package size.
To access new Google Play services features or products, upgrade the SDK when a new version is released to the Google
Maven repository.
provides a lightweight client library that contains the
Services
Google Play services contains on-device Google services that run in the background on every Google-certified Android
device.
Automatic updates to Google Play services are delivered independent of carrier, OS, or OEM system image updates. In
general, devices running Android 4.4 or higher receive updates automatically, provided that these devices have Google
Play services installed and sufficient storage available. This means that users receive improvements and bug fixes more
quickly, and you can take advantage of the latest APIs while reaching most devices in the Android ecosystem. Devices
older than Android 4.4, or devices without Google Play services installed, aren't supported.