0% found this document useful (0 votes)
91 views40 pages

Java Versions for Android Builds

The document discusses the selection of Java Development Kit (JDK) versions for Android builds, highlighting the importance of using the JetBrains Runtime (JBR) for Android Studio and the configuration of Gradle builds. It explains how to choose the appropriate JDK for building applications, the compatibility of Java APIs with different Android versions, and the significance of specifying Java toolchains and source compatibility. Additionally, it provides an overview of the Android SDK and its components essential for Android application development.

Uploaded by

sunil.betha
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)
91 views40 pages

Java Versions for Android Builds

The document discusses the selection of Java Development Kit (JDK) versions for Android builds, highlighting the importance of using the JetBrains Runtime (JBR) for Android Studio and the configuration of Gradle builds. It explains how to choose the appropriate JDK for building applications, the compatibility of Java APIs with different Android versions, and the significance of specifying Java toolchains and source compatibility. Additionally, it provides an overview of the Android SDK and its components essential for Android application development.

Uploaded by

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

Java versions in Android builds

bookmark_border

Whether your source code is written in Java, Kotlin, or both, there are several places you
must choose a JDK or Java language version for your build.

Glossary
Java Development Kit (JDK)

The Java Development Kit (JDK) contains:

 Tools, such as a compiler, profiler, and archive creator. These are used behind the
scenes during your build to create your application.
 Libraries containing APIs that you can cal
calll from your Kotlin or Java source code.
Note that not all functions are available on Android.
 The Java Virtual Machine (JVM), an interpreter that executes Java applications. You
use the JVM to run the Android Studio IDE and the Gradle build tool. The JVM is not
used on Android devices or emulators.

JetBrains Runtime (JBR)

The JetBrains Runtime (JBR) is an enhanced JDK, distributed with Android Studio.
It includes several optimizations for use in Studio and related JetBrains products,
but can also be used to run other Java applications.

How do I choose a JDK to run Android Studio?


We recommend that you use the JBR to run Android Studio. It's deployed with and used to
test Android Studio, and includes enhancements for optimal Android Studio usage. To
ensure this, don't set the STUDIO_JDK environment variable.

The startup scripts for Android Studio look for a JVM in the following order:

1. STUDIO_JDK environment variable


2. [Link] directory (in the Android Studio distribution)
3. jbr directory (JetBrains Runtime), in the Android Studio distribution. Recommended.
4. JDK_HOME environment variable
5. JAVA_HOME environment variable
6. java executable in the PATH environment variable

How do I choose which JDK runs my Gradle builds?


If you run Gradle using the buttons in Android Studio, the JDK set in the Android Studio
settings is used to run Gradle. If you run Gradle in a terminal, either inside or outside
Android Studio, the JAVA_HOME environment variable (if set) determines which JDK runs
the Gradle scripts. If JAVA_HOME is not set, it uses the java command on
your PATH environment variable.

For the most consistent results, make sure you set your JAVA_HOME environment
variable, and Gradle JDK configuration in Android Studio to that same JDK.

Note: If you run a Gradle command in the Android Studio Terminal by right-clicking and
selecting Run highlighted command using the IDE then it uses the JDK in the Android
Studio settings, not JAVA_HOME.

When running your build, Gradle creates a process called a daemon to perform the actual
build. This process can be reused, as long as the builds are using the same JDK and
Gradle version. Reusing a daemon reduces the time to start a new JVM and initialize the
build system.

If you start builds with different JDKs or Gradle versions, additional daemons are created,
consuming more CPU and memory.

Tip: When working with multiple projects simultaneously, if possible, specify the same
Gradle version in their [Link] file to reduce the number of Gradle
daemons created.

Gradle JDK configuration in Android Studio

To modify the existing project's Gradle JDK configuration, open the Gradle settings
from File (or Android Studio on macOS) > Settings > Build, Execution, Deployment >
Build Tools > Gradle. The Gradle JDK drop-down contains the following options to
select from:

 Macros such as JAVA_HOME and GRADLE_LOCAL_JAVA_HOME


 JDK table entries in vendor-version format like jbr-17 which are stored in the Android
configuration files
 Downloading a JDK
 Adding a specific JDK
 Locally detected JDKs from the operating system's default JDK installation directory

The selected option is stored in the gradleJvm option in the project's .idea/[Link] file, and
its JDK path resolution is used to run Gradle when started through Android Studio.
Figure 1. Gradle JDK settings in Android Studio.

The macros enable dynamic project JDK path selection:

 JAVA_HOME: uses the environment variable with the same name

 GRADLE_LOCAL_JAVA_HOME: uses the [Link] property in the .gradle/[Link] file


which defaults to the JetBrains Runtime.

The selected JDK is used to run your Gradle build and resolve JDK API references when
editing your build scripts and source code. Note that the specified compileSdk will further
restrict which Java symbols will be available when editing and building your source code.

Note: In most cases, we recommend using GRADLE_LOCAL_JAVA_HOME, which is the default for
newly created projects. This lets you define a project-specific
project JDK
K without opening the
project first.

Make sure to choose a JDK version that is higher than or equal to the JDK versions used
by plugins that you use in your Gradle build. To determine the minimum required JDK
see the compatibility table in the release
version for the Android Gradle Plugin (AGP), see
notes.

For example, the Android Gradle Plugin version 8.x requires JDK 17. If you try to run a
Gradle build that uses it with an earlier version of the JDK, it reports a message like:

An exception occurred applying plugin request [id: '[Link]']


> Failed to apply plugin '[Link]'.
> Android Gradle plugin requires Java 17 to run. You are currently using
Java 11.
Your current JDK is located in /usr/local/buildtools/java/jdk11
You can try some of the following options:
- changing the IDE settings.
- changing the JAVA_HOME environment variable.
- changing `[Link]` in `[Link]`.

Which Java APIs can I use in my Java or Kotlin source code?


An Android application can use some of the APIs defined in a JDK, but not all of them.
The Android SDK defines implementations of many Java library functions as part of its
available APIs. The compileSdk property specifies which Android SDK version to use when
compiling your Kotlin or Java source code.

Each version of Android supports a specific version of the JDK and a subset of its
available Java APIs. If you use a Java API that's available in a compileSdk that's not
available in the specified minSdk, you might be able to use the API in the earlier version of
Android through a process known as desugaring. See Java 11+ APIs available through
desugaring for supported APIs.

Use this table to determine which Java version is supported by each Android API, and
where to find details on which Java APIs are available.

Android Java API and language features supported

14 (API 34) 17 Core libraries


13 (API 33) 11 Core libraries
12 (API 32) 11 Java API
11 and lower Android versions

Which JDK compiles my Java source code?


The Java toolchain JDK contains the Java compiler used to build any Java source code.
This JDK also runs the Kotlin compiler (which runs on a JVM), javadoc, and tests run
during the build.

The toolchain defaults to the JDK used to run Gradle. If you use the default and run a
build on different machines (for example, your local machine and a separate Continuous
Integration server), the results of your build can differ if different JDK versions are used.

To create a more-consistent build, you can explicitly specify a Java toolchain version.
Specifying this:
 Locates a compatible JDK on the system running the build.
 If no compatible JDK exists (and a toolchain resolver is defined), downloads one.
 Exposes the toolchain Java APIs for calls from source code.
 Compiles Java source using its Java language version.
 Supplies defaults for sourceCompatibility and targetCompatibility.

We recommend that you always specify the Java toolchain, and either ensure that the
specified JDK is installed, or add a toolchain resolver to your build.

You can specify the toolchain whether your source code is written in Java, Kotlin, or both.
Specify the toolchain at the top level of your module's [Link](.kts) file.

If your source code is only written in Java, specify the Java toolchain version like this:

If your source is only Kotlin or a mix of Kotlin and Java, specify the Java toolchain version
like this:

The toolchain JDK version can be the same as the JDK used to run Gradle, but keep in
mind they serve different purposes.

Which Java language source features can I use in my Java


source code?
The sourceCompatibility property determines which Java language features are available
during compilation of Java source. It does not affect Kotlin source.

If not specified, this defaults to the Java toolchain or JDK used to run Gradle. We
recommend that you always explicitly specify a toolchain (preferred) or sourceCompatibility.

Specify sourceCompatibility in your module's [Link](.kts) file.

Note: As of Android Studio Giraffe, when projects are imported,


the sourceCompatibility option is also used as a default for IDE code assist and linting
when writing Java source. Some Java language features require library support and are
not available on Android. The compileSdk option determines which libraries are available.
Other features, such as switch expressions, only require the Java compiler and work on
Android.

Which Java binary features can be used when I compile my


Kotlin or Java source?
Specifying targetCompatibility and jvmTarget determines the Java class-format version used
when generating bytecode for compiled Java and Kotlin source, respectively.
Some Kotlin features existed before equivalent Java features were added. Early Kotlin
compilers had to create their own way to represent those Kotlin features. Some of these
features were later added to Java. With later jvmTarget levels, the Kotlin compiler might
directly use the Java feature, which might result in better performance.

targetCompatibility defaults to the same value as sourceCompatibility, but if specified, must be


greater than or equal to sourceCompatibility.

jvmTarget defaults to the toolchain version.

Different versions of Android support different versions of Java. You can take advantage
of additional Java features by increasing targetCompatibility and jvmTarget, but this might
force you to also increase your minimum Android SDK version to ensure the feature is
available.

Android SDK and it’s Components


Read
Courses
Jobs

Android SDK stands for Android Software Development Kit which is developed by
Google for Android Platform. With the help of Android SDK, we can create android Apps
easily.
About Android SDK
Android SDK is a collection of libraries and Software Development tools that are essential
for Developing Android Applications. Whenever Google releases a new version or update of
Android Software, a corresponding SDK also releases with it. In the updated or new version
of SDK, some more features are included which are not present in the previous version.
Android SDK consists of some tools which are very essential for the development of
Android Application. These tools provide a smooth flow of the development process from
developing and debugging. Android SDK is compatible with all operating systems such as
Windows, Linux, macOS, etc.
Components of Android SDK
Android SDK Components play a major role in the Development of Android applications.
Below are the
he important components:
1. Android SDK Tools
Android SDK tool is an important component of Android SDK. It consists of a complete set
of development and debugging tools. Below are the SDK developer tools:
 Android SDK Build tool.
 Android Emulator.
 Android SDK Platform-tools.
tools.
 Android SDK Tools.
These are shown below :

2. Android SDK Build-Tools


Tools
Android SDK build tools are used for building actual binaries of Android App. The main
functions of Android SDK Build tools are built, debug, run and test Android applications.
a
The latest version of the Android SDK Build tool is 30.0.3. While downloading or updating
Android in our System, one must ensure that its latest version is download in SDK
Components.
3. Android Emulator
An Android Emulator is a device that simulates an Android device on your system. Suppose
we want to run our android application that we code. One option is that we will run this on
our Android Mobile by Enabling USB Debugging on our mobile. Another option is using
Android Emulator. In Android Emulator the virtual android device is shown on our system
on which we run the Android application that we code.
Thus, it simply means that without needing any physical device Android SDK component
“Android Emulator” provides a virtual device on the System
System where we run our Application.
The emulator’s come with the configuration for Various android phones, tablets, Wear OS,
and Android TV devices.

In Android Virtual Emulator all functions that are feasible on real Android mobile is works
on virtual Device like:
 phone calls, text messages.
 stimulate different network speeds.
 specify the location of a device
 access on google play store and lot’s more.
But there is one disadvantage of this em ulator is that. It is very slow when System’s PC has
emulator
less RAM. It works fine when a maximum GB of RAM is present on our device.
4. Android SDK Platform-tools
tools
Android SDK Platform-tools
tools is helpful when we are working on Project and they will show
the error messages at the same time. It is specifically used for testing. It includes:
 command line tool that helps to communicate with
Android Debug Bridge (ADB), is a command-line
the device. It allows us to perform an action such as Installing App and Debugging App
etc.
 Fastboot
oot allows you to flash a device with a new system image.
 Systrace tools help to collect and inspect timing information. It is very crucial for App
Debugging.
5. Android SDK Tools
Android SDK tool is a component of SDK tool. It consists of a set of tools which
w and other
Utilities which are crucial for the development of Android Application. It contains the
complete set of Debugging and Development tools for android.
6. SDK Platforms
For Each Android Software, one SDK platform is available as shown below:
Like in this Android 11.0(R) is installed.
These are numbered according to the android version. The new version of the SDK platform
has more features and more compatible but the old version is less compatible with fewer
features. Like in Android 11.0(R) have more compatible and have more feature but
bu the
below versions like Android 10.0(Q), Android4.4(KitKat) have less feature and is less
compatible.
7. SDK Update Sites
In SDK Update Sites, some sites are embedded in it which will check for Android SDK
Updates Tools. In this, one must ensure we don’t unclick the button below because these are
checked by default which will check for updates if we will unclick it then it doesn’t check
updates for those.
Android App Development Tools to Build Responsive Apps
A touchscreen mobile device such as a smartphone
smartphone or tablet is the primary target of the Android
operating system. With the founding of the Open Handset Alliance in 2007, Android was
introduced by Android Inc., backed financially by Google (a consortium of hardware, software, and
telecommunications companies devoted to the advancement of open standards for mobile devices).
Android Holds Almost 74.13% market share and has become a buzzword in the technology sector.

Source: Root Nation

The Android platform is open-source,


source, unlike iOS and Blackberry, allowing you to develop custom
applications. No developer phone is required, and your hardware does not have to be registered as a
development device to develop them. However, if you don’t want to get into these technical terms,
collaborating
ing with an Android app development company will benefit you.

Now without any ado, let’s go through the top Android app development tools that are currently
trending in the market.

Eclipse
known and popular Android app development tool. The app development projects
Eclipse is a well-known
can be customized using a collection of tools and a different coding environment.
Eclipse is mostly used to create Java programs using plug
plug-ins
ins from libraries. However, the ability
ab
to develop code in ABAP, C++, C#, Fortran, Python, JavaScript, Ruby, Scala, and many other
languages has been made possible by the most recent updates and upgrades.

As one of the most well-liked


liked Android development tools, Eclipse has a large selectio
selection of features.
These functions aid in scaling the codebase for future application improvements and optimization.

Android Studio

Android Studio is one of the most widely used Android IDEs for developing mobile apps. This is
because the official integrated development environment for Google’s Android operating system is
also known as Android Studio.

Following its introduction on May 16, 2013, at the Google I/O Conference, Android Studio gained
popularity.

Fascinating Features of Android Studio

 Gradle build support


 Instant run
 In-built
built support for the Google Cloud platform
 Fast emulator to debug apps
 Maven repository

Android Debug Bridge


An essential debugging tool in the Android development environment is ADB. It is client
client-server
software with three components and is a necessary tool for Android developers

1. a client that transmits commands


2. a device’s daemon (adbd), which
wh executes commands
3. a server that coordinates client-ADBD
client communication

The Platform-Tools
Tools package for the Android SDK contains ADB. You can obtain this package
using the SDK Manager, which is installed on Android SDK / platform tools. Alternatively, you
Platform Tools package if that’s what you
can directly download the standalone Android SDK Platform-Tools
need.

Native Development Kit

The NDK is a suite of tools that enables Android developers to use native-code
native languages like C
and C++ to build some aspects of their apps. In addition, developers can benefit from NDK since it
allows them to reuse code libraries created in these languages. However, the fact that NDK won’t
help most apps is the most important
rtant thing to keep in mind in this situation.

Because native code often increases complexity rather than performance, the developer must weigh
its benefits and cons. Native code may not always boost performance. Use the NDK only if it is
necessary for yourr app; do not use it just because you want to code in C or C++.

HeadSpin
This Android app development tool gives businesses useful user experience insights that improve
mobile outcomes.

Thousands of devices and more than 150 locations around the world can now access this tool. You
should be aware that this Android app development tool does not need an SDK to grow the
t
codebase.

Additionally, this tool for developing apps is entirely API-based.


API based. But that’s not all; using artificial
intelligence that is integrated into the tool’s engine, all performance concerns are prioritized in this
tool based on their impact.

Unity 3D

The ideal tool for creating high-definition


definition Android gaming applications is Unity 3D. With the help
of this tool, developers may produce 2D and 3D game apps with dependable graphics, a fluid
structure, and a fantastic layout. In addition, the latest version of Unity 3D can now be used to
construct cross-platform
platform gaming applications, despite the fact that it is frequently used to make
game apps for websites and mobile devices.

CE of Unity, 60-70% of all games are created on this platform.


According to John Riccitiello, CEO
Whether we choose to believe him or not, one thing is certain: When it comes to games,
g Unity is
one of the top technologies needed for Android app development.

Basic4Android

Basic4android compiles code into native Android apps without the assistance of other run-time
run
environments. This utility does not support other platforms because it was created exclusively for
Android applications.
Features:

 Creating Android apps using a more straightforward programming language (BASIC)


 A visual editor that allows for flexible view manipulation
 Wireless bug fixing
 Briefly said B4A offers an efficient IDE and interpreter that lets you build programs in a less
complex programming language

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 more

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

o SDK Tools 26.1.1 or higher


o 64-bit processor
o Windows: CPU with UG (unrestricted guest) support
o 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:

1. Open the AVD Manager.


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

1. $ emulator -avd avd_name [ {-option [value]} ... ]

or

1. $ 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:

1. $ /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:

1. $ emulator -list-avds
Run and stop an emulator, and clear data
From the Virtual Device page, we can perform the following operation on emulator:

o To run an Android emulator that uses an AVD, double-click the AVD, or click Launch
o To stop the running emulator, right-click and select Stop, or click Menu ▼ and select
Stop.
o 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.

Install Android
Android supports java, c++, c# etc. language to develop android applications. Java is the
officially supported language for android. All the android examples of this site is
developed using Java language and Eclipse IDE.

Here, we are going to tell you, the required softwares to develop android applications
using Eclipse IDE.

There are two ways to install android.

1. By ADT Bundle
2. By Setup Eclipse Manually
1) By Android Studio
It is the simplest technique to install required software for android application. It includes:

o Eclipse IDE
o Android SDK
o Eclipse Plugin

Click me to download android adt bundle

If you download the Android Studio from android site, you don't need to have eclipse IDE,
android SDK and eclipse Plugin because it is already included in Android Studio.

If you have downloaded the Android Studio, unjar it, go to eclipse IDE and start the eclipse
by clicking on the eclipse icon. You don't need to do any extra steps here.

If eclipse is not started, paste the JRE directory inside the eclipse directory.

2) By set up eclipse manually


Visit the next page to learn about setting up android in eclipse manually.

Introduction to Activities in Android


Read
Courses
Practice
Jobs

Activity class is one of the very important parts of the Android Component. Any app, don’t
matter how small it is (in terms of code and scalability), has at least one Activity class.
Unlike most programming languages, in which the main() method is the entry point for that
program or application to start its execution, the android operating system initiates the code
in an Activity instance by invoking specific callback methods that correspond to specific
stages of its Lifecycle. So it can be said that An activity is the entry point for interacting
with the user. Every activity contains the layout, which has a user interface to interact with
the user. As we know that every activity contains a layout associated with it, so it can be said
that the activity class is the gateway, through which a user can interact programmatically
with the UI. Layout for a particular activity is set with the help
of setContentView(). setContentView() is a function that takes View as a parameter. The
view parameter basically contains the layout file for that activity. The code has been given in
both Java and Kotlin Programming Language for Android.
The Following Code Indicates that activity_main is the Layout File of
MainActivity
 Kotlin
 Java

import [Link]

import [Link]

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {

[Link](savedInstanceState)

setContentView([Link].activity_main)

}
While activities are often presented to the user as the full-screen window, Multiwindow
mode, or Picture in Picture mode, here are two methods almost all subclasses of Activity
will implement:
1. onCreate()
2. onPause()
1. onCreate() Method
The syntax for Kotlin:
override fun onCreate(savedInstanceState: Bundle?)

The syntax for Java:


protected void onCreate(Bundle savedInstanceState)

 onCreate(Bundle) method is the place, where the user initializes the activity. This
method is called when the activity is starting. This is the method that is used to initialize
most of the things in the android app. onCreate() method takes savedInstanceState as
the parameter, which the object of type Bundle, i.e Bundle Object which contains the
previously saved data of the activity. If the activity is newly created then the bundle
won’t be saving any data of the activity and would contain the null value.
 onCreate() method calls the setContentView() method to set the view corresponding to
the activity. By default in any android application, setContentView point to
activity_main.xml file, which is the layout file corresponding to MainActivity. The
onCreate method uses the findViewById() method so that the user can interact
programmatically with the widgets in android and then customize them according to
need.
Bundle: If the activity is being re-initialized or restarted after previously being closed, then
this Bundle contains the data it most recently supplied
in onSaveInstanceState(Bundle). onSaveInstanceState() method is the method that is
called to save the data just before our activity is killed.
2. onPause() Method
The syntax for Kotlin:
override fun onPause() {
[Link]()
}

The syntax for Java:


protected void onPause() {
[Link]();
}

This method is called part of the Activity Lifecycle when the user no longer actively
interacts with the activity, but it is still visible on the screen. Let’s suppose the user is
running two apps simultaneously on a mobile phone, i.e when activity B is launched in front
of activity A, activity A will go in the onPause() state, and activity B would go in
the onStart() state of the activity lifecycle. One important point to be remembered is that for
any activity to be accessed by a system, i.e. android here, that activity must be declared in
a Manifest File. The Manifest File is an XML file included in in the Application and is by
default known as [Link].
[Link]
Declaring Activity in Manifest File
Open the app folder, and then open the subfolder manifest, and then open
the [Link] file.

Let’s suppose the reader wants to have one more activity, apart from the MainActivity which
is included by default in the project. Before adding one more activity and not doing any
changes,

Let’s see what the [Link]


AndroidManifest.x File looks like

 XML

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


encoding="utf

[Link]
<manifest xmlns:android="[Link]
[Link]

xmlns:tools="[Link]
[Link]

package="[Link]">

<application
android:allowBackup="true"

android:dataExtractionRules="@xml/data_extraction_rules"

android:fullBackupContent="@xml/backup_rules"

android:icon="@mipmap/ic_launcher"

android:label="@string/app_name"

android:roundIcon="@mipmap/ic_launcher_round"

android:supportsRtl="true"

android:theme="@style/[Link]"

tools:targetApi="31">

<activity

android:name=".MainActivity"

android:exported="true">

<intent-filter>

<action android:name="[Link]" />

<category android:name="[Link]" />

</intent-filter>

</activity>

</application>

</manifest>
Now let’s add another activity named SecondActivity, and see how to declare it in the
manifest file. One must write the Declaration Code within the application
tag, otherwise, the declaration will give the error, and SecondActitvity will not be
detected by the System. The Declaration Code is given below.
<activity
android:name=".SecondActivity"
android:exported="true" >
</activity>

So it can conclude that an application can have one or more activities without any
restrictions. Every activity that the android app uses must be declared in
the [Link] file. and the main activity for the app must be declared in the
manifest with a <intent-filter> that includes the MAIN action and LAUNCHER. Any
activity whether it is MainActivity or any other activity must be declared within
the <application> of the AndroidManifest file. If the user forgets to declare any of the
activity, then android will not be able to detect that activity in the app. If either the MAIN
action or LAUNCHER category is not declared for the main activity, then the app icon will
not appear in the Home screen’s list of apps.
Adding Permissions to Application
For any service that the Developer wants to use in the Android App, like Internet service,
Bluetooth service, Google Maps, App Notification service, etc, the Developer needs to take
the permission of the Android System. All those Permissions or Requests must be declared
within the Manifest File. Open the [Link] file, with the procedure shown
above. Let’s say the user needs to add Internet permission, that needs to be accessed by the
app. Add the below Internet Permission within the manifest tag.
<uses-permission android:name="[Link]" />

Let’s say one needs to add Bluetooth permission within the app, then it must be declared
like this:
<uses-permission android:name="[Link]" />

Note: Let’s say that the MainActivity extends AppCompatActivity in the code snippet given
at the top, internally the structure is as shown in the image given below. It can be seen
that AppCompatActivity also extends the Activity Class.
Feeling lost in thee vast world of Backend Development? It's time for a change! Join our Java
Backend Development - Live Course and embark on an exciting journey to master backend
development efficiently and on schedule.

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.

ifecycle method of Activity describes how activity will behave at different states.
The 7 lifecycle

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

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


2. <[Link] xmlns:android="[Link]
com/apk/res/android"
3. xmlns:app="[Link]
4. xmlns:tools="[Link]
5. android:layout_width="match_parent"
6. android:layout_height="match_parent"
7. tools:context="[Link]">
8.
9. <TextView
10. android:layout_width="wrap_content"
11. android:layout_height="wrap_content"
12. android:text="Hello World!"
13. app:layout_constraintBottom_toBottomOf="parent"
14. app:layout_constraintLeft_toLeftOf="parent"
15. app:layout_constraintRight_toRightOf="parent"
16. app:layout_constraintTop_toTopOf="parent" />
17.
18. </[Link]>

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]

1. package [Link];
2.
3. import [Link];
4. import [Link];
5. import [Link];
6.
7. public class MainActivity extends Activity {
8.
9. @Override
10. protected void onCreate(Bundle savedInstanceState) {
11. [Link](savedInstanceState);
12. setContentView([Link].activity_main);
13. Log.d("lifecycle","onCreate invoked");
14. }
15. @Override
16. protected void onStart() {
17. [Link]();
18. Log.d("lifecycle","onStart invoked");
19. }
20. @Override
21. protected void onResume() {
22. [Link]();
23. Log.d("lifecycle","onResume invoked");
24. }
25. @Override
26. protected void onPause() {
27. [Link]();
28. Log.d("lifecycle","onPause invoked");
29. }
30. @Override
31. protected void onStop() {
32. [Link]();
33. Log.d("lifecycle","onStop invoked");
34. }
35. @Override
36. protected void onRestart() {
37. [Link]();
38. Log.d("lifecycle","onRestart invoked");
39. }
40. @Override
41. protected void onDestroy() {
42. [Link]();
43. Log.d("lifecycle","onDestroy invoked");
44. }
45. }
Output:

You will not see any output on the emulator or device. You need to open logcat.
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.
The onCreate() and onDestroy() methods are called only once throughout the activity lifecycle.

You might also like