0% found this document useful (0 votes)
23 views109 pages

Android App Development Overview

Uploaded by

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

Android App Development Overview

Uploaded by

chhatarpur7113
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

ANDROID APPLICATION

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 Versions, Codename and API


Let's see the android versions, codenames and API Level provided by Google.

Version Code name API Level


1.5 Cupcake 3
1.6 Donut 4
2.1 Eclair 7
2.2 Froyo 8
2.3 Gingerbread 9 and 10
3.1 and 3.3 Honeycomb 12 and 13
4 Ice Cream Sandwitch 15
4.1, 4.2 and 4.3 Jelly Bean 16, 17 and 18
4.4 KitKat 19
5 Lollipop 21
6 Marshmallow 23
7 Nougat 24-25
8 Oreo 26-27
What is Android

Before learning all topics of android, it is required to know what is android.

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.

What is Open Handset Alliance (OHA)


It's a consortium of 84 companies such as google, samsung, AKM, synaptics, KDDI, Garmin, Teleca, Ebay, Intel etc.
It was established on 5th November, 2007, led by Google. It is committed to advance open standards, provide
services and deploy handsets using the Android Plateform.

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.

Categories of Android applications


There are many android applications in the market. The top categories are:
 Entertainment
 Tools
 Communication
 Productivity
 Personalization
 Music and Audio
 Social
 Media and Video
 Travel and Local 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.

Figure 1. Google Fit on Android Historical data


If you want users to be able to view fitness data from past activities, you can use the History API. This API provides access
to the historical health and wellness data and lets apps perform bulk operations, such as inserting, deleting, and reading
data.

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.

View and set goals


Your app can help motivate users by showing how their fitness activity compares to the goals that they've set. The Goals
API helps your app show users the health and fitness goals that they've created.

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

A comparison of Dalvik and ART architectures


Android 2.2 "Froyo" brought trace-based just-in-
time (JIT) compilation into Dalvik, optimizing the
execution of applications by
continually profiling applications each time they run
and dynamically compiling frequently executed
short segments of their bytecode into
native machine code. While Dalvik interprets the
rest of application's bytecode, native execution of
those short bytecode segments, called "traces",
provides significant performance improvements.[3][4]
Unlike Dalvik, ART introduces the use of ahead-of-
time (AOT) compilation by compiling entire
applications into native machine code upon their
installation. By eliminating Dalvik's interpretation and
trace-based JIT compilation, ART improves the overall
execution efficiency and reduces power consumption, which results in improved battery autonomy on mobile devices. At
the same time, ART brings faster execution of applications, improved memory allocation and garbage collection (GC)
mechanisms, new applications debugging features, and more accurate high-level profiling of applications.[2][5][6]
To maintain backward compatibility, ART uses the same input bytecode as Dalvik, supplied through standard .dex files as
part of APK files, while the .odex files are replaced with Executable and Linkable Format (ELF) executables. Once an
application is compiled by using ART's on-device dex2oat utility, it is run solely from the compiled ELF executable; as a
result, ART eliminates various application execution overheads associated with Dalvik's interpretation and trace-based JIT
compilation. A disadvantage of ART is that additional time is required for compilation when an application is installed, and
applications take up slightly more secondary storage (usually flash memory) to store the compiled code.
Android 4.4 "KitKat" brought a technology preview of ART, including it as an alternative runtime environment and
keeping Dalvik as the default virtual machine.[7][8] In the subsequent major Android release, Android 5.0 "Lollipop", Dalvik
was entirely replaced by ART.
Android 7.0 "Nougat" switched its Java Runtime Environment from the discontinued Apache Harmony to OpenJDK,
introducing a JIT compiler with code profiling to ART, which lets it constantly improve the performance of Android apps as
they run.[9] The JIT compiler complements ART's current ahead-of-time compiler and helps improve runtime performance,
and save storage space by only compiling some parts of the apps.[8][10]
Android 9 "Pie" reduced the amount of storage used by APKs by using compressed bytecode files, and profiler data can
be uploaded to Google Play servers to be bundled with apps when downloaded by users with a similar device.[11]
Android 13 ART will be updated with a new garbage collector (GC) utilizing the Linux userfaultfd system call.[12][13][14] It
reduces memory pressure, compiled code size, jank and prevents the risk of killing apps because of low memory during
GC.[14] Other changes also improve app startup, reduce jank and improve performance.[14] Because of the Mainline project,
Android 12 ART will also be updated.

Dalvik Virtual Machine | DVM


As we know the modern JVM is high performance and provides excellent memory management. But it needs to be
optimized for low-powered handheld devices as well.
The Dalvik Virtual Machine (DVM) is an android virtual machine optimized for mobile devices. It optimizes the virtual
machine for memory, battery life and performance.
Dalvik is a name of a town in Iceland. The Dalvik VM was written by Dan Bornstein.
The Dex compiler converts the class files into the .dex file that run on the Dalvik VM. Multiple class files are converted into
one dex file.
Let's see the compiling and packaging process from the source file:

The javac tool compiles the java source file into the
class file.

The dx tool takes all the class files of your application


and generates a single .dex file. It is a platform-
specific tool.

The Android Assets Packaging Tool (aapt) handles


the packaging process.

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.

3) Download and install the android SDK


First of all, download the android SDK
. In this example we have installed the android SDK for windows (.exe version).
Now double click on the exe file, it will be installed. I am using the android 2.2 version here.

4) Download the ADT plugin for eclipse


ADT (Android Development Tools) is required for developing the android application in the eclipse IDE. It is the plugin for
Eclipse IDE that is designed to provide the integrated environment.
For downloading the ADT, you need to follow these steps:
1) Start the eclipse IDE, then select Help > Install new software...
2) In the work with combo box, write [Link]
3) select the checkbox next to Developer Tools and click next
4) You will see, a list of tools to be downloaded here, click next
5) click finish
6) After completing the installation, restart the eclipse IDE
5) Configuring the ADT plugin
After the installing ADT plugin, now tell the eclipse IDE for your android
SDK location. To do so:
Select the Window menu > preferences
Now select the android from the left panel. Here you may see a dialog
box asking if you want to send the statistics to the google. Click proceed.
Click on the browse button and locate your SDK directory e.g. my SDK location is C:\Program Files\Android\android-sdk .
Click the apply button then OK.

6) Create an Android Virtual Device (AVD)


For running the android application in the Android Emulator, you need to create and AVD. For creating the AVD:
Select the Window menu > AVD Manager
Click on the new button, to create the AVD
Now a dialog appears, write the AVD name e.g. myavd. Now choose the target android version e.g. android2.2.
click the create AVD

7) create and run the simple android example


android apps
In this page, you will know how to create the simple hello android application. We are creating the simple example of
android using the Eclipse IDE. For creating the simple example:
Create the new android project
Write the message (optional)
Run the android application

Hello Android Example


You need to follow the 3 steps mentioned above for creating the Hello android application.
1) Create the New Android project
For creating the new android studio project:
1) Select Start a new Android Studio project
2) Provide the following information: Application name, Company domain, Project location and Package name of
application and click next.
3) Select the API level of application and click next.

4) Select the Activity type (Empty Activity).


5) Provide the Activity Name and click finish.
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:

2) Write the message


Android studio auto generates code for activity_main.xml file.
You may edit this file according to your requirement.
<?xml version="1.0" encoding="utf-8"?>
<[Link] xmlns:android=
"[Link]
xmlns:app="[Link]
auto"
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="[Link]
y">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello Android!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</[Link]>
}
package [Link];
import [Link];
import [Link];
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
}
}
3) Run the android application
To run the android application, click the run icon on the toolbar or simply press Shift + F10.

The android emulator might take 2 or 3 minutes to boot.


So please have patience. After booting the emulator, the
android studio installs the application and launches the
activity. You will see something like this:

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.

Requirement and recommendations


The Android emulator takes additional requirements beyond the basic system requirement for Android Studio. These
requirements are given below:
Hello Java Program for Beginners
SDK Tools 26.1.1 or higher
64-bit processor
Windows: CPU with UG (unrestricted guest) support
HAXM 6.2.1 or later (recommended HAXM 7.2.0 or later)
Install the emulator
The Android emulator is installed while installing the Android Studio. However some components of emulator may or may
not be installed while installing Android Studio. To install the emulator component, select the Android
Emulator component in the SDK Tools tab of the SDK Manager.
Run an Android app on the Emulator
We can run an Android app form the Android Studio project, or we can run an app which is installed on the Android
Emulator as we run any app on a device.
To start the Android Emulator and run an application in our project:
1. In Android Studio, we need to create an Android Virtual Device (AVD) that the emulator can use to install and run
your app. To create a new AVD:-
1.1 Open the AVD Manager by clicking Tools > AVD Manager.

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.

Launch the Emulator without first running an app


To start the emulator:
Open the AVD Manager.
Double-click an AVD, or click Run
While the emulator is running, we can run the Android Studio
project and select the emulator as the target device. We can
also drag an APKs file to install on an emulator, and then run
them.
Start the emulator from the command line
The Android SDK includes the Android device emulator.
Android emulator lets you develop and test out the application
without using a physical device.
Starting the emulator
Using the emulator command, we will start an emulator. It is an alternative to run our project or start through the AVD
Manager.
Here is the basic command-line syntax for starting a virtual device:
$ emulator -avd avd_name [ {-option [value]} ... ]
or
$ emulator @avd_name [ {-option [value]} ... ]
For example, if we execute the emulator from Android Studio on a Mac, the default command line will be similar as
follows:
$ /Users/user_name/Library/Android/sdk/emulator/emulator -avd Nexus_5X_API_23 -netdelay none -netspeed full
To display the list of AVD names, enter the following command:
$ emulator -list-avds
Run and stop an emulator, and clear data
From the Virtual Device page, we can perform the following operation on emulator:
To run an Android emulator that uses an AVD, double-click the AVD, or click Launch
To stop the running emulator, right-click and select Stop, or click Menu ▼and select Stop.
If we want to clear the data from an emulator and return it to the initial state when it was first defined, then right-click an
AVD and select Wipe Data. Or click menu ▼and select Wipe Data.
Sdkmanager
The sdkmanager is a command line tool that allows you to
view, install, update, and uninstall packages for the Android
SDK. If you're using Android Studio, then you do not 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, but for scripts, choose a specific version instead to ensure stability.
Usage
You can use the sdkmanager to perform the following tasks.
List installed and available packages
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
sdkmanager packages
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 (which includes adb and fastboot) 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, simply 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
Update all installed packages
sdkmanager --update [options]

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.

add one or multiple Google Accounts to your device


 If you haven't already, set up a Google account.
 Open your device's Settings app.
 Tap Accounts Add account Google.
 Follow the instructions to add your account.
 If needed, repeat steps to add multiple accounts.
Use & manage your accounts on the Google Play Store
Switch between accounts
You can add another Google Account to your device, if you have multiple accounts, and choose which account you're
using. These instructions will work for the Google Play apps.
Switch accounts in a Google Play app
 Open a Google Play app.
 At the top right, tap your profile picture or initial.
 Tap the Down arrow .
 Select an account.
Switch accounts on the Google Play website
Go to [Link]
In the top right, choose your profile icon.
Choose Switch account.
Select a different account.
If you can't find another account, tap Use another account.
Secure your account with recovery options
You can help protect your Google Account and your Google Play purchases by adding account recovery options, like
a backup email address or phone number. This helps us contact you if you ever forget your password or need help
with your account.
The Google Account Help Center has all the information you need to:
Set recovery email address and phone number.
Protect your account with 2-Step Verification.
Manage your account.

Fix account & sign in problems


If you can't sign in to the Google Play Store on your device or are having other account issues, you can get help with
account problems.

Install APK on Android


If you are an Android phone holder, you mostly download the apps for your device from Google Play Store. However,
third-party sources also offer Android apps in the form of an APK file to download and install. Installing an APK file in
Android is simple, but it requires doing some settings before installing APK on Android
. First of all, you have to prepare your device's settings to install the APK file from third-party sources. Second, download
the APK file on your Android smartphone. And finally, open the downloaded APK file to install on your device.

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.

Why Use an APK?


If you have ever installed an application from Google Play Store before, then this task unintentionally installed the
application's APK file in your Android device. Clicking on the green install button automatically transfer the APK file to your
Android phone from Google Play Store and runs it for you.

Best sites for APK download


Numerous web sources offer to download APK files, but be sure to select a trusted website. Some APK files may contain
suspicious software, which could be dangerous for the phone's security. Always try to avoid downloading and installing any
app outside the Google Play Store on your device.
Based on the user's review, some of the trusted sites to download APK files are [Link], [Link],
[Link], etc. But before downloading and installing an APK from any site, read some user's reviews and comments.
However, AKPMirror is one of the safest and trusted sites to download APK files on your device. APKMirror monitors the
files that you will not install any malware other than APK files, but not all sites give such a feature. You may also visit
APKPure for downloading and installing APK files.
Security of your device and data is a priority of these sites so that you can download APK files without worry about viruses
and malware files.
install an APK on your Android device
Before installing an app using an APK file other than Google Play Store, we have to ensure that our Android phone settings
are enabled to install third-party apps. It can be checked under the "Security" tab or the Setting menu. Generally, this
option says install from unknown sources or allows third-party installations. However, the newer Android versions of
phones are a little more different.

For Android 8 and above


The option (Settings) may slightly differ based on the device
version or device model.
On non-Samsung devices:
1. Launch your device's Settings
2. Tap on the security (& privacy)

3. Under the APP INSTALLATION section, click on Unknown source installations.


4. Select your preferred browser (such as Google Chrome or Mozilla Firefox) using which you want to download the APK
files.

5. Enable the toggle button that allows app installs.


On Samsung devices:
1. Launch your phone's Settings
2. Go to Biometrics and security and tap on the Install unknown apps
3. Select your preferred browser (Samsung Internet, Chrome or Firefox) using which you want to download the APK files.

4. Enable the toggle to installs apps.

For versions earlier than Android 8

1. Launch the device's Settings


2. Tap on the Security.
3. Under the Device administration section, toggle the Unknown sources

Install an Android File Manager


After the configuration of third-party app installation on an Android device, you also need to install a "File Manager" app.
It makes it easy to locate your APK file on your smartphone so that you can run it to install. There are several Android File
Manager
apps you will find on Google Play Store. Download one of them which you prefer more, and this app locates the APK file
once it is transferred to your phone.
The easiest way to download the APK Installer from your Android
One of the easiest ways to install an APK file on an Android device by downloading the installer files using your Android
browser.
1. Once you find the best website that offers Android APK files, it shows a link to download that particular APK file. Save
this file on your phone. You may see a warning message displaying "This type of file can harm your device," accept it.
2. Click on OK to proceed.
3. If your device browser doesn't allow opening a file just after downloading, open the file manager you installed and go to
the Downloads folder.
4. Tap on the APK file you downloaded to install. Allow the required app
permissions to install if asks. Now click on INSTALL.
5. You will see a confirmation when the app is installed successfully, and
your app is visible in your list of installed apps.
install APK Files from your computer
Visit a website on your computer that provides APK files for Android, search for
APK files, and download it to your PC.
Make sure that third-party apps installation is enabled on your Android device
(discussed above).
Now, connect your Android device with your computer via USB cable.
When you connect your Android device with a PC, it may ask whether you want to
charge your phone or connect to media or file transfer. Choose a file transfer
option.
Look for your phone's folder on your PC. It may be in the name of your phone's
name of PC suit under "My Computer" on Windows.
Copy the downloaded APK file from your computer to your Android device in your
chosen folder.
Using the file manager application, search for the APK file's location on your Android device.
Once you find the APK file, tap on it to install.
Newer versions of Android devices do set up activity slightly differently. Rather than the device setting to allow the
installation of APK files from unknown sources, they give a feature to allow your browser or file manager to install APK on
your device.

Set up your development environment


Follow the instructions on this page to set up the Privacy Sandbox on Android SDK in Android Studio.

Set up the Privacy Sandbox SDK


Note: It is recommended to use Android Studio Canary for testing Privacy Sandbox.
Within Android Studio, install the SDK as follows:
Install the latest Canary build or Stable build of Android Studio.
In Android Studio, go to Tools > SDK Manager.
In the SDK Platforms tab, select Android TiramisuPrivacySandbox Preview.
In the SDK Tools tab, select Android SDK Build-Tools 33.
Click OK to install the SDK.
Declare the correct API levels
To use the Privacy Preserving APIs that are part of the Privacy Sandbox on Android, declare your app's compile API level
and target API level as follows, based on your version of the Android Gradle plugin (AGP):
AGP 7.0.0 or higher:
compileSdkPreview "TiramisuPrivacySandbox"
targetSdkPreview "TiramisuPrivacySandbox"
AGP 4.2.0 or lower:
compileSdkVersion "android-TiramisuPrivacySandbox"
targetSdkVersion "android-TiramisuPrivacySandbox"
Get the Privacy Sandbox on Android on a supported 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.

Set up the Privacy Sandbox SDK


Note: It is recommended to use Android Studio Canary for testing Privacy Sandbox.
Within Android Studio, install the SDK as follows:
Install the latest Canary build or Stable build of Android Studio.
In Android Studio, go to Tools > SDK Manager.
In the SDK Platforms tab, select Android TiramisuPrivacySandbox Preview.
In the SDK Tools tab, select Android SDK Build-Tools 33.
Click OK to install the SDK.

Declare the correct API levels


To use the Privacy Preserving APIs that are part of the Privacy Sandbox on Android, declare your app's compile API level
and target API level as follows, based on your version of the Android Gradle plugin (AGP):
AGP 7.0.0 or higher:
compileSdkPreview "TiramisuPrivacySandbox"
targetSdkPreview "TiramisuPrivacySandbox"
AGP 4.2.0 or lower:
compileSdkVersion "android-TiramisuPrivacySandbox"
targetSdkVersion "android-TiramisuPrivacySandbox"

Get the Privacy Sandbox on Android on a supported 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.

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

Update all installed packages


To update all installed packages, use the following syntax:
sdkmanager --update [options]
Accept licenses
You are required to accept the necessary license for each package you have installed. This step occurs during the
installation flow when you install packages from within Android Studio.
If you don't have Android Studio installed, or it is for a CI server or other headless Linux device without a GUI installed, do
the following from the command-line:
sdkmanager--licenses
This prompts you to accept any licenses that haven't already been accepted.
Options
The following table lists the available options for the commands listed in the preceding section:

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.

--newer With --list, show only new or updatable packages.

--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}

CONFIGURE YOUR BUILD(ANDROID PROJECT STRUCTURE)


The Android build system compiles app resources and source code, and packages them into APKs or Android App Bundles
that you can test, deploy, sign, and distribute. Android Studio uses Gradle, an advanced build toolkit, to automate and
manage the build process, while allowing you to define flexible custom build configurations. Each build configuration can
define its own set of code and resources, while reusing the parts common to all versions of your app. The Android plugin
for Gradle works with the build toolkit to provide processes and configurable settings that are specific to building and
testing Android applications.
Gradle and the Android plugin run independent of Android Studio. This means that you can build your Android apps from
within Android Studio, the command line on your machine, or on machines where Android Studio is not installed (such as
continuous integration servers). If you are not using Android Studio, you can learn how to build and run your app from the
command line. The output of the build is the same whether you are building a project from the command line, on a
remote machine, or using Android Studio.
Note: Because Gradle and the Android plugin run independently from Android Studio, you need to update the build tools
separately. Read the release notes to learn how to update Gradle and the Android plugin.
The flexibility of the Android build system enables you to perform custom build configurations without modifying your
app's core source files. This section helps you understand how the Android build system works, and how it can help you
customize and automate multiple build configurations. If you simply want to learn more about deploying your app,
see Building and Running from Android Studio. To start creating custom build configurations right away using Android
Studio, see Configuring Build Variants.
The build process
The build process involves many tools and processes that convert your project into an Android Application Package (APK)
or Android App Bundle (AAB). The build process is very flexible, so it's useful to understand some of what is happening
under the hood.
The build process for a typical Android app module, as shown in
figure 1, follows these general steps:
The compilers convert your source code into DEX (Dalvik
Executable) files, which include the bytecode that runs on
Android devices, and everything else into compiled resources.
The packager combines the DEX files and compiled resources
into an APK or AAB, depending on the chosen build target.
Before your app can be installed onto an Android device or
distributed to a store, such as Google Play, the APK or AAB
must be signed.
The packager signs your APK or AAB using either the debug or
release keystore:
If you are building a debug version of your app, that is, an app
you intend only for testing and profiling, the packager signs
your app with the debug keystore. Android Studio
automatically configures new projects with a debug keystore.
If you are building a release version of your app that you intend
to release externally, the packager signs your app with the
release keystore that you need to configure. To create a release
keystore, read about signing your app in Android Studio.
Before generating your final APK, the packager uses
the zipalign tool to optimize your app to use less memory
Figure 1. The build process of a typical Android app module. when running on a device.

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.

Build configuration files


Creating custom build configurations requires you to make changes to one or more build configuration files,
or [Link] files. These plain text files use Domain Specific Language (DSL) to describe and manipulate the build
logic using Groovy, which is a dynamic language for the Java Virtual Machine (JVM). You don’t need to know
Groovy to start configuring your build because the Android plugin for Gradle introduces most of the DSL elements
you need. To learn more about the Android plugin DSL, read the DSL reference documentation.
When starting a new project, Android Studio automatically creates
some of these files for you, as shown in figure 2, and populates them
based on sensible defaults.

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.

The Gradle settings file


The [Link] file, located in the root project directory, defines
project-level repository settings and tells Gradle which modules it
should include when building your app. For most projects, the file looks
like the following by default:
Figure 2. The default project structure for an Android app module.

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.

The top-level build file


The top-level [Link] file, located in the root project directory, defines dependencies that apply to all modules in your
project. By default, the top-level build file uses the plugins block to define the Gradle dependencies that are common to all
modules in the project. In addition, the top-level build file contains code to clean your build directory. The following code
sample describes the default settings and DSL elements you can find in the top-level [Link] file after creating a new
project.
GroovyKotlin

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'])
}

Gradle properties files


Gradle also includes two properties files, located in your root project directory, that you can use to specify settings for the
Gradle build toolkit itself:
[Link]
This is where you can configure project-wide Gradle settings, such as the Gradle daemon's maximum heap size. For more
information, see The Build Environment.
[Link]
Configures local environment properties for the build system, including the following:
[Link] - Path to the NDK. This property has been deprecated. Any downloaded versions of the NDK will be installed in
the ndk directory within the Android SDK directory.
[Link] - Path to the SDK.
[Link] - Path to CMake.
[Link] - in Android Studio 3.5+, creates a symlink to the NDK that can be shorter than the installed NDK path.

Remap the NDK to a shorter path (Windows only)


The most common issue with Windows long paths is that tools (such as [Link]) in the installed NDK folder end up with very
deep paths, but the tools don't support long paths well.
In [Link], you can set the property [Link] to request that the Gradle plugin create a symlink to the NDK. The
path of that symlink can be shorter than the existing NDK folder. For example, [Link] = C:\ will result in the following
symlink: C:\ndk\19.0.5232133
Syncing project with Gradle files
When you make changes to the build configuration files in your project, Android Studio requires that you sync your project
files so that it can import your build configuration changes and run some checks to make sure your configuration won't
create build errors.
To sync your project files, click Sync Now in the notification bar that appears when you make a change, as shown in figure
3, or click Sync Project from the menu bar. If Android Studio notices any errors with your configuration, for
example, your source code uses API features that are only available in an API level higher than your compileSdkVersion,
the Messages window appears to describe the issue.

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.

CREATING HELLO ANDROID APP


In this page, you will know how to create the simple hello android application. We are creating the simple example of
android using the Eclipse IDE. For creating the simple example:
 Create the new android project
 Write the message (optional)
 Run the android application

HELLO ANDROID EXAMPLE


You need to follow the 3 steps mentioned above for creating the Hello android application.
1) Create the New Android project
For creating the new android studio project:
1) Select Start a new Android Studio project
2) Provide the following information: Application name, Company domain, Project location and Package name of application
and click next.
3) Select the API level of application and click next.
4) Select the Activity type (Empty Activity).
5) Provide the Activity Name and click finish.

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:

2) WRITE THE MESSAGE


Android studio auto generates code for activity_main.xml file. You may edit this file according to your requirement.
<?xml version="1.0" encoding="utf-8"?>
<[Link] xmlns:android="[Link]
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 Android!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</[Link]>
}
package [Link];
import [Link];
import [Link];
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
}
}

3) Run the android application


To run the android application, click the run icon on
the toolbar or simply press Shift + F10.

The android emulator might take 2 or 3 minutes to


boot. So please have patience. After booting the
emulator, the android studio installs the application
and launches the activity. You will see something like
this:

Run apps on a hardware device (Deploy it on USB-Connected Android Device)


When building an Android app, it's important that you always test your app on a real device before releasing it to users. This
page describes how to set up your development environment and Android device for testing and debugging over
an Android Debug Bridge (ADB) connection.
Note: Use the Android emulator to test your app on different versions of the Android platform and different screen sizes.
Also consider using Firebase Test Lab to run your app on a wide variety of real devices hosted in a cloud-based
infrastructure.
Set up a device for development
Before you can start debugging on your device, decide if you want to connect the device to using a USB cable or Wi-Fi. Then
do the following:
On the device, open the Settings app, select Developer options, and then enable USB debugging (if applicable).
Note: If you do not see Developer options, follow the instructions to enable developer options.
Set up your system to detect your device.
Chrome OS: No additional configuration required.
macOS: No additional configuration required.
Ubuntu Linux: There are two things that need to be set up correctly: each user that wants to use adb needs to be in the
plugdev group, and the system needs to have udev rules installed that cover the device.
plugdev group: If you see an error message that says you're not in the plugdev group, you'll need to add yourself to the
plugdev group:
sudousermod -aGplugdev $LOGNAME
Note that groups only get updated on login, so you'll need to log out for this change to take effect. When you log back in,
you can use id to check that you're now in the plugdev group.
udev rules: The android-sdk-platform-tools-common package contains a community-maintained default set of udev rules
for Android devices. To install:
apt-get install android-sdk-platform-tools-common
Windows: Install a USB driver for ADB (if applicable). For an installation guide and links to OEM drivers, see the Install OEM
USB drivers document.

Connect to your device using USB


When you are set up and plugged in over USB, you can click Run in Android Studio to build and run your
app on the device.
You can also use adb to issue commands, as follows:
Verify that your device is connected by running the adb devices command from your android_sdk/platform-
tools/ directory. If connected, you'll see the device listed.
Issue any adb command with the -d flag to target your device.

Connect to your device using Wi-Fi


Android 11 (and later) supports deploying and debugging your app wirelessly from your workstation via Android Debug
Bridge (adb). For example, you can deploy your debuggable app to multiple remote devices without physically connecting
your device via USB and contending with common USB connection issues, such as driver installation.
To use wireless debugging, you need to pair your device to your workstation using a pairing code. To begin, complete the
following steps:
Ensure that your workstation and device are connected to the same wireless network.
Ensure that your device is running Android 11 or higher. For more informaton, see Check & update your Android version.
Ensure that you have Android Studio Bumblebee Canary. You can download it here.
On your workstation, update to the latest version of the SDK Platform-Tools.
To connect to your device, follow these steps:
Open Android Studio and select Pair Devices Using Wi-Fi from the run configurations dropdown menu.

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

 Enable developer options on your device.


 Enable debugging over Wi-Fi on your device.
Tap on Wireless debugging and pair your device:
To pair your device with a QR code, select Pair device with QR code and scan the QR code obtained from above.
To pair your device with a pairing code, select Pair device with pairing code from the Pair devices over Wi-Fi window above.
On your device, select Pair using pairing code and take note of the six digit pin code. Once your device appears on the Pair
devices over Wi-Fi window, you can select Pair and enter the six digit pin code shown on your device.
setting on a Google Pixel phone.
After you are paired, you can attempt to deploy your app to your device.
To pair a different device or to forget this device on your workstation, navigate
to Wireless debugging on your device, tap on your workstation name under Paired
devices, and select Forget.
Troubleshoot device connection
If your device is not connecting to Android Studio, try the following to resolve the
issue.
Figure 4. Example of six digit pin code entry.
Troubleshoot with the Connection Assistant
The Connection Assistant provides step-by-step instructions to help you set up and use a device over the ADB connection.
To start the assistant, choose Tools >
Troubleshoot Device Connections.
The Connection Assistant provides instructions, in-context controls, and a list of connected devices in a series of pages in
the Assistant panel. Use the Next and Previous buttons at the bottom of the Assistant panel to work through the pages as
needed:
 Connect your device over USB:
The Connection Assistant begins by prompting you to connect your device over USB, and it provides a Rescan USB
devices button with which you can start a new scan for connected devices.
 Enable USB debugging:
The Connection Assistant then tells you how to enable USB debugging in the on-device developer options.
 Restart the ADB server:
 Finally, if you still don't see your device on the list of available devices, you can use the Restart ADB server button on the last
page of the Connection Assistant. Restarting the ADB server also causes ADB to scan for devices again. If you still don't see
your device on the list of available devices, try the troubleshooting steps in the next section of this page.
Resolve USB connection issues
 If the Connection Assistant is not detecting your device over USB, you can try the following troubleshooting steps to resolve
the issue:
 Check that Android Studio can connect to the Android EmulatorTo check if the issue is being caused by a connection
problem between Android Studio and the Android Emulator, follow these steps:
 Open the AVD Manager.
 Create a new AVD if you don't already have one.
 Run the emulator using your AVD.
 Do one of the following:
 If Android Studio can't connect to the emulator, download the latest SDK Platform Tools and then try again.
 If the emulator starts successfully, check the USB cable.
Check the USB cable
To check if the issue is being caused by a faulty USB cable, follow the steps in this section.
If you have another USB cable:
 Connect the device using the secondary cable.
 Check if the Connection Assistant can now detect the device.
 If the device is not detected, try the primary cable again.
 If the device still isn't detected, assume that the problem is with the device and check if the device is set up for
development.
If you don't have another USB cable but you do have another Android device:
 Connect the secondary device to your computer.
 If the Connection Assistant can detect the secondary device, assume that the problem is with the primary device
and check if the device is set up for development.
If the secondary device is not detected, the problem might be with the USB cable.
Check if the device is set up for development
To check if the issue is being caused by settings on the device, follow these steps:
 Follow the steps in the Set up a device for development section.
 If this does not resolve the problem, contact the device OEM's customer support for help. Tell the customer support
representative that the device won't connect to Android Studio using ADB.
Resolve wireless connection issues
If you are having issues connecting to your device wirelessly, you can try the following troubleshooting steps to resolve the issue.
Check if your workstation and device meet the prerequisites
To meet the prerequisites for wireless debugging, ensure that:
 Your workstation and device are connected to the same wireless network.
 Your device is running Android 11 or higher. For more information, see Check & update your Android version.
 You have Android Studio Bumblebee. You can download it here.
 You have the latest version of the SDK Platform Tools on your workstation.
Check for other known issues
The following is a list of current known issues with wireless debugging in Android Studio and how to resolve them.
 Wi-Fi is not connecting: Some Wi-Fi networks, such as corporate Wi-Fi networks, may block p2p connections and
not allow you to connect over Wi-Fi. Try connecting with a cable or another Wi-Fi network.
 ADB over Wi-Fi sometimes turns off automatically: This can happen if the device either switches Wi-Fi networks
or disconnects from the network.
RSA security key
When you connect a device running Android 4.2.2 (API level 17) or higher to your computer, the system shows a dialog asking
whether to accept an RSA key that allows debugging through this computer. This security mechanism protects user devices
because it ensures that USB debugging and other adb commands cannot be executed unless you're able to unlock the device
and acknowledge the dialog.

INSTALL OEM USB DRIVERS


If you are developing on Windows and want to connect a device for testing, then you need to install the appropriate USB driver.
This page provides links to the web sites for several original equipment manufacturers (OEMs), where you can download the
appropriate USB driver for your device.
If you're developing on Mac OS X or Linux, then you shouldn't need a USB driver. Instead read Using Hardware Devices.
To connect and debug with any of the Google Nexus devices using Windows, you need to install the Google USB driver.
Install a USB driver
First, find the appropriate driver for your device from the OEM drivers table below.
Once you've downloaded your USB driver, follow the instructions below to install or upgrade the driver, based on your version
of Windows and whether you're installing for the first time or upgrading an existing driver. Then see Using Hardware
Devices for other important information about using an Android device for development.
Caution: You may make changes to android_winusb.inf file found inside usb_driver\ (for example, to add support for
other devices), however, this will lead to security warnings when you install or upgrade the driver. Making any other
changes to the driver files may break the installation process.
Windows 10
To install the Android USB driver on Windows 10 for the first time, do the following:
 Connect your Android device to your computer's USB port.
 From Windows Explorer, open Computer Management.
 In the Computer Management left pane, select Device Manager.
 In the Device Manager right pane, locate and expand Portable Devices or Other Devices, depending on which one
you see.
 Right-click the name of the device you connected, and then select Update Driver Software.
 In the Hardware Update wizard, select Browse my computer for driver software and click Next.
 Click Browse and then locate the USB driver folder. For example, the Google USB Driver is located
in android_sdk\extras\google\usb_driver\.
 Click Next to install the driver.
Windows 8.1
To install the Android USB driver on Windows 8.1 for the first time, do the following:
 Connect your Android device to your computer's USB port.
 Access search, as follows:
Touch screen: On your computer, swipe in from the right edge of the screen and tap Search.
Using a mouse: Point to the lower-right corner of the screen, move the mouse pointer up, and then click Search.
 In the search box, type into and then click Device Manager.
 Double-click the device category, and then double-click the device you want.
 Click the Driver tab, click Update Driver, and follow the instructions.
Windows 7
To install the Android USB driver on Windows 7 for the first time, do the following:
 Connect your Android device to your computer's USB port.
 Right-click on Computer from your desktop or Windows Explorer, and select Manage.
 Select Devices in the left pane.
 Locate and expand Other device in the right pane.
 Right-click the device name (such as Nexus S) and select Update Driver Software. This will launch the Hardware
Update Wizard.
 Select Browse my computer for driver software and click Next.
 Click Browse and locate the USB driver folder. (The Google USB Driver is located
in android_sdk\extras\google\usb_driver\.)
 Click Next to install the driver.
Or, to upgrade an existing Android USB driver on Windows 7 and higher with the new driver:
 Connect your Android device to your computer's USB port.
 Right-click on Computer from your desktop or Windows Explorer, and select Manage.
 Select Device Manager in the left pane of the Computer Management window.
 Locate and expand Android Phone in the right pane.
 Right-click on Android Composite ADB Interface and select Update Driver. This will launch the Hardware Update
Wizard.
 Select Install from a list or specific location and click Next.
 Select Search for the best driver in these locations; uncheck Search removable media; and check Include this location
in the search.
 Click Browse and locate the USB driver folder. (The Google USB Driver is located
in android_sdk\extras\google\usb_driver\.)
 Click Next to upgrade the driver.
Get OEM drivers

OEM Driver URL

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]

ANDROID EMULATOR(SETINGUO AN EMULATOR)


The Android Emulator simulates Android devices on your computer so that you can test your application on a variety of
devices and Android API levels without needing to have each physical device. The emulator offers these advantages:
 Flexibility: In addition to being able to simulate a variety of devices and Android API levels, the emulator comes with
predefined configurations for various Android phone, tablet, Wear OS, and Android TV devices.
 High fidelity: The emulator provides almost all of the capabilities of a real Android device. You can simulate incoming
phone calls and text messages, specify the location of the device, simulate different network speeds, simulate rotation and
other hardware sensors, access the Google Play Store, and much more.
 Speed: Testing your app on the emulator is in some ways faster and easier than doing so on a physical device. For
example, you can transfer data faster to the emulator than to a device connected over USB.
In most cases, the emulator is the best options for your testing needs. This page covers the core emulator functionalities and
how to get started with it.
Alternatively, you can deploy your app to a physical device. For more information, see Run apps on a hardware device.
Get started with the emulator
The Android Emulator enables you to test your app on many different devices, virtually. The emulator comes with Android
Studio by default, so you shouldn’t have to manually install it. The basic workflow with the emulator goes as follows:
 Verify that you have the system requirements.
 Create an Android Virtual Device (AVD).
 Run your app on the emulator.
 Navigate the emulator.
This page covers the steps to set up and explore your virtual testing environment in more detail. If you already have your
app running on the emulator and are ready to use more advanced features, see Advanced emulator usage.
If you’re experiencing issues with the emulator, see Troubleshoot emulator. Depending on your needs and resources, it
might be worth delving into system requirements and technical configurations, or it might be better to use a physical device.

Emulator system requirements


For the best experience, you should use the emulator in Android Studio on a computer with the following specs:
 16GB RAM
 64-bit Windows, macOS, Linux, or ChromeOS operating system
 16GB disk space
Note: If you're using a ChromeOS operating system, check the devices that support the Android Emulator in the ChromeOS
documentation.
If you don’t have these specs, the emulator might still run, but it probably won’t be smooth. In this case, consider testing on
a physical device instead by following the guidance at Run apps on a hardware device.

Create an Android Virtual Device


Each instance of the Android Emulator uses an Android virtual device (AVD) to specify the Android version and hardware
characteristics of the simulated device. To effectively test your app, you should create an AVD that models each device on
which your app is designed to run. To create an AVD, see Create and manage virtual devices.
Each AVD functions as an independent device, with its own private storage for user data, SD card, and so on. By default, the
emulator stores the user data, SD card data, and cache in a directory specific to that AVD. When you launch the emulator, it
loads the user data and SD card data from the AVD directory.
Run your app on the emulator
After you have created an Android Virtual Device (AVD), you can start the Android Emulator and run an app in your project:
 In the toolbar, select the AVD that you want to run your app on from the target device drop-down menu.

 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.

Wear OS pairing assistant


If you want to test your app with Wear OS devices, the Wear OS pairing assistant
guides you step-by-step through pairing Wear OS emulators with physical or virtual phones directly in Android Studio. To
learn more, see Use the Wear OS emulator pairing assistant.
Navigate the emulator
While the emulator is running, you can use your computer mouse to mimic your finger on the touch screen, and use the
emulator panel to perform common actions.
Navigate the emulator screen
Use your computer mouse pointer to mimic your finger on the touchscreen; select menu items and input fields; and click
buttons and controls. Use your computer keyboard to type characters and enter emulator shortcuts.
Table 1. Gestures for navigating the emulator

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

Close Close the emulator.

Minimize Minimize the emulator window.

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.

Rotate left Rotate the device 90 degrees counterclockwise.

Rotate right Rotate the device 90 degrees clockwise.

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.

Home Return to the Home screen.

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.

Menu Press Control+M (Command+M on Mac) to simulate the Menu button.


More Click to access other features and settings, described in the next table.

Update the emulator


To update the Android Emulator, select the Android Emulator component in the SDK Tools tab of the SDK Manager. For
instructions, see Update your tools using the SDK Manager.

ANDROID [Link] FILE IN ANDROID ([Link] FILE)


The [Link] file contains information of your package, including components of the application such as
activities, services, broadcast receivers, content providers etc.
It performs some other tasks also:
 It is responsible to protect the application to access any protected parts by providing the permissions.
 It also declares the android api that the application is going to use.
 It lists the instrumentation classes. The instrumentation classes provides profiling and other informations. These
informations are removed just before the application is published etc.
This is the required xml file for all the android application and located inside the root directory.
A simple [Link] file looks like this:
<manifest xmlns:android="[Link]
package="[Link]"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/title_activity_main" >
<intent-filter>
<action android:name="[Link]" />
<category android:name="[Link]" />
</intent-filter>
</activity>
</application>
</manifest>
Elements of the [Link] file
The elements used in the above xml file are described below.
<manifest>
manifest is the root element of the [Link] file. It has package attribute that describes the package
name of the activity class.
<application>
application is the subelement of the manifest. It includes the namespace declaration. This element contains
several subelements that declares the application component such as activity etc.
The commonly used attributes are of this element are icon, label, theme etc.
android:icon represents the icon for all the android application components.
android:label works as the default label for all the application components.
android:theme represents a common theme for all the android activities.
<activity>
activity is the subelement of application and represents an activity that must be defined in the
[Link] file. It has many attributes such as label, name, theme, launchMode etc.
android:label represents a label i.e. displayed on the screen.
android:name represents a name for the activity class. It is required attribute.
<intent-filter>
intent-filter is the sub-element of activity that describes the type of intent to which activity, service or broadcast
receiver can respond to.
<action>
It adds an action for the intent-filter. The intent-filter must have at least one action element.
<category>
It adds a category name to an intent-filter.

Android Device Monitor(DDMS)

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.

VIEW ON-DEVICE FILES WITH DEVICE FILE EXPLORER(FILE EXPLORER)


The Device File Explorer allows you to view, copy, and delete files on an Android device. This is useful when examining files
that are created by your app or if you want to transfer files to and from a device.
To work with a device's file system, proceed as follows:
 Click View > Tool Windows > Device File Explorer or click the Device File Explorer button in the tool
window bar to open the Device File Explorer.
 Select a device from the drop down list.
 Interact with the device content in the file explorer window. Right-click on a file or directory to create a new file or
directory, save the selected file or directory to your machine, upload, delete, or synchronize. Double-click a file to
open it in Android Studio.
Android Studio saves files you open this way in a temporary directory outside of your project. If you make
modifications to a file you opened using the Device File Explorer, and would like to save your changes back to
the device, you must manually upload the modified version of the file to the
device.

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.)

ANDROID ACTIVITY LIFECYCLE & INTENTS

1. Android Activity Lifecycle

Android Activity Lifecycle is controlled by 7 methods of [Link] class. The


android Activity is the subclass of ContextThemeWrapper class.
An activity is the single screen in android. It is like window or frame of Java.
By the help of activity, you can place all your UI components or widgets in a single screen.
The 7 lifecycle method of Activity describes how activity will behave at different states.

2. Android Activity Lifecycle methods


Let's see the 7 lifecycle methods of android activity.
Method Description

onCreate called when activity is first created.

onStart called when activity is becoming visible to the user.

onResume called when activity will start interacting with the user.

onPause called when activity is not visible to the user.

onStop called when activity is no longer visible to the user.

onRestart called after your activity is stopped, prior to start.

onDestroy called before the activity is destroyed.

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]>

3. Android Activity Lifecycle Example


It provides the details about the invocation of life cycle methods of activity. In this example, we are displaying the
content on the logcat.
File: [Link]
package [Link];
import [Link];
import [Link];
import [Link];
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
Log.d("lifecycle","onCreate invoked");
}
@Override
protected void onStart() {
[Link]();
Log.d("lifecycle","onStart invoked");
}
@Override
protected void onResume() {
[Link]();
Log.d("lifecycle","onResume invoked");
}
@Override
protected void onPause() {
[Link]();
Log.d("lifecycle","onPause invoked");
}
@Override
protected void onStop() {
[Link]();
Log.d("lifecycle","onStop invoked");
}
@Override
protected void onRestart() {
[Link]();
Log.d("lifecycle","onRestart invoked");
}
@Override
protected void onDestroy() {
[Link]();
Log.d("lifecycle","onDestroy invoked");
}
}
Now see on the logcat: onCreate, onStart and onResume methods are invoked.
Now click on the HOME Button. You will see onPause method is invoked.
After a while, you will see onStop method is invoked.
Now see on the emulator. It is on the home. Now click on the center button to launch the app again.
Now click on the lifecycleactivity icon.
Now see on the logcat: onRestart, onStart and onResume methods are invoked.
If you see the emulator, application is started again.

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.

Types of Android Intents


There are two types of intents in android: implicit and explicit.
1) Implicit Intent
Implicit Intent doesn't specifiy the component. In such case, intent provides information of available components
provided by the system that is to be invoked.
For example, you may write the following code to view the webpage.
 Intent intent=new Intent(Intent.ACTION_VIEW);
 [Link]([Link]("[Link]
 startActivity(intent);
2) Explicit Intent
Explicit Intent specifies the component. In such case, intent provides the external class to be invoked.
 Intent i = new Intent(getApplicationContext(), [Link]);
 startActivity(i);
To get the full code of explicit intent, visit the next page.
Android Implicit Intent Example
Let's see the simple example of implicit intent that displays a web page.
activity_main.xml
File: activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<[Link] xmlns:android="[Link]
xmlns:app="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent" Output:
android:layout_height="match_parent"
tools:context="[Link]">
<EditText
android:id="@+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="60dp"
android:ems="10"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.575"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="8dp"
android:layout_marginLeft="156dp"
android:layout_marginTop="172dp"
android:text="Visit"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/editText" />
</[Link]>
Activity class
File: [Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class MainActivity extends AppCompatActivity {
Button button;
EditText editText;
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
button = findViewById([Link]);
editText = findViewById([Link]);
[Link](new [Link]() {
@Override
public void onClick(View view) {
String url=[Link]().toString();
Intent intent=new Intent(Intent.ACTION_VIEW, [Link](url));
startActivity(intent);
}
});
}
}

Android Explicit Intent Example


Android Explicit intent specifies the component to be invoked from activity. In other words, we can call another
activity in android by explicit intent.
We can also pass the information from one activity to another using explicit intent.
Here, we are going to see an example to call one activity from another and vice-versa.
Android calling one activity from another activity example
Let's see the simple example of android explicit example that calls one activity from another and vice versa.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<[Link] xmlns:android="[Link]
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:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="First Activity"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.454"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.06" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="392dp"
android:onClick="callSecondActivity"
android:text="Call second activity"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</[Link]>
ActivityOne class
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_first);
}
public void callSecondActivity(View view){
Intent i = new Intent(getApplicationContext(), [Link]);
[Link]("Value1", "Android By Javatpoint");
[Link]("Value2", "Simple Tutorial");
// Set the request code to any code you like, you can identify the
// callback via this code
startActivity(i);
}
}
activitytwo_main.xml
<?xml version="1.0" encoding="utf-8"?>
<[Link] xmlns:android="[Link]
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:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="Second Activity"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.454"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.06" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="392dp"
android:onClick="callFirstActivity"
android:text="Call first activity"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</[Link]>
ActivityTwo class
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class SecondActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_second);
Bundle extras = getIntent().getExtras();
String value1 = [Link]("Value1");
String value2 = [Link]("Value2");
[Link](getApplicationContext(),"Values are:\n First value: "+value1+
"\n Second Value: "+value2, Toast.LENGTH_LONG).show();
}
public void callFirstActivity(View view){
Intent i = new Intent(getApplicationContext(), [Link]);
startActivity(i);
}
}

Android StartActivityForResult Example


By the help of android startActivityForResult() method, we can get result from another activity.
By the help of android startActivityForResult() method, we can send information from one activity to another and vice-
versa. The android startActivityForResult method, requires a result from the second activity (activity to be invoked).
In such case, we need to override the onActivityResult method that is invoked automatically when second activity returns
result.
Method Signature
There are two variants of startActivityForResult() method.
1. public void startActivityForResult (Intent intent, int requestCode)
2. public void startActivityForResult (Intent intent, int requestCode, Bundle options)
Android StartActivityForResult Example
Let's see the simple example of android startActivityForResult method.
activity_main.xml
Drag one textview and one button from the pallete, now the xml file will look like this.
File: activity_main.xml
<RelativeLayout xmlns: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_alignLeft="@+id/button1"
android:layout_alignParentTop="true"
android:layout_marginTop="48dp"
android:text="Default Message" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="42dp"
android:text="GetMessage" />
</RelativeLayout>
second_main.xml
This xml file is created automatically when you create another activity. To create new activity Right click on the package
inside the src -> New -> Other ->Android Activity.
Now drag one editText, one textView and one button from the pallete, now the xml file will look like this:
File: second_main.xml
<RelativeLayout xmlns: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=".SecondActivity" >
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="61dp"
android:layout_toRightOf="@+id/textView1"
android:ems="10" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/editText1"
android:layout_alignBottom="@+id/editText1"
android:layout_alignParentLeft="true"
android:text="Enter Message:" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText1"
android:layout_centerHorizontal="true"
android:layout_marginTop="34dp"
android:text="Submit" />
</RelativeLayout>

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;
}
}

Android Share App Data (ACTION_SEND)


Android uses ACTION_SEND event of [Link] class to send data from one activity to another and from
current activity to outside the application. Intent class needs to specify the data and its type which is to be share.
Most commonly, ACTION_SEND action sends URL of build-in Browser app. While sharing the data, Intent
call createChooser() method which takes Intent object and specify the title of the chooser
dialog. [Link]() method allows to display the chooser.
Example of ACTION_SEND
In this example, we are going to share plain text which is a URL of browser.
activity_main.xml
<?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:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:id="@+id/textView" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Share App"
android:id="@+id/button"
android:layout_marginBottom="95dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
Activity class
File: [Link]
package [Link];

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.

Declaring component capabilities


As discussed above, in Activating components, you can use an Intent to start activities, services, and broadcast
receivers. You can use an Intent by explicitly naming the target component (using the component class name) in the
intent. You can also use an implicit intent, which describes the type of action to perform and, optionally, the data
upon which you‟d like to perform the action. The implicit intent allows the system to find a component on the
device that can perform the action and start it. If there are multiple components that can perform the action
described by the intent, the user selects which one to use.
Caution: If you use an intent to start a Service, ensure that your app is secure by using an explicit intent. Using an
implicit intent to start a service is a security hazard because you cannot be certain what service will respond to the
intent, and the user cannot see which service starts. Beginning with Android 5.0 (API level 21), the system throws
an exception if you call bindService() with an implicit intent. Do not declare intent filters for your services.
The system identifies the components that can respond to an intent by comparing the intent received to the intent
filters provided in the manifest file of other apps on the device.
When you declare an activity in your app's manifest, you can optionally include intent filters that declare the
capabilities of the activity so it can respond to intents from other apps. You can declare an intent filter for your
component by adding an <intent-filter> element as a child of the component's declaration element.
For example, if you build an email app with an activity for composing a new email, you can declare an intent filter
to respond to "send" intents (in order to send a new email), as shown in the following example:
<manifest ... >
...
<application ... >
<activity android:name="[Link]">
<intent-filter>
<action android:name="[Link]" />
<data android:type="*/*" />
<category android:name="[Link]" />
</intent-filter>
</activity>
</application>
</manifest>
If another app creates an intent with the ACTION_SEND action and passes it to startActivity(), the system may start
your activity so the user can draft and send an email.
For more about creating intent filters, see the Intents and Intent Filters document.
Declaring app requirements
There are a variety of devices powered by Android and not all of them provide the same features and capabilities.
To prevent your app from being installed on devices that lack features needed by your app, it's important that you
clearly define a profile for the types of devices your app supports by declaring device and software requirements in
your manifest file. Most of these declarations are informational only and the system does not read them, but external
services such as Google Play do read them in order to provide filtering for users when they search for apps from
their device.
For example, if your app requires a camera and uses APIs introduced in Android 8.0 (API Level 26), you must
declare these requirements.
The values for minSdkVersion and targetSdkVersion are set in your app module's [Link] file:
android {
...
defaultConfig {
...
minSdkVersion 26
targetSdkVersion 29
}
}
Note: Don't set minSdkVersion and targetSdkVersion directly in the manifest file, since they will be overwritten by
Gradle during the build process. For more information, see Specify API level requirements.
Declare the camera feature directly in your app's manifest file:
<manifest ... >
<uses-feature android:name="[Link]"
android:required="true" />
...
</manifest>

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:

[Link] Attribute & Description

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.

Constant Value Description

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);

Navigate Between Activities


Switching between pages in an application is one of the basic features of an app. We can
do that by adding few lines of code.
For that open android studio and create a new project.
create new project > Empty Activity >Next > Enter name of the project > Finish
Create two activies that we can navigate in using a button.
(We can navigate between pages using pretty much every element, not necessarily
button).
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<[Link]:android="[Link]
xmlns:app="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/page1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This Is the First Page"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</[Link]>
activity_main2.xml
<?xml version="1.0" encoding="utf-8"?>
<[Link]:android="[Link]
xmlns:app="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity2">
<Button
android:id="@+id/page2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This Is the Second Page"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</[Link]>
Don‟t forget to give id‟s to the buttons which we will need in [Link] file.
To navigate from activity_main.xml to activity_main2.xml we have to write the code in [Link] file.
We have to set an onClickListner to the element which we are going to use to navigate between pages (in this case button).
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class MainActivity extends AppCompatActivity {
Button b1 ;
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
b1 = findViewById([Link].page1);
[Link](
new [Link]() {
@Override
public void onClick(View v) {
Intent i = new Intent([Link],[Link]);
startActivity(i);
}
}
);

}
}
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.

[Link] Flags & Description

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) ;
}

Event Handling Examples


Event Listeners Registration Using an Anonymous Inner Class
Here you will create an anonymous implementation of the listener and will be useful if each class is applied to a single
control only and you have advantage to pass arguments to event handler. In this approach event handler methods can access
private data of Activity. No reference is needed to call to Activity.
But if you applied the handler to more than one control, you would have to cut and paste the code for the handler and if the
code for the handler is long, it makes the code harder to maintain.
Following are the simple steps to show how we will make use of separate Listener class to register and capture click event.
Similar way you can implement your listener for any other required event type.
Step Description

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.

3 Modify the detault content of res/layout/activity_main.xml file to include Android UI controls.

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.

EXCHANGING DATA BETWEEN ACTIVITIE


Basic Information
According to me, this concept forms a strong base in android
application development. Our application contains too many
screens or activities. You might need to pass data from one
activity to another activity. You might be thinking that this can be
done easily with the help of database. Just store the data into the
database and then extract it wherever required. That‟s right, but
think, is that right to always create a database for each and every
small fragment of data which you need to display on screen and
writing big codes in java class for extracting data which will
include opening and querying of database, extra time for searching
into the database, etc. Database plays important role when you
need to display large amount of data at a time.
This post will show you how to pass data between activities.
Follow the same procedure to create a new project as described
in first basic android application. The file structure will also be
similar to the previous project. Here we are using two activities to
exchange the data. I have named my project as “DataPassing”.
File structure

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.

Android Application : Exchanging data between activities


You might have created a blank project as per above given instructions. Now you have two activities- MainActivity and
MainActivity2. Copy the below code in [Link] class which you have created. This must be your first default
class after creating project.
[Link]
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class MainActivity extends AppCompatActivity
{
TextView txtview_data;
Button btn_send_data;
Bundle b=new Bundle();
String data="12345";
@Override
protected void onCreate(Bundle savedInstanceState)
{
[Link](savedInstanceState);
setContentView([Link].activity_main);
txtview_data=(TextView)findViewById([Link].txtview2_page1);
txtview_data.setText(data);
btn_send_data=(Button)findViewById([Link].btn_send);
btn_send_data.setOnClickListener(new [Link]()
{
public void onClick(View v)
{
Intent intent = new Intent([Link](), [Link]);
[Link]("datakey",data); //Here key=data1 and value=data
[Link](b); //putting bundle data into intent
startActivity(intent);
}
});
}
}
The code for activity_main.xml is given below.
activity_main.xml
<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:text="This is First Page"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/txtview1_page1" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click to send above data to MainActivity2"
android:id="@+id/btn_send"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/txtview2_page1"
android:layout_above="@+id/btn_send"
android:layout_centerHorizontal="true" />
</RelativeLayout>
The code for second activity is shown below.
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
public class MainActivity2 extends AppCompatActivity {
TextView txtview_comingdata;
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main2);
txtview_comingdata=(TextView)findViewById([Link].txtview2_page2);
Bundle b=getIntent().getExtras();
final String coming_data=(String) [Link]("datakey");// accessing the data by the same key
txtview_comingdata.setText(coming_data);
}
}
activity_main2.xml
<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="[Link].MainActivity2">

<TextView android:text="This is Second Page"


android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/txtview1_page2" />

<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.

Inflating the Menu Into the Android ActionBar


In order for the menu items defined in the menu XML file to be displayed, you need to inflate the menu file. We do so inside
the onCreateOptionsMenu() method of the activity where we wish to add the ActionBar. Here is the code snippet:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate([Link].menu_main, menu);
return true;
}
The [Link].menu_main parameter is the constant referring to the menu XML file. The menu parameter is the menu into
which we want to inflate the menu items.

Responding to Android Action Bar Events


To find out when the user taps on one of these things, we‟ll need to override onOptionsItemSelected() from the
MainActivity as shown below:
@Override
public boolean onOptionsItemSelected(MenuItem item) { switch([Link]()) {
case [Link]:
//add the function to perform here
return(true);
case [Link]:
//add the function to perform here
return(true);
case [Link]:
//add the function to perform here
return(true);
case [Link]:
//add the function to perform here
return(true);
}
return([Link](item));
}
Now let‟s assign some basic functions to each menu items in our project.
Project Structure

Android ActionBar Example Code


We‟ve implemented the four menu items in the MainActivity as shown in the snippet below: [Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class MainActivity extends AppCompatActivity {
TextView count;
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate([Link].menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) { switch([Link]()) {
case [Link]:
count=(TextView)findViewById([Link]);
[Link]("Add is clicked");
return(true);
case [Link]:
count=(TextView)findViewById([Link]);
[Link]("Nothing is selected");
return(true);
case [Link]:
[Link](this, [Link].about_toast, Toast.LENGTH_LONG).show();
return(true);
case [Link]:
finish();
return(true);
}
return([Link](item));
}
}
The items are assigned their respective functions. The item selected is determined from its id that was defined in
the menu_main.xml file. Here we just change the TextView contents in the first two items, display a toast in the third and
exit the application in the fourth item. Note that the AppCompatActivity is a replacement for the deprecated version
of ActionBarActivity. The [Link] file is defined as follows:
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="[Link]">
<!-- Customize your theme here. -->
</style>
</resources>
As you can see the parent theme uses a derivative of [Link] which holds an
ActionBar by default(unless you use [Link] class). Hence there
is no need to define it explicitly here.
Android Action Bar Backporting
 Since ActionBar was introduced after Android Honeycomb 3.0, to implement ActionBar
when minSdkVersion is 11 or less we need to import the app-compat-v7 jar into our
gradle as we have done here to enable backward compatibility
 Another way is to import and extend the MainActivity
with ActionBarSherlock independent of the action bar backport, since this class was
introduced after Android 3.0
Below image shows the output produced by our project, you can see that the ActionBar includes
the predefined icons. The textview updates the content since add icon was clicked. The textview
reverts he content to the original since reset was clicked. When about is clicked, toast notification appears as
ActionBar in Android with Example
In Android applications, ActionBar is the element present at the top of the activity screen. It is a salient feature of a mobile
application that has a consistent presence over all its activities. It provides a visual structure to the app and contains some of the
frequently used elements for the users. Android ActionBar was launched by Google in 2013 with the release of Android 3.0(API
11). Before that, the name of this top most visual element was AppBar. AppBar contains only the name of the application or
current activity. It was not very much useful for the users and developers also have negligible option to customize it.
Google announced a support library along with the introduction of ActionBar. This library is a part of AppCompat and its
purpose is to provide backward compatibility for older versions of Android and to support tabbed interfaces. All applications that
use the default theme provided by the Android([Link]), contains an ActionBar by default.
However, developers can customize it in several ways depending upon their needs. Components included in the ActionBar are:
 App Icon: Display the branding logo/icon of the application.
 View Controls: Section that displays the name of the application or current activity. Developers can also include spinner or
tabbed navigation for switching between views.
 Action Button: Contains some important actions/elements of the app that may be required to the users frequently.
 Action Overflow: Include other actions that will be displayed as a menu.
Designing a Custom ActionBar
The following example demonstrates the steps involved in creating a custom ActionBar for the MainActivity of an
application. All important aspects of visual elements like icon, title, subtitle, action buttons, and overflow menu will be
covered.
Note: Following steps are performed on Android Studio version 4.0
Step 1: Default ActionBar
As mentioned earlier, every android app contains an ActionBar by default. This pre-included ActionBar display title for the
current activity that is managed by the [Link] file. The string value of the application‟s title is provided
by @string/app_name resource present under the application nodes.
<application
…..
…..
android:label=”@string/app_name”
…..
</application>
Step 2: Creating a new directory and design items of ActionBar
To code the elements of ActionBar, create a new directory in the resource folder of the application project files. Right-click
on the res folder and selects New -> Directory. Give the name “menu” to the new directory.
Further, create a new Menu Resource File by right click on the menu directory. As the ActionBar is being created for the
main Activity, type the name as “main” to the Menu Resource File. With this, a new file named “[Link]” must be created
under the menu directory. In this file, one can declare the items which will be displayed as the action buttons of the
ActionBar.
For every menu items, the following attributes are needed to be configured:
 android:title: Its value contains the title of the menu item that will be displayed
when a user clicks and holds that item in the app.
 android:id: A unique ID for the menu item that will be used to access it anywhere
in the whole application files.
 android:orderInCategory: The value of this attribute specify the item‟s position in
the ActionBar. There are two ways to define the position of different menu items. The first one is to provide the
same value of this attribute for all items and the position will be defined in the same order as they are declared in the
code. The second way is to provide a different numeric value for all items and then the items will position
themselves according to ascending order of this attribute‟s value.
 app:showAsAction: This attribute defines how the item is going to be present in the action bar. There are four possible flags
to choose from:
 a. always: To display the item in the ActionBar all the time.
 b. ifRoom: To keep the item if space is available.
 c. never: With this flag, the item will be not be displayed as an icon in ActionBar, but will be present in the overflow
menu.
 d. withText: To represent an item as both icon and the title, one can append this flag with the always or ifRoom
flag(always|withText or ifRoom|withText).
 android:icon: The icon of an item is referenced in the drawable directories through this attribute.
Icon of an ActionBar Item
In order to provide an icon to an item, right-click on the res folder, select new, and then Image Asset. A dialog box will
appear, choose the Icon Type as Action Bar and Tab Icons. Choose assets type as “Clip Art” and select an image from
the clip art collection. Provide a desired name to the icon. Click on Next, then Finish. This icon will now get loaded in
the drawable directory of the res folder. The name provided by the developers to these icons will now be used to
reference the item‟s icon resource.

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

1) onAttach(Activity) it is called only once when it is attached with activity.

2) onCreate(Bundle) It is used to initialize the fragment.

3) onCreateView(LayoutInflater, creates and returns view hierarchy.


ViewGroup, Bundle)

4) onActivityCreated(Bundle) It is invoked after the completion of onCreate() method.

5) onViewStateRestored(Bundle) It provides information to the fragment that all the saved state
of fragment view hierarchy has been restored.

6) onStart() makes the fragment visible.

7) onResume() makes the fragment interactive.

8) onPause() is called when fragment is no longer interactive.

9) onStop() is called when fragment is no longer visible.

10) onDestroyView() allows the fragment to clean up resources.

11) onDestroy() allows the fragment to do final clean up of fragment state.

12) onDetach() It is called immediately prior to the fragment no longer being


associated with its activity.

Android Fragment Example


Let's have a look at the simple example of android fragment.
activity_main.xml
File: activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="[Link]
xmlns:app="[Link]
xmlns:tools="[Link]
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context="[Link]">
<fragment
android:id="@+id/fragment1"
android:name="[Link].Fragment1"
android:layout_width="0px"
android:layout_height="match_parent"
android:layout_weight="1"
/>
<fragment
android:id="@+id/fragment2"
android:name="[Link].Fragment2"
android:layout_width="0px"
android:layout_height="match_parent"
android:layout_weight="1"
/>
</LinearLayout>
File: fragment_fragment1.xml
<FrameLayout xmlns:android="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#F5F5DC"
tools:context="[Link].Fragment1">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/hello_blank_fragment" />
</FrameLayout>

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);
}
}

Thread Concept in Java


Before introducing the thread concept, we were unable to run more than one task in parallel. It was a drawback, and to
remove that drawback, Thread Concept was introduced.
A Thread is a very light-weighted process, or we can say the smallest part of the process that allows a program to
operate more efficiently by running multiple tasks simultaneously.
In order to perform complicated tasks in the background, we used the Thread concept in
Java. All the tasks are executed without affecting the main program. In a program or
process, all the threads have their own separate path for execution, so each thread of a
process is independent.
Another benefit of using thread is that if a thread gets an exception or an error at the time
of its execution, it doesn't affect the execution of the other threads. All the threads share a
common memory and have their own stack, local variables and program counter. When
multiple threads are executed in parallel at the same time, this process is known
as Multithreading
In a simple way, a Thread is a:
 Feature through which we can perform multiple activities within a single
process.
 Lightweight process.
 Series of executed statements.
 Nested sequence of method calls.
Thread Model
Just like a process, a thread exists in several states. These states are as follows:
1) New (Ready to run)
A thread is in New when it gets CPU time.
2) Running
A thread is in a Running state when it is under execution.
3) Suspended
A thread is in the Suspended state when it is temporarily inactive or under
execution.
4) Blocked
A thread is in the Blocked state when it is waiting for resources.
5) Terminated
A thread comes in this state when at any given time, it halts its execution
immediately.
Creating Thread
A thread is created either by "creating or implementing" the Runnable Interface or by extending the Thread class. These
are the only two ways through which we can create a thread.
Let's dive into details of both these way of creating a thread:
Thread Class
A Thread class has several methods and constructors which allow us to perform various operations on a thread. The
Thread class extends the Object class. The Object class implements the Runnable interface. The thread class has the
following constructors that are used to perform various operations.
 Thread()
 Thread(Runnable, String name)
 Thread(Runnable target)
 Thread(ThreadGroup group, Runnable target, String name)
 Thread(ThreadGroup group, Runnable target)
 Thread(ThreadGroup group, String name)
 Thread(ThreadGroup group, Runnable target, String name, long stackSize)
Runnable Interface(run() method)
The Runnable interface is required to be implemented by that class whose instances are intended to be executed by a
thread. The runnable interface gives us the run() method to perform an action for the thread.
start() method
The method is used for starting a thread that we have newly created. It starts a new thread with a new callstack. After
executing the start() method, the thread changes the state from New to Runnable. It executes the run() method when the
thread gets the correct time to execute it.
Let's take an example to understand how we can create a Java
thread by extending the Thread class:
[Link]
// Implementing runnable interface by extending Thread class
public class ThreadExample1 extends Thread {
// run() method to perform action for thread.
public void run()
{
int a= 10;
int b=12;
int result = a+b;
[Link]("Thread started running..");
[Link]("Sum of two numbers is: "+ result);
}
public static void main( String args[] )
{
// Creating instance of the class extend Thread class
ThreadExample1 t1 = new ThreadExample1();
//calling start method to execute the run() method of the Thread class
[Link]();
}
}
Creating thread by implementing the runnable interface
In Java, we can also create a thread by implementing the runnable interface. The runnable interface provides us both the
run() method and the start() method.
Let's takes an example to understand how we can create, start and run the thread using the runnable interface.
[Link]
class NewThread implements Runnable {
String name;
Thread thread;
NewThread (String name){
[Link] = name;
thread = new Thread(this, name);
[Link]( "A New thread: " + thread+ "is created\n" );
[Link]();
}
public void run() {
try {
for(int j = 5; j > 0; j--) {
[Link](name + ": " + j);
[Link](1000);
}
}catch (InterruptedException e) {
[Link](name + " thread Interrupted");
}
[Link](name + " thread exiting.");
}
}
class ThreadExample2 {
public static void main(String args[]) {
new NewThread("1st");
new NewThread("2nd");
new NewThread("3rd");
try {
[Link](8000);
} catch (InterruptedException excetion) {
[Link]("Inturruption occurs in Main Thread");
}
[Link]("We are exiting from Main Thread");
}
}

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:

Types of Java Exceptions


There are mainly two types of
exceptions: checked and
unchecked. An error is
considered as the unchecked
exception. However, according
to Oracle, there are three types
of exceptions namely:
 Checked Exception
 Unchecked Exception
 Error
Difference between Checked and Unchecked Exceptions
1) Checked Exception
The classes that directly inherit the Throwable class except RuntimeException and Error are known as checked exceptions.
For example, IOException, SQLException, etc. Checked exceptions are checked at compile-time.
2) Unchecked Exception
The classes that inherit the RuntimeException are known as unchecked exceptions. For example, ArithmeticException,
NullPointerException, ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked at compile-time, but
they are checked at runtime.
3) Error
Error is irrecoverable. Some example of errors areOutOfMemoryError, VirtualMachineError, AssertionError etc.
Java Exception Keywords
Java provides five keywords that are used to handle the exception. The following table describes each.

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.

throw The "throw" keyword is used to throw an exception.

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.

Java Exception Handling Example


Let's see an example of Java Exception Handling in which we are using a try-catch statement to handle the exception.
[Link]
public class JavaExceptionExample{
public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){[Link](e);}
//rest code of the program
[Link]("rest of the code...");
}
}
Common Scenarios of Java Exceptions
There are given some scenarios where unchecked exceptions may occur. They are as follows:
1) A scenario where ArithmeticException occurs
If we divide any number by zero, there occurs an ArithmeticException.
int a=50/0;//ArithmeticException
2) A scenario where NullPointerException occurs
If we have a null value in any variable
, performing any operation on the variable throws a NullPointerException.
 String s=null;
 [Link]([Link]());//NullPointerException
 3) A scenario where NumberFormatException occurs
If the formatting of any variable or number is mismatched, it may result into NumberFormatException. Suppose we have
a string
variable that has characters; converting this variable into digit will cause NumberFormatException.
 String s="abc";
 int i=[Link](s);//NumberFormatException
 4) A scenario where ArrayIndexOutOfBoundsException occurs
When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs. there may be other reasons to occur
ArrayIndexOutOfBoundsException. Consider the following statements.
1. int a[]=new int[5];
2. a[10]=50; //ArrayIndexOutOfBoundsException

Android Media Player Example


We can play and control the audio files in android by the help of MediaPlayer class.
Here, we are going to see a simple example to play the audio file. In the next page, we will see the example to control the
audio playback like start, stop, pause etc.
MediaPlayer class
The [Link] class is used to control the audio or video files.
Methods of MediaPlayer class
There are many methods of MediaPlayer class. Some of them are as follows:
Method Description

public void setDataSource(String path) sets the data source (file path or http url) to use.

public void prepare() prepares the player for playback synchronously.

public void start() it starts or resumes the playback.

public void stop() it stops the playback.

public void pause() it pauses the playback.

public booleanisPlaying() checks if media player is playing.

public void seekTo(int millis) seeks to specified time in miliseconds.

public void setLooping(boolean looping) sets the player for looping or non-looping.

public booleanisLooping() checks if the player is looping or non-looping.

public void selectTrack(int index) it selects a track for the specified index.

public int getCurrentPosition() returns the current playback position.

public int getDuration() returns duration of the file.

public void setVolume(float sets the volume on this player.


leftVolume,floatrightVolume)

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.

public void start() starts the video view.

public void stopPlayback() stops the playback.

public void pause() pauses the playback.

public void suspend() suspends the playback.

public void resume() resumes the playback.

public void seekTo(int millis) seeks to specified time in miliseconds.


Android Video Player Example
By the help of MediaController and VideoView classes, we can play the video files in android.
MediaController class
The [Link] is a view that contains media controls like play/pause, previous, next, fast-forward,
rewind etc.

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):

public class MenuActivity extends ActionBarActivity {

@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)

Methods of SQLiteOpenHelper class


There are many methods in SQLiteOpenHelper class. Some of them are as follows:

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)

public synchronized void close () closes the database object.

public void onDowngrade(SQLiteDatabasedb, int called when database needs to be downgraded.


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.

int update(String table, ContentValues updates a row.


values, String whereClause, String[]
whereArgs)
Cursor query(String table, String[] columns, returns a cursor over the resultset.
String selection, String[] selectionArgs,
String groupBy, String having, String
orderBy)

Example of android SQLite database


Let's see the simple example of android sqlite database.
package [Link];
public class Contact {
int _id;
String _name;
String _phone_number;
public Contact(){ }
public Contact(int id, String name, String _phone_number){
this._id = id;
this._name = name;
this._phone_number = _phone_number;
}
public Contact(String name, String _phone_number){
this._name = name;
this._phone_number = _phone_number;
}
public int getID(){
return this._id;
}
public void setID(int id){
this._id = id;
}
public String getName(){
return this._name;
}
public void setName(String name){
this._name = name;
}
public String getPhoneNumber(){
return this._phone_number;
}
public void setPhoneNumber(String phone_number){
this._phone_number = phone_number;
}
}
Now, let's create the database handler class that extends SQLiteOpenHelper class and provides the
implementation of its methods.
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "contactsManager";
private static final String TABLE_CONTACTS = "contacts";
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_PH_NO = "phone_number";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
//3rd argument to be passed is CursorFactory instance
}
// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_PH_NO + " TEXT" + ")";
[Link](CREATE_CONTACTS_TABLE);
}
// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
[Link]("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// Create tables again
onCreate(db);
}
// code to add the new contact
void addContact(Contact contact) {
SQLiteDatabase db = [Link]();
ContentValues values = new ContentValues();
[Link](KEY_NAME, [Link]()); // Contact Name
[Link](KEY_PH_NO, [Link]()); // Contact Phone
// Inserting Row
[Link](TABLE_CONTACTS, null, values);
//2nd argument is String containing nullColumnHack
[Link](); // Closing database connection
}
// code to get the single contact
Contact getContact(int id) {
SQLiteDatabase db = [Link]();
Cursor cursor = [Link](TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
new String[] { [Link](id) }, null, null, null, null);
if (cursor != null)
[Link]();
Contact contact = new Contact([Link]([Link](0)),
[Link](1), [Link](2));
// return contact
return contact;
}
// code to get all contacts in a list view
public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = [Link]();
Cursor cursor = [Link](selectQuery, null);
// looping through all rows and adding to list
if ([Link]()) {
do {
Contact contact = new Contact();
[Link]([Link]([Link](0)));
[Link]([Link](1));
[Link]([Link](2));
// Adding contact to list
[Link](contact);
} while ([Link]());
}
// return contact list
return contactList;
}
// code to update the single contact
public int updateContact(Contact contact) {
SQLiteDatabase db = [Link]();
ContentValues values = new ContentValues();
[Link](KEY_NAME, [Link]());
[Link](KEY_PH_NO, [Link]());
// updating row
return [Link](TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { [Link]([Link]()) });
}
// Deleting single contact
public void deleteContact(Contact contact) {
SQLiteDatabase db = [Link]();
[Link](TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { [Link]([Link]()) });
[Link]();
}
// Getting contacts Count
public int getContactsCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = [Link]();
Cursor cursor = [Link](countQuery, null);
[Link]();
// return count
return [Link]();
}
}
File: [Link]
package [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);
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.

WHAT ARE CRUD OPERATIONS?


Any organizations that tracks data (like accounts, payment information, or other records) need systems that
provide persistent storage, which is usually organized into a database. A relational database consists of data
organized by rows and columns. They can be connected to other tables using primary and foreign keys.
CRUD (create, read, update, delete) is an acronym that refers to the four functions we use to implement
persistent storage applications and relational database applications, including the Oracle Database, Microsoft
SQL Server, and MySQL.
The table below summarizes what each CRUD operation means.

Why is CRUD so important?


CRUD is constantly used for anything related to database
Letter Operation Function and database design. Software developers can’t get anything done
without CRUD operations. Website development, for example, uses
REST (Representational State Transfer), which is a superset of CRUD
C Create Insert
used for HTTP resources.
On the other end, CRUD is just as important for end-users. Without it,
R Read Select things like registering for websites, creating blogs, or bookmarks
would be impossible. Most applications we use let us add or create
new entries, search for existing ones, make changes to them or
U Update Edit delete them.

D Delete Delete CRUD offers many benefits including:


 It facilitates security control by satisfying the various access
requirements
 It simplifies and facilitates application design making it more scalable
 It has better performance compared to ad-hoc SQL statements

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.

Keep the learning going.


Learn SQL without scrubbing through videos or documentation. Educative’s text-based courses are easy to skim and feature
live coding environments, making learning quick and efficient.

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:

DELETE FROM menu;


Android ListView
Android ListView is a view which contains the group of items and displays in a scrollable list. ListView is
implemented by importing [Link] class. ListView is a default scrollable which does not use
other scroll view.
ListView uses Adapter classes which add the content from data source (such as string array, array, database etc)
to ListView. Adapter bridges data between an AdapterViews and other Views (ListView, ScrollView etc).
Example of ListView
Let's implement a simple listview example.
Structure of listview project
Play Videox
android Listview1
activity_main.xml
First we need to drag and drop ListView component from palette to activity_main.xml file.
File: activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<[Link]:android="[Link]
xmlns:app="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="[Link]">
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="fill_parent"
/>
</[Link]>
Create an additional [Link] file in layout folder which contains view components displayed in listview.
[Link]
File: [Link]
<?xml version="1.0" encoding="utf-8"?>
<TextViewxmlns:android="[Link]
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textStyle="bold"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:padding="2dp"
android:textColor="#4d4d4d"
/>
Now place the list of data in [Link] file by creating string-array.
[Link]
File:[Link]
<resources>
<string name="app_name">ListView</string>
<string-array name="array_technology">
<item>Android</item>
<item>Java</item>
<item>Php</item>
<item>Hadoop</item>
<item>Sap</item>
<item>Python</item>
<item>Ajax</item>
<item>C++</item>
<item>Ruby</item>
<item>Rails</item>
<item>.Net</item>
<item>Perl</item>
</string-array>
</resources>
Activity class
In java class we need to add adapter to listview using setAdapter() method of listview.
File: [Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class MainActivity extends AppCompatActivity {
ListViewlistView;
TextViewtextView;
String[] listItem;
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
listView=(ListView)findViewById([Link]);
textView=(TextView)findViewById([Link]);
listItem = getResources().getStringArray([Link].array_technology);
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
[Link].simple_list_item_1, [Link].text1, listItem);
[Link](adapter);
[Link](new [Link]() {
@Override
public void onItemClick(AdapterView<?>adapterView, View view, int position, long l) {
// TODO Auto-generated method stub
String value=[Link](position);
[Link](getApplicationContext(),value,Toast.LENGTH_SHORT).show();
}
});
}
}

OVERVIEW OF GOOGLE PLAY SERVICES


Google Play services powers a broad set of SDKs on Android to help you
build your app, enhance privacy and security, engage users, and grow
your business. These SDKs are unique in that they only require a thin
client library to be included in your app, as shown in figure 1. At
runtime, the client library communicates with the bulk of the SDK's
implementation and footprint in Google Play services.
o By providing shared, client-side implementations, Google Play
Figure 1. Google Play services receives
services: regular updates that contain improvements
and bug fixes.
o Helps to optimize on-device resources, such as storage and memory, to improve app quality and your users' overall
experience.
o Receives automatic updates—independent of OS, OEM, or app updates—so your users receive improvements and
bug fixes more quickly.
o Powers SDKs that are backward compatible to Android 4.4 (API level 19) and are available on a variety of form
factors, enabling you to reach more users with less effort.

HOW GOOGLE PLAY SERVICES WORKS

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.

You might also like