KEMBAR78
Mob Unit1 | PDF | Android (Operating System) | Mobile App
0% found this document useful (0 votes)
14 views37 pages

Mob Unit1

mob unit1

Uploaded by

Ansh Singh 10 B
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)
14 views37 pages

Mob Unit1

mob unit1

Uploaded by

Ansh Singh 10 B
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
You are on page 1/ 37

UNIT-1

History of Mobile Application


The history of mobile apps is surprisingly rich and spans much further back than
you might think! Let's take a journey through some key milestones:

Early beginnings (1980s - 1990s):

 Predecessors: Personal Digital Assistants (PDAs) like the Psion Organiser and
Palm Pilot played a crucial role with built-in apps for calendars, contacts, and
notes.
 Games: Nokia's iconic "Snake" in 1997 is considered one of the first mobile
games, paving the way for future entertainment apps.
 Simple functionality: Early apps focused on utilitarian tasks like
calculations, scheduling, and basic communications.

The dawn of smartphones (2000s):

 BlackBerry (late 1990s): Pioneered mobile email and internet browsing, blurring
the line between phone and device.
 Symbian OS: A dominant platform in the early 2000s, powering smartphones
from Nokia, Sony Ericsson, and others.
 J2ME: Java-based platform aimed at bringing app functionalities to feature
phones but faced limitations.

The revolution arrives (2007 - present):

 iPhone (2007): Introduced a touch-screen interface, app store concept, and


powerful hardware, sparking a mobile app renaissance.
 Android (2008): Open-source platform fueled an explosion of affordable
smartphones and diverse app development.
 App Stores: Became central to discovering and downloading apps, with Apple's
App Store and Google Play leading the charge.

Key advancements and trends:

 3G and beyond: Faster internet speeds enabled data-intensive apps like


streaming, social media, and navigation.
 Mobile payments: Integration of secure payment systems for seamless in-app
purchases.
 Augmented Reality (AR) and Virtual Reality (VR): Immersive technologies open
up new possibilities for gaming, education, and more.
 Artificial intelligence (AI): Chatbots, personalized recommendations, and voice
assistants enhance user experience.

The future of mobile apps:

 Focus on user experience: Personalized apps, AI-powered features, and seamless


integration across devices.
 Emerging technologies: AR/VR, foldable displays, and blockchain will likely
play a significant role.
 Greater accessibility and inclusivity: Ensuring apps cater to diverse needs and
abilities.
Different types of Mobile Applications

1. Productivity and Organization:

 Task management: Trello, Asana, Todoist - Keep track of tasks, set


deadlines, and collaborate with others.
 Calendars and scheduling: Google Calendar, Outlook, Fantastical - Organize
appointments, events, and reminders.
 Note-taking: Evernote, OneNote, Google Keep - Capture ideas, thoughts, and
information seamlessly.
 File management: Dropbox, Google Drive, Microsoft OneDrive -
Store, access, and share documents and files from anywhere.

2. Communication and Social Networking:

 Messaging: WhatsApp, Telegram, Signal - Connect with friends and family


through text, voice, and video calls.
 Social media: Facebook, Instagram, Twitter - Share updates, connect with
communities, and discover new content.
 Professional networking: LinkedIn, Xing - Build professional connections, find
job opportunities, and showcase your skills.
 Video conferencing: Zoom, Google Meet, Microsoft Teams - Collaborate with
colleagues and clients remotely.

3. Entertainment and Leisure:

 Games: From casual puzzles to immersive MMORPGs, there's a game for


everyone.
 Streaming services: Netflix, Disney+, Hulu - Watch movies, TV shows, and
original content on demand.
 Music streaming: Spotify, Apple Music, YouTube Music - Access millions of
songs and create personalized playlists.
 E-books and audiobooks: Kindle, Audible - Read or listen to books on the go.

4. Health and Fitness:

 Workout trackers: Strava, Nike Run Club, Fitbit - Monitor your activity, set
goals, and track progress.
 Yoga and meditation apps: Headspace, Calm, Down Dog - Improve
mindfulness, manage stress, and promote relaxation.
 Diet and nutrition apps: MyFitnessPal, Cronometer, Yummly - Track calorie
intake, plan meals, and find healthy recipes.
 Mental health apps: Talkspace, BetterHelp, Headspace - Access therapy
resources, mindfulness exercises, and mental health support.

5. Finance and Business:

 Banking apps: Bank of America, Chase, Wells Fargo - Manage your


accounts, transfer funds, and pay bills on the go.
 Investment apps: Stash, Robinhood, Acorns - Invest in stocks, ETFs, and other
financial instruments.
 Project management: Asana, Trello, Monday.com - Manage projects, teams, and
tasks efficiently.
 Customer relationship management (CRM): Salesforce, HubSpot, Zoho -
Manage customer interactions, track leads, and close deals.

6. Travel and Lifestyle:


 Booking apps: Airbnb, Booking.com, Hopper - Find and book
accommodation, flights, and activities.
 Navigation apps: Google Maps, Waze, Apple Maps - Get directions, avoid
traffic, and explore new places.
 Food delivery apps: DoorDash, Grubhub, Uber Eats - Order food from your
favorite restaurants and get it delivered to your doorstep.
 Language learning apps: Duolingo, Babbel, Memrise - Learn languages in a fun
and interactive way.
A Brief History of Android

The story of Android is one of remarkable growth and unexpected twists,


transforming from a humble camera software project into the world's most
dominant mobile operating system. Here's a quick timeline of its journey:

2003:

 Android Inc. is founded by Andy Rubin, Rich Miner, Chris White, and Nick
Sears. Initially, their target was digital cameras!
 Google's interest sparks, recognizing the potential for a smartphone OS.

2005:

 Google acquires Android Inc. for $50 million, bringing the team under their
wing.

2007:

 The first public beta of the Android OS is released, codenamed "Cupcake."

2008:

 The HTC Dream (T-Mobile G1) becomes the first commercially available
Android phone, marking the official debut.
 Initial versions focused on core functionalities like email, web browsing, and
basic apps.

2009 - 2011:
 Rapid growth with new phone releases from various manufacturers like
Samsung, Motorola, and LG.
 Open-source nature attracts developers, leading to an explosion of apps in the
Google Play Store.

2012:

 Android surpasses iOS to become the most popular mobile OS globally.

2014:

 Android 5.0 Lollipop introduces a major design overhaul, focusing on usability


and material design.

2016:

 Android Nougat further refines multitasking and user experience.

2017 - Present:

 Continued focus on AI integration, performance optimization, and security


improvements.
 Emergence of foldable phones and other form factors, pushing the boundaries of
mobile technology.

Key Takeaways:

 Android's open-source nature and flexibility played a crucial role in its success.
 Strong partnerships with phone manufacturers fueled its widespread adoption.
 Continuous innovation and focus on user experience kept Android at the
forefront.

Looking Ahead:

The future of Android promises further integration with AI, machine learning,
and advanced features like augmented reality. Android's journey from camera
software to global phenomenon is a testament to its adaptability and its
commitment to empowering users through an open and customizable platform.

Android Operating System


Android is a mobile operating system (OS) primarily designed for touchscreen
devices like smartphones and tablets. It's developed by a consortium known as
the Open Handset Alliance, with Google playing a leading role. Here's a
breakdown of its key aspects:

Core Features:

 Based on the Linux kernel: Provides a stable and secure foundation for the OS.
 Open-source: Allows customization and development by manufacturers and
developers, leading to diversity in devices and apps.
 Touchscreen interface: Intuitive and user-friendly, with intuitive gestures and
swipes for navigation.
 Multitasking: Allows running multiple apps simultaneously and switching
between them.
 Extensive app ecosystem: Google Play Store boasts millions of apps across
various categories, catering to diverse needs.
 Regular updates: Google and device manufacturers provide security patches and
new features through updates.

Benefits of Android:

 Affordability: Android powers a wide range of smartphones at various price


points, making it accessible to a broader audience.
 Customization: Users can personalize their devices with widgets, launchers, and
custom settings.
 Openness: Developers can create and distribute apps freely, fostering innovation
and competition.
 Integration with Google services: Seamless access to popular Google services
like Gmail, Maps, and Assistant.
 Constant evolution: New features and improvements are introduced
regularly, keeping the platform fresh and relevant.

Applications of Android:

 Communication: Texting, calling, video conferencing, social media.


 Entertainment: Games, music streaming, video streaming, e-books.
 Productivity: Calendars, email, note-taking, file management.
 Finance: Banking apps, investment apps, budgeting tools.
 Health and fitness: Fitness trackers, workout apps, nutrition apps.
 Travel and navigation: Booking apps, maps, travel guides.

Overall, Android is a versatile and powerful mobile OS that offers a diverse app
ecosystem, customization options, and constant evolution. It's no wonder it
remains the most popular mobile platform globally.

Android KitKat(4.4)
Android KitKat brings all of Android's most innovative, most beautiful, and most
useful features to more devices everywhere.

Printing framework
Android apps can now print any type of content over Wi-Fi or cloud-hosted
services such as Google Cloud Print.

Full-screen Immersive mode

Android Lollipop(5.0)

Material design
Android 5.0 brings Material design to Android and gives you an expanded UI
toolkit for integrating the new design patterns easily in your apps.

Document-centric apps
Android 5.0 introduces a redesigned Overview space (formerly called Recents)
that’s more versatile and useful for multitasking.
Android Platform architecture
Android is an open source, Linux-based software stack created for a wide array
of devices and form factors.
Major components of the Android platform.
Android Software Stack

Linux kernel
The foundation of the Android platform is the Linux kernel. For example, the
Android Runtime (ART) relies on the Linux kernel for underlying functionalities
such as threading and low-level memory management.
Using a Linux kernel lets Android take advantage of key security features and
lets device manufacturers develop hardware drivers for a well-known kernel.

Hardware abstraction layer (HAL)


The hardware abstraction layer (HAL) provides standard interfaces that expose
device hardware capabilities to the higher-level Java API framework. The HAL
consists of multiple library modules, each of which implements an interface for a
specific type of hardware component, such as the camera or Bluetooth module.
When a framework API makes a call to access device hardware, the Android
system loads the library module for that hardware component.
Android runtime

For devices running Android version 5.0 (API level 21) or higher, each app runs
in its own process and with its own instance of the Android Runtime (ART).
ART is written to run multiple virtual machines on low-memory devices by
executing Dalvik Executable format (DEX) files, a bytecode format designed
specifically for Android that's optimized for a minimal memory footprint. Build
tools, such as d8, compile Java sources into DEX bytecode, which can run on the
Android platform.
Some of the major features of ART include the following:
 Ahead-of-time (AOT) and just-in-time (JIT) compilation
 Optimized garbage collection (GC)
 On Android 9 (API level 28) and higher, conversion of an app package's DEX
files to more compact machine code
 Better debugging support, including a dedicated sampling profiler, detailed
diagnostic exceptions and crash reporting, and the ability to set watchpoints to
monitor specific fields
Prior to Android version 5.0 (API level 21), Dalvik was the Android runtime. If
your app runs well on ART, then it can work on Dalvik as well, but the reverse
might not be true.
Android also includes a set of core runtime libraries that provide most of the
functionality of the Java programming language, including some Java 8 language
features, that the Java API framework uses.

Native C/C++ libraries


Many core Android system components and services, such as ART and HAL, are
built from native code that requires native libraries written in C and C++. The
Android platform provides Java framework APIs to expose the functionality of
some of these native libraries to apps. For example, you can access OpenGL
ES through the Android framework’s Java OpenGL API to add support for
drawing and manipulating 2D and 3D graphics in your app.
If you are developing an app that requires C or C++ code, you can use
the Android NDK to access some of these native platform libraries directly from
your native code.

Java API framework


The entire feature-set of the Android OS is available to you through APIs written
in the Java language. These APIs form the building blocks you need to create
Android apps by simplifying the reuse of core, modular system components and
services, which include the following:
 A rich and extensible view system you can use to build an app’s UI, including
lists, grids, text boxes, buttons, and even an embeddable web browser
 A resource manager, providing access to non-code resources such as localized
strings, graphics, and layout files
 A notification manager that enables all apps to display custom alerts in the status
bar
 An activity manager that manages the lifecycle of apps and provides a
common navigation back stack
 Content providers that enable apps to access data from other apps, such as the
Contacts app, or to share their own data
Developers have full access to the same framework APIs that Android system
apps use.

System apps
Android comes with a set of core apps for email, SMS messaging, calendars,
internet browsing, contacts, and more. Apps included with the platform have no
special status among the apps the user chooses to install. So, a third-party app
can become the user's default web browser, SMS messenger, or even the default
keyboard. Some exceptions apply, such as the system's Settings app.
The system apps function both as apps for users and to provide key capabilities
that developers can access from their own app. For example, if you want your
app to deliver SMS messages, you don't need to build that functionality yourself.
You can instead invoke whichever SMS app is already installed to deliver a
message to the recipient you specify.
Application fundamentals

Android apps can be written using Kotlin, the Java programming language, 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 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
isn't required at runtime. An AAB is a publishing format and can't be installed 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 the particular device 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, which 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 can't access
parts of the system it is not given permission for.
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 about permissions, see Permissions on
Android.

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 types of app components:
 Activities
 Services
 Broadcast receivers
 Content providers
Each type serves a distinct purpose and has a distinct lifecycle that defines how a
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.
A different app can start any one of these activities if the email app allows
it. For example, a camera app might start the activity in the email app for
composing a new email to let the user 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—
so that the system keeps running the process that is hosting the activity.
 Knowing which previously used processes contain stopped activities the
user might return to and prioritizing those processes more highly to keep
them available.
 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 primary example of this is
sharing.
You implement an activity as a subclass of the Activity class. For more
information about the Activity class, see Introduction to activities.
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 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 might 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 represent different types of started services, which the
system handles differently:
 Music playback is something the user is directly aware of, and the app
communicates this to the system by indicating that it wants to be in the
foreground, with a notification to tell the user that it is running. In this case,
the system prioritizes keeping that service's process running, because the
user has a bad experience if it goes away.
 A regular background service is not something the user is directly aware of,
so the system has more freedom in managing its process. It might let it be
killed, 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. A bound service provides an API to
another process, and the system knows there is a dependency between these
processes. So if process A is bound to a service in process B, the system
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 knows to treat
process B as something the user also cares about.
Because of their flexibility, services are useful building blocks 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 run.
A service is implemented as a subclass of Service. For more information
about the Service class, see the Services overview.
Broadcast receivers
A broadcast receiver is a component that lets the system deliver events to
the app outside of a regular user flow so the app can 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. Because the alarm is delivered to
a BroadcastReceiver in the app, there is no need for the app to remain
running until the alarm goes off.
Many broadcasts originate from the system, like a broadcast announcing
that the screen is turned off, the battery is low, or a picture is captured.
Apps can also initiate broadcasts, such as to let other apps know that some
data is downloaded to the device and is available for them to use.
Although broadcast receivers don't display a user interface, they can 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, a broadcast receiver might schedule a JobService to perform
some work based on an event using JobScheduler. Broadcast receivers
often involve apps interacting with each other, so it's important to be aware
of the security implications when setting them up.
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 permits it.
For example, the Android system provides a content provider that manages
the user's contact information. Any app with the proper permissions can
query the content provider, such as using ContactsContract.Data, 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 lets the system do in
managing an app:
 Assigning a URI doesn't require that the app remain running, so URIs can
persist after their owning apps exit. The system only needs to make sure
that an owning app is still running when it retrieves 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 let that app access the data using a temporary URI permission
grant so that it accesses the data only behind that URI, and 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.
Activate components

An asynchronous message called an intent activates three of the four component


types: activities, services, and broadcast receivers. 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 (an explicit intent) or a specific type of component
(an implicit intent).
For activities and services, an intent defines the action to perform, such as
to view or send something, and might 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. You can also 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 defines the broadcast announcement. For
example, a broadcast to indicate that 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
activated when targeted by a request from a ContentResolver. The content
resolver handles all direct transactions with the content provider, and the
component performing transactions with the provider calls methods on
the ContentResolver object. This leaves a layer of abstraction for security reasons
between the content provider and the component requesting information.
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, when you want the activity to return a
result, startActivityForResult().
 On Android 5.0 (API level 21) and higher, 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() or sendOrderedBroadcast().
 You can perform a query to a content provider by calling query() on
a ContentResolver.

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, AndroidManifest.xml. Your app declares all its components in this file,
which is 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.
Declare 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 ... >
<applicationandroid:icon="@drawable/app_icon.png" ... >
<activityandroid:name="com.example.project.ExampleActivity"
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
don't declare in the manifest aren't visible to the system and, consequently, can
never run. However, broadcast receivers can either be 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 App
manifest overview.
Declare component capabilities

As discussed in the Activate components section, you can use an Intent to start
activities, services, and broadcast receivers. You do this 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 you want to perform the action on. An implicit intent lets the
system 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.
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 do this 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 to send a new
email, as shown in the following example:
<manifest ... >
...
<application ... >
<activityandroid:name="com.example.project.ComposeEmailActivity">
<intent-filter>
<actionandroid:name="android.intent.action.SEND"/>
<dataandroid:type="*/*"/>
<categoryandroid:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
</application>
</manifest>

If another app creates an intent with the ACTION_SEND action and passes it
to startActivity(), the system might 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.
Declare 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. The system doesn't read them,
but external services such as Google Play do read them to provide filtering for
users when they search for apps from their device.
For example, suppose 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 build.gradle file:
android{
...
defaultConfig{
...
minSdkVersion26
targetSdkVersion29
}
}

Note: Don't set minSdkVersion and targetSdkVersion directly in the manifest


file, since they are overwritten by Gradle during the build process. For more
information, see Specify API level requirements.

You declare the camera feature in your app's manifest file:


<manifest ... >
<uses-featureandroid:name="android.hardware.camera.any"
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 can't install your app from
Google Play. However, you can also declare that your app uses the camera, but
does not require it. To do so, you set the required attribute to false, check at
runtime whether the device has a camera, and disable any camera features as
needed.
More information about how you can manage your app's compatibility with
different devices is provided in the Device compatibility overview.
Introduction to activities

The Activity class is a crucial component of an Android app, and the way
activities are launched and put together is a fundamental part of the platform's
application model. Unlike programming paradigms in which apps are launched
with a main() method, the Android system initiates code in an Activity instance
by invoking specific callback methods that correspond to specific stages of its
lifecycle.

The concept of activities


The mobile-app experience differs from its desktop counterpart in that a user's
interaction with the app doesn't always begin in the same place. Instead, the user
journey often begins non-deterministically. For instance, if you open an email
app from your home screen, you might see a list of emails. By contrast, if you are
using a social media app that then launches your email app, you might go directly
to the email app's screen for composing an email.
The Activity class is designed to facilitate this paradigm. When one app invokes
another, the calling app invokes an activity in the other app, rather than the app
as an atomic whole. In this way, the activity serves as the entry point for an app's
interaction with the user. You implement an activity as a subclass of
the Activity class.
An activity provides the window in which the app draws its UI. This window
typically fills the screen, but may be smaller than the screen and float on top of
other windows. Generally, one activity implements one screen in an app. For
instance, one of an app’s activities may implement a Preferences screen, while
another activity implements a Select Photo screen.
Most apps contain multiple screens, which means they comprise multiple
activities. Typically, one activity in an app is specified as the main activity,
which is the first screen to appear when the user launches the app. Each activity
can then start another activity in order to perform different actions. For example,
the main activity in a simple e-mail app may provide the screen that shows an e-
mail inbox. From there, the main activity might launch other activities that
provide screens for tasks like writing e-mails and opening individual e-mails.
Although activities work together to form a cohesive user experience in an app,
each activity is only loosely bound to the other activities; there are usually
minimal dependencies among the activities in an app. In fact, activities often start
up activities belonging to other apps. For example, a browser app might launch
the Share activity of a social-media app.
To use activities in your app, you must register information about them in the
app’s manifest, and you must manage activity lifecycles appropriately. The rest
of this document introduces these subjects.

Configuring the manifest

For your app to be able to use activities, you must declare the activities, and
certain of their attributes, in the manifest.
Declare activities

To declare your activity, open your manifest file and add an <activity> element
as a child of the <application> element. For example:
<manifest ... >
<application ... >
<activityandroid:name=".ExampleActivity"/>
...
</application ... >
...
</manifest>

The only required attribute for this element is android:name, which specifies the
class name of the activity. You can also add attributes that define activity
characteristics such as label, icon, or UI theme. For more information about these
and other attributes, see the <activity> element reference documentation.
Android activity lifecycle

As a user navigates through, out of, and back to your app, the Activity instances
in your app transition through different states in their lifecycle. The Activity class
provides a number of callbacks that let the activity know when a state changes or
that the system is creating, stopping, or resuming an activity or destroying the
process the activity resides in.

Within the lifecycle callback methods, you can declare how your activity
behaves when the user leaves and re-enters the activity. For example, if you're
building a streaming video player, you might pause the video and terminate the
network connection when the user switches to another app. When the user
returns, you can reconnect to the network and let the user resume the video from
the same spot.
Each callback lets you perform specific work that's appropriate to a given change
of state. Doing the right work at the right time and handling transitions properly
make your app more robust and performant. For example, good implementation
of the lifecycle callbacks can help your app avoid the following:
 Crashing if the user receives a phone call or switches to another app while using
your app.
 Consuming valuable system resources when the user is not actively using it.
 Losing the user's progress if they leave your app and return to it at a later time.
 Crashing or losing the user's progress when the screen rotates between landscape
and portrait orientation.
This document explains the activity lifecycle in detail. The document begins by
describing the lifecycle paradigm. Next, it explains each of the callbacks: what
happens internally while they execute and what you need to implement during
them.
It then briefly introduces the relationship between activity state and a process’s
vulnerability to being killed by the system. Finally, it discusses several topics
related to transitions between activity states.
For information about handling lifecycles, including guidance about best
practices, see Handling Lifecycles with Lifecycle-Aware Components and Save
UI states. To learn how to architect a robust, production-quality app using
activities in combination with architecture components,

Activity-lifecycle concepts

To navigate transitions between stages of the activity lifecycle, the Activity class
provides a core set of six
callbacks: onCreate(), onStart(), onResume(), onPause(), onStop(),
and onDestroy(). The system invokes each of these callbacks as the activity
enters a new state.
Lifecycle callbacks
This section provides conceptual and implementation information about the
callback methods used during the activity lifecycle.
Some actions belong in the activity lifecycle methods. However, place code that
implements the actions of a dependent component in the component, rather than
the activity lifecycle method. To achieve this, you need to make the dependent
component lifecycle-aware. To learn how to make your dependent components
lifecycle-aware, see Handling Lifecycles with Lifecycle-Aware Components.
onCreate()

You must implement this callback, which fires when the system first creates the
activity. On activity creation, the activity enters the Created state. In
the onCreate() method, perform basic application startup logic that happens only
once for the entire life of the activity.
For example, your implementation of onCreate() might bind data to lists,
associate the activity with a ViewModel, and instantiate some class-scope
variables. This method receives the parameter savedInstanceState, which is
a Bundle object containing the activity's previously saved state. If the activity has
never existed before, the value of the Bundle object is null.
If you have a lifecycle-aware component that is hooked up to the lifecycle of
your activity, it receives the ON_CREATE event. The method annotated
with @OnLifecycleEvent is called so your lifecycle-aware component can
perform any setup code it needs for the created state.
The following example of the onCreate() method shows fundamental setup for
the activity, such as declaring the user interface (defined in an XML layout file),
defining member variables, and configuring some of the UI. In this example, the
XML layout file passes the file’s resource
ID R.layout.main_activity to setContentView().
As an alternative to defining the XML file and passing it to setContentView(),
you can create new View objects in your activity code and build a view hierarchy
by inserting new View objects into a ViewGroup. You then use that layout by
passing the root ViewGroup to setContentView(). For more information about
creating a user interface, see the user interface documentation.
Your activity does not remain in the Created state. After the onCreate() method
finishes execution, the activity enters the Started state and the system calls
the onStart() and onResume() methods in quick succession.
onStart()

When the activity enters the Started state, the system invokes onStart(). This call
makes the activity visible to the user as the app prepares for the activity to enter
the foreground and become interactive. For example, this method is where the
code that maintains the UI is initialized.
When the activity moves to the Started state, any lifecycle-aware component tied
to the activity's lifecycle receives the ON_START event.
The onStart() method completes quickly and, as with the Created state, the
activity does not remain in the Started state. Once this callback finishes, the
activity enters the Resumed state and the system invokes
the onResume() method.
onResume()

When the activity enters the Resumed state, it comes to the foreground, and the
system invokes the onResume() callback. This is the state in which the app
interacts with the user. The app stays in this state until something happens to take
focus away from the app, such as the device receiving a phone call, the user
navigating to another activity, or the device screen turning off.
When the activity moves to the Resumed state, any lifecycle-aware component
tied to the activity's lifecycle receives the ON_RESUME event. This is where the
lifecycle components can enable any functionality that needs to run while the
component is visible and in the foreground, such as starting a camera preview.
When an interruptive event occurs, the activity enters the Paused state and the
system invokes the onPause() callback.
If the activity returns to the Resumed state from the Paused state, the system once
again calls the onResume() method. For this reason, implement onResume() to
initialize components that you release during onPause() and to perform any other
initializations that must occur each time the activity enters the Resumed state.
onPause()

The system calls this method as the first indication that the user is leaving your
activity, though it does not always mean the activity is being destroyed. It
indicates that the activity is no longer in the foreground, but it is still visible if the
user is in multi-window mode. There are several reasons why an activity might
enter this state:
 An event that interrupts app execution, as described in the section about
the onResume() callback, pauses the current activity. This is the most common
case.
 In multi-window mode, only one app has focus at any time, and the system
pauses all the other apps.
 The opening of a new, semi-transparent activity, such as a dialog, pauses the
activity it covers. As long as the activity is partially visible but not in focus, it
remains paused.
onStop()

When your activity is no longer visible to the user, it enters the Stopped state, and
the system invokes the onStop() callback. This can occur when a newly launched
activity covers the entire screen. The system also calls onStop() when the activity
finishes running and is about to be terminated.
When the activity moves to the Stopped state, any lifecycle-aware component
tied to the activity's lifecycle receives the ON_STOP event. This is where the
lifecycle components can stop any functionality that does not need to run while
the component is not visible on the screen.
In the onStop() method, release or adjust resources that are not needed while the
app is not visible to the user. For example, your app might pause animations or
switch from fine-grained to coarse-grained location updates.
Using onStop() instead of onPause() means that UI-related work continues, even
when the user is viewing your activity in multi-window mode.
onDestroy()

onDestroy() is called before the activity is destroyed. The system invokes this
callback for one of two reasons:
1. The activity is finishing, due to the user completely dismissing the activity or due
to finish() being called on the activity.
2. The system is temporarily destroying the activity due to a configuration change,
such as device rotation or entering multi-window mode.
When the activity moves to the destroyed state, any lifecycle-aware component
tied to the activity's lifecycle receives the ON_DESTROY event. This is where
the lifecycle components can clean up anything they need to before
the Activity is destroyed.
Instead of putting logic in your Activity to determine why it is being destroyed,
use a ViewModel object to contain the relevant view data for your Activity. If
the Activity is recreated due to a configuration change, the ViewModel does not
have to do anything, since it is preserved and given to the next Activity instance.
If the Activity isn't recreated, then the ViewModel has the onCleared() method
called, where it can clean up any data it needs to before being destroyed. You can
distinguish between these two scenarios with the isFinishing() method.
If the activity is finishing, onDestroy() is the final lifecycle callback the activity
receives. If onDestroy() is called as the result of a configuration change, the
system immediately creates a new activity instance and then calls onCreate() on
that new instance in the new configuration.

Configuration change occurs


There are a number of events that can trigger a configuration change. Perhaps the
most prominent example is a change between portrait and landscape orientations.
Other cases that can cause configuration changes include changes to language
settings or input device.
When a configuration change occurs, the activity is destroyed and recreated. This
triggers the following callbacks in the original activity instance:
1. onPause()
2. onStop()
3. onDestroy()
A new instance of the activity is created, and the following callbacks are
triggered:
1. onCreate()
2. onStart()
3. onResume()
Use a combination of ViewModel instances, the onSaveInstanceState() method,
or persistent local storage to preserve an activity’s UI state across configuration
changes. Deciding how to combine these options depends on the complexity of
your UI data, use cases for your app, and consideration of the speed of retrieval
versus memory usage. For more information about saving your activity UI state,
see Save UI states.
Intents and intent filters

An Intent is a messaging object you can use to request an action from


another app component. Although intents facilitate communication between
components in several ways, there are three fundamental use cases:
 Starting an activity
An Activity represents a single screen in an app. You can start a new instance of
an Activity by passing an Intent to startActivity(). The Intent describes the
activity to start and carries any necessary data.
If you want to receive a result from the activity when it finishes,
call startActivityForResult(). Your activity receives the result as a
separate Intent object in your activity's onActivityResult() callback. For more
information, see the Activities guide.
 Starting a service
A Service is a component that performs operations in the background without a
user interface. With Android 5.0 (API level 21) and later, you can start a service
with JobScheduler. For more information about JobScheduler, see its API-
reference documentation.
For versions earlier than Android 5.0 (API level 21), you can start a service by
using methods of the Service class. You can start a service to perform a one-time
operation (such as downloading a file) by passing an Intent to startService().
The Intent describes the service to start and carries any necessary data.
If the service is designed with a client-server interface, you can bind to the
service from another component by passing an Intent to bindService(). For more
information, see the Services guide.
 Delivering a broadcast
A broadcast is a message that any app can receive. The system delivers various
broadcasts for system events, such as when the system boots up or the device
starts charging. You can deliver a broadcast to other apps by passing
an Intent to sendBroadcast() or sendOrderedBroadcast().
The rest of this page explains how intents work and how to use them. For related
information, see Interacting with Other Apps and Sharing Content.

Intent types
There are two types of intents:
 Explicit intents specify which component of which application will satisfy the
intent, by specifying a full ComponentName. You'll typically use an explicit
intent to start a component in your own app, because you know the class name of
the activity or service you want to start. For example, you might start a new
activity within your app in response to a user action, or start a service to
download a file in the background.
 Implicit intents do not name a specific component, but instead declare a general
action to perform, which allows a component from another app to handle it. For
example, if you want to show the user a location on a map, you can use an
implicit intent to request that another capable app show a specified location on a
map.
Receiving an implicit intent

To advertise which implicit intents your app can receive, declare one or more
intent filters for each of your app components with an <intent-filter> element in
your manifest file. Each intent filter specifies the type of intents it accepts based
on the intent's action, data, and category. The system delivers an implicit intent to
your app component only if the intent can pass through one of your intent filters.
An app component should declare separate filters for each unique job it can do.
For example, one activity in an image gallery app may have two filters: one filter
to view an image, and another filter to edit an image. When the activity starts, it
inspects the Intent and decides how to behave based on the information in
the Intent (such as to show the editor controls or not).
Each intent filter is defined by an <intent-filter> element in the app's manifest
file, nested in the corresponding app component (such as an <activity> element).
In each app component that includes an <intent-filter> element, explicitly set a
value for android:exported. This attribute indicates whether the app component is
accessible to other apps. In some situations, such as activities whose intent filters
include the LAUNCHER category, it's useful to set this attribute to true.
Otherwise, it's safer to set this attribute to false.
Inside the <intent-filter>, you can specify the type of intents to accept using one
or more of these three elements:
<action>
Declares the intent action accepted, in the name attribute. The value must
be the literal string value of an action, not the class constant.
<data>
Declares the type of data accepted, using one or more attributes that specify
various aspects of the data URI (scheme, host, port, path) and MIME type.
<category>
Declares the intent category accepted, in the name attribute. The value must
be the literal string value of an action, not the class constant.
here's an activity declaration with an intent filter to receive
an ACTION_SEND intent when the data type is text:
<activityandroid:name="ShareActivity"android:exported="false">
<intent-filter>
<actionandroid:name="android.intent.action.SEND"/>
<categoryandroid:name="android.intent.category.DEFAULT"/>
<dataandroid:mimeType="text/plain"/>
</intent-filter>
</activity>
Example filters

To demonstrate some of the intent filter behaviors, here is an example from the
manifest file of a social-sharing app:
<activityandroid:name="MainActivity"android:exported="true">
<!-- This activity is the main entry, should appear in app launcher -->
<intent-filter>
<actionandroid:name="android.intent.action.MAIN"/>
<categoryandroid:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>

<activityandroid:name="ShareActivity"android:exported="false">
<!-- This activity handles "SEND" actions with text data -->
<intent-filter>
<actionandroid:name="android.intent.action.SEND"/>
<categoryandroid:name="android.intent.category.DEFAULT"/>
<dataandroid:mimeType="text/plain"/>
</intent-filter>
<!-- This activity also handles "SEND" and "SEND_MULTIPLE" with media
data -->
<intent-filter>
<actionandroid:name="android.intent.action.SEND"/>
<actionandroid:name="android.intent.action.SEND_MULTIPLE"/>
<categoryandroid:name="android.intent.category.DEFAULT"/>
<dataandroid:mimeType="application/vnd.google.panorama360+jpg"/>
<dataandroid:mimeType="image/*"/>
<dataandroid:mimeType="video/*"/>
</intent-filter>
</activity>
The first activity, MainActivity, is the app's main entry point—the activity that
opens when the user initially launches the app with the launcher icon:
 The ACTION_MAIN action indicates this is the main entry point and does not
expect any intent data.
 The CATEGORY_LAUNCHER category indicates that this activity's icon
should be placed in the system's app launcher. If the <activity> element does not
specify an icon with icon, then the system uses the icon from
the <application> element.
These two must be paired together in order for the activity to appear in the app
launcher.
The second activity, ShareActivity, is intended to facilitate sharing text and
media content. Although users might enter this activity by navigating to it
from MainActivity, they can also enter ShareActivity directly from another app
that issues an implicit intent matching one of the two intent filters.
Permissions on Android

App permissions help support user privacy by protecting access to the following:
 Restricted data, such as system state and users' contact information
 Restricted actions, such as connecting to a paired device and recording audio
Figure 1 illustrates the workflow for using app permissions
Types of permissions

Android categorizes permissions into different types, including install-time


permissions, runtime permissions, and special permissions.
Install-time permissions

Install-time permissions give your app limited access to restricted data or let your
app perform restricted actions that minimally affect the system or other apps.
When you declare install-time permissions in your app, an app store presents an
install-time permission notice to the user when they view an app's details page, as
shown in figure 2. The system automatically grants your app the permissions
when the user installs your app.
Android includes several sub-types of install-time permissions, including normal
permissions and signature permissions.

Normal permissions

These permissions allow access to data and actions that extend beyond your app's
sandbox but present very little risk to the user's privacy and the operation of other
apps.
The system assigns the normal protection level to normal permissions.

Signature permissions

The system grants a signature permission to an app only when the app is signed
by the same certificate as the app or the OS that defines the permission.
Applications that implement privileged services, such as autofill or VPN
services, also make use of signature permissions. These apps require service-
binding signature permissions so that only the system can bind to the services.
The system assigns the signature protection level to signature permissions.
Runtime permissions

Runtime permissions, also known as dangerous permissions, give your app


additional access to restricted data or let your app perform restricted actions that
more substantially affect the system and other apps. Therefore, you need
to request runtime permissions in your app before you can access the restricted
data or perform restricted actions. Don't assume that these permissions have been
previously granted—check them and, if needed, request them before each access.
When your app requests a runtime permission, the system presents a runtime
permission prompt, as shown in figure 3.
Many runtime permissions access private user data, a special type of restricted
data that includes potentially sensitive information. Examples of private user data
include location and contact information.
The microphone and camera provide access to particularly sensitive information.
Therefore, the system helps you explain why your app accesses this information.
The system assigns the dangerous protection level to runtime permissions.
Special permissions

Special permissions correspond to particular app operations. Only the platform


and OEMs can define special permissions. Additionally, the platform and OEMs
usually define special permissions when they want to protect access to
particularly powerful actions, such as drawing over other apps.
The Special app access page in system settings contains a set of user-toggleable
operations. Many of these operations are implemented as special permissions.
Learn more about how to request special permissions.
Declare app permissions

As mentioned in the workflow for using permissions, if your app requests app
permissions, you must declare these permissions in your app's manifest file.
These declarations help app stores and users understand the set of permissions
that your app might request.
The process to request a permission depends on the type of permission:
 If the permission is an install-time permission, such as a normal permission or a
signature permission, the permission is granted automatically at install time.
 If the permission is a runtime permission or special permission, and if your app is
installed on a device that runs Android 6.0 (API level 23) or higher, you must
request the runtime permission or special permission yourself.

Add declaration to app manifest


To declare a permission that your app might request, include the
appropriate <uses-permission> element in your app's manifest file. For example,
an app that needs to access the camera has this line in AndroidManifest.xml:
<manifest ...>
<uses-permissionandroid:name="android.permission.CAMERA"/>
<application ...>
...
</application>
</manifest>
Android StudioAndroid Studio is the official Integrated Development
Environment (IDE) for Android app development. Based on the powerful code
editor and developer tools from IntelliJIDEA , Android Studio offers even more
features that enhance your productivity when building Android apps, such as:
 A flexible Gradle-based build system
 A fast and feature-rich emulator
 A unified environment where you can develop for all Android devices
 Live Edit to update composables in emulators and physical devices in real time
 Code templates and GitHub integration to help you build common app features
and import sample code
 Extensive testing tools and frameworks
 Lint tools to catch performance, usability, version compatibility, and other
problems
 C++ and NDK support
 Built-in support for Google Cloud Platform, making it easy to integrate Google
Cloud Messaging and App Engine

Project structure
Each project in Android Studio contains one or more modules with source code
files and resource files. The types of modules include:
 Android app modules
 Library modules
 Google App Engine modules
By default, Android Studio displays your project files in the Android project
view, as shown in figure 1. This view is organized by modules to provide quick
access to your project's key source files. All the build files are visible at the top
level, under Gradle Scripts.
Each app module contains the following folders:
 manifests: Contains the AndroidManifest.xml file.
 java: Contains the Kotlin and Java source code files, including JUnit test code.
 res: Contains all non-code resources such as UI strings and bitmap images.
The Android project structure on disk differs from this flattened representation.
To see the actual file structure of the project, select Project instead
of Android from the Project menu.

Gradle build system

Android Studio uses Gradle as the foundation of the build system, with more
Android-specific capabilities provided by the Android Gradle plugin. This build
system runs as an integrated tool from the Android Studio menu and
independently from the command line. You can use the features of the build
system to do the following:
 Customize, configure, and extend the build process.
 Create multiple APKs for your app with different features, using the same project
and modules.
 Reuse code and resources across source sets.
By employing the flexibility of Gradle, you can achieve all of this without
modifying your app's core source files.
Android Studio build files are named build.gradle.kts if you
use Kotlin (recommended) or build.gradle if you use Groovy. They are plain text
files that use the Kotlin or Groovy syntax to configure the build with elements
provided by the Android Gradle plugin. Each project has one top-level build file
for the entire project and separate module-level build files for each module.
When you import an existing project, Android Studio automatically generates the
necessary build files.

You might also like