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

Final Android Manual

The document discusses application fundamentals in Android development. It covers the application workflow which includes setting up the workspace, writing the app code, building and running, debugging and testing, and publishing. It also discusses app components like activities, services, broadcast receivers, and content providers which serve as entry points for an app. Activities have lifecycle states like active, visible, stopped and destroyed which are important to understand for state management.

Uploaded by

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

Final Android Manual

The document discusses application fundamentals in Android development. It covers the application workflow which includes setting up the workspace, writing the app code, building and running, debugging and testing, and publishing. It also discusses app components like activities, services, broadcast receivers, and content providers which serve as entry points for an app. Activities have lifecycle states like active, visible, stopped and destroyed which are important to understand for state management.

Uploaded by

wali ahmed
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 96

ANDROID CONTENETS MANUAL

Topic: Application Fundamentals

Developer workflow basics


The workflow to develop an app for Android is conceptually the same as other app platforms.
However, to efficiently build a well-designed app for Android, you need some specialized tools.
The following list provides an overview of the process to build an Android app and includes
links to some Android Studio tools you should use during each phase of development.

1. Set up your workspace

This is the phase you probably already finished:Install Android Studio and create a project.
For a walkthrough with Android Studio that teaches some Android development fundamentals,
also check out the guide toBuilding your first app.
2. Write your app

Now you can get to work. Android Studio includes a variety of tools and intelligence to help you
work faster, write quality code, design a UI, and create resources for different device types. For
more information about the tools and features available, see Write your app.
3. Build and run

During this phase, you build your project into a debuggable APK package that you can install
and run on the emulator or an Android-powered device. For more information about how to run
your code, see Build and run your app.
You can also begin customizing your build. For example, you can create build variants that
produce different types of APKs from the same project, and shrink your code and resources to
make your APK file smaller. For an introduction to customizing your build, see Configure your
build.
4. Debug, profile, and test

This is the iterative phase in which you continue writing your app but with a focus on
eliminating bugs and optimizing app performance. Of course, creating tests will help you in
those endeavors.
For information about basic debugging tasks, read Debug your app and Write and view logs.
To view and analyze various performance metrics such as memory usage, network traffic, CPU
impact, and more, see Performance profiling tools.
And for an introduction to building tests, see Test your app.
5. Publish

When you're ready to release your app to users, there are just a few more things to consider, such
as versioning your app and signing it with a key
Topic: Application Fundamentals

Android apps can be written using Kotlin, Java, and C++ languages.

The Android SDK tools compile your code along with any data and resource files into an
APK, an Android package, which is an archive file with an .apk suffix.

One APK file contains all the contents of an Android app and is the file that Android-powered
devices use to install the app.

Each Android app lives in its own security sandbox, protected by the following Android security
features:

 The Android operating system is a multi-user Linux system in which each app is a different user.
 By default, the system assigns each app a unique Linux user ID (the ID is used only by the
system and is unknown to the app). The system sets permissions for all the files in an app so that
only the user ID assigned to that app can access them.
 Each process has its own virtual machine (VM), so an app's code runs in isolation from other
apps.
 By default, every app runs in its own Linux process. The Android system starts the process when
any of the app's components need to be executed, and then shuts down the process when it's no
longer needed or when the system must recover memory for other apps.

The Android system implements the principle of least privilege. That is, each app, by default,
has access only to the components that it requires to do its work and no more. This creates a very
secure environment in which an app cannot access parts of the system for which it is not given
permission. However, there are ways for an app to share data with other apps and for an app to
access system services:

 It's possible to arrange for two apps to share the same Linux user ID, in which case they are able
to access each other's files. To conserve system resources, apps with the same user ID can also
arrange to run in the same Linux process and share the same VM. The apps must also be signed
with the same certificate.
 An app can request permission to access device data such as the user's contacts, SMS
messages, the mountable storage (SD card), camera, and Bluetooth. The user has to explicitly
grant these permissions.

App components
App components are the essential building blocks of an Android app. Each component is an
entry point through which the system or a user can enter your app. Some components depend on
others.

There are FOUR different types of app components:

1. Activities
2. Services
3. Broadcast receivers
4. Content providers

Each type serves a distinct purpose and has a distinct lifecycle that defines how the component
is created and destroyed.

The following sections describe the four types of app components.

1) Activities

Activities are one of the fundamental building blocks of apps on the Android platform.
They serve as the entry point for a user's interaction with an app, and are also central to
how a user navigates within an app (as with the Back button) or between apps (as with
the Recents button).

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

For example

A camera app can start the activity in the email app that composes new mail to allow the user to
share a picture. An activity facilitates the following key interactions between system and app:

 Keeping track of what the user currently cares about (what is on screen) to ensure that the
system keeps running the process that is hosting the activity.
 Knowing that previously used processes contain things the user may return to (stopped
activities), and thus more highly prioritize keeping those processes around.
 Helping the app handle having its process killed so the user can return to activities with
their previous state restored.
 Providing a way for apps to implement user flows between each other, and for the system
to coordinate these flows. (The most classic example here being share.)

Skillfully managing activities allows you to ensure:

 Orientation changes take place smoothly without disrupting the user experience.
 User data is not lost during activity transitions.
 The system kills processes when it's appropriate to do so.

Activity Lifecycle
Activities in the system are managed as activity stacks. When a new activity is started, it is
usually placed on the top of the current stack and becomes the running activity -- the previous
activity always remains below it in the stack, and will not come to the foreground again until the
new activity exits. There can be one or multiple activity stacks visible on screen.

An activity has essentially FOUR states:

1. If an activity is in the foreground of the screen (at the highest position of the topmost stack), it is
ACTIVE OR RUNNING. This is usually the activity that the user is currently interacting with.
2. If an activity has lost focus but is still presented to the user, it is VISIBLE.
3. If an activity is completely obscured by another activity, it is STOPPED OR HIDDEN. It still retains all
state and member information, however, it is no longer visible to the user so its window is hidden and it
will often be killed by the system when memory is needed elsewhere.
4. The system can drop the activity from memory by either asking it to finish, or simply killing its process,
making it Destroyed. When it is displayed again to the user, it must be completely restarted and restored
to its previous state.

The following diagram shows the important state paths of an Activity.

The square rectangles represent callback methods you can implement to perform operations
when the Activity moves between states.

The colored ovals are major states the Activity can be in.
There are THREE key LOOPS you may be interested in monitoring within your activity:

1. The entire lifetime of an activity happens between the first call to onCreate(Bundle) through to a single
final call to onDestroy(). An activity will do all setup of "global" state in onCreate(), and release all
remaining resources in onDestroy().
For example, if it has a thread running in the background to download data from the network, it may
create that thread in onCreate() and then stop the thread in onDestroy().

2. The visible lifetime of an activity happens between a call to onStart() until a corresponding call to
onStop(). During this time the user can see the activity on-screen, though it may not be in the foreground
and interacting with the user. Between these two methods you can maintain resources that are needed to
show the activity to the user.
For example, you can register a BroadcastReceiver in onStart() to monitor for changes that impact your
UI, and unregister it in onStop() when the user no longer sees what you are displaying. The onStart() and
onStop() methods can be called multiple times, as the activity becomes visible and hidden to the user.
3. The foreground lifetime of an activity happens between a call to onResume() until a corresponding call
to onPause(). During this time the activity is in visible, active and interacting with the user. An activity
can frequently go between the resumed and paused states.
For example when the device goes to sleep, when an activity result is delivered, when a new intent is
delivered -- so the code in these methods should be fairly lightweight.

Ending Words:

The entire lifecycle of an activity is defined by the following Activity methods. All of these are
hooks that you can override to do appropriate work when the activity changes state.

All activities will implement onCreate(Bundle) to do their initial setup; many will also implement
onPause() to commit changes to data and prepare to pause interacting with the user, and onStop()
to handle no longer being visible on screen.

You should always call up to your superclass when implementing these methods.

_____________________________________________________________________________________

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.

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.

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

__________________________________________________________________________

NOTE

To use activities in your app, you must Register Information about them in the app’s manifest,
and you must Manage Activity Lifecycles appropriately.
Configuring Manifest
For your app to be able to use activities, you must declare the activities, and certain of their
attributes, in the manifest.

1) 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 ... >
<activity android:name=".ExampleActivity" />
...
</application ... >
...
</manifest >

Note:

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.

Note: After you publish your app, you should not change activity names. If you do, you might break some
functionality, such as app shortcuts. For more information on changes to avoid after publishing, see Things
That Cannot Change.

2) Declare Intent Filters


Intent filters are a very powerful feature of the Android platform. They provide the ability to
launch an activity based not only on an explicit request, but also an implicit one.

For example, an explicit request might tell the system to “Start the Send Email activity in the
Gmail app".
By contrast, an implicit request tells the system to “Start a Send Email screen in any activity
that can do the job."

When the system UI asks a user which app to use in performing a task, that’s an intent filter at
work.

Note:

You can take advantage of this feature by declaring

an <intent-filter> attribute in the <activity> element.

The definition of this element includes an <action> element and, optionally, a <category>
element and/or a <data> element.

These elements combine to specify the type of intent to which your activity can respond.

Example: The following code snippet shows

how to configure an activity that sends text data, and receives requests from other activities
to do so:

<activity android:name=".ExampleActivity" android:icon="@drawable/app_icon">


<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
</activity>

In above example,

 <action> element specifies that this activity sends data.


 Declaring the <category> element as DEFAULT enables the activity to receive launch requests.
 The <data> element specifies the type of data that this activity can send.

The following code snippet shows how to Call The Activity described above:

// Create the text message with a string


Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.setType("text/plain");
sendIntent.putExtra(Intent.EXTRA_TEXT, textMessage);

// Start the activity


startActivity(sendIntent);

If you intend for your app to be self-contained and not allow other apps to activate its activities, you don't
need any other intent filters.
Note: Activities that you don't want to make available to other applications should have no intent filters,
and you can start them yourself using explicit intents.

3) Declare Permissions:
You can use the manifest's <activity> tag to control which apps can start a particular activity.

A parent activity cannot launch a child activity unless both activities have the same permissions
in their manifest.

Note:

If you declare a <uses-permission> element for a particular activity, the calling activity must have
a matching <uses-permission> element.

Example:

If your app wants to use socialApp to share a post on social media, SocialApp itself must define
the permission that an app calling it must have:

<manifest>
<activity android:name="...."
android:permission=”com.google.socialapp.permission.SHARE_POST”

/>

Then, to be allowed to call SocialApp, your app must match the permission set in SocialApp's manifest:

<manifest>
<uses-permission android:name="com.google.socialapp.permission.SHARE_POST" />
</manifest>

____________________________________________________

Managing the activity lifecycle


Over the course of its lifetime, an activity goes through a number of states. You use a series of
callbacks to handle transitions between states.

The following sections introduce these callbacks.

public class Activity extends ApplicationContext {


protected void onCreate(Bundle savedInstanceState);

protected void onStart();

protected void onRestart();

protected void onResume();

protected void onPause();

protected void onStop();

protected void onDestroy();


}

In general the movement through an activity's lifecycle looks like this:

Method Description Killable? Next

onCreate() Called when the activity No onStart()


is first created. This is
where you should do all
of your normal static set
Method Description Killable? Next

up: create views, bind


data to lists, etc. This
method also provides you
with a Bundle containing
the activity's previously
frozen state, if there was
one.
Always followed
by onStart().

onRestart() Called after your activity No onStart()


has been stopped, prior to
it being started again.
Always followed
by onStart()

onStart() Called when the activity No onResume()or onS


is becoming visible to the top()
user.
Followed
by onResume() if the
activity comes to the
foreground, or onStop() if
it becomes hidden.

onResum Called when the activity No onPause()


e() will start interacting with
the user. At this point
your activity is at the top
of its activity stack, with
user input going to it.
Always followed
by onPause().

onPause( Called when the activity Pre- onResume()or


) loses foreground state, is Build.VERSION_CODES.HONE onStop()
no longer focusable or YCOMB
before transition to
stopped/hidden or
destroyed state. The
Method Description Killable? Next

activity is still visible to


user, so it's recommended
to keep it visually active
and continue updating the
UI. Implementations of
this method must be very
quick because the next
activity will not be
resumed until this method
returns.
Followed by
either onResume() if the
activity returns back to
the front, or onStop() if it
becomes invisible to the
user.

onStop() Called when the activity Yes onRestart()or


is no longer visible to the onDestroy()
user. This may happen
either because a new
activity is being started
on top, an existing one is
being brought in front of
this one, or this one is
being destroyed. This is
typically used to stop
animations and refreshing
the UI, etc.
Followed by
either onRestart() if this
activity is coming back to
interact with the user,
oronDestroy() if this
activity is going away.

onDestroy() The final call you receive Yes Nothing


before your activity is
destroyed. This can
Method Description Killable? Next

happen either because the


activity is finishing
(someone
called Activity#finish on
it), or because the system
is temporarily destroying
this instance of the
activity to save space.
You can distinguish
between these two
scenarios with
the Activity#isFinishingm
ethod.

onCreate()
You must implement this callback, which fires when the system creates your activity. Your
implementation should initialize the essential components of your activity:

For Example:

 your app should create views and bind data to lists here.

 Most importantly, this is where you must call setContentView() to define the layout for
the activity's user interface.

 When onCreate() finishes, the next callback is always onStart().

onStart()
As onCreate() exits, the activity enters the Started state, and the activity becomes VISIBLE to the
user.

This callback contains what amounts to the activity’s final preparations for coming to the
foreground and becoming interactive.
onResume()
The system invokes this callback just before the activity starts interacting with the user.

At this point, the activity is at the top of the activity stack, and captures all user input.

Most of an app’s core functionality is implemented in the onResume() method.

The onPause() callback always follows onResume().

onPause()
The system calls onPause() when the activity loses focus and enters a Paused state.

This state occurs when, for example, the user taps the Back or Recents button. When the system
calls onPause() for your activity, it technically means your activity is still partially visible, but
most often is an indication that the user is leaving the activity, and the activity will soon enter the
Stopped or Resumed state.

An activity in the Paused state may continue to update the UI if the user is expecting the UI to
update.

Examples of such an activity include one showing a navigation map screen or a media player
playing. Even if such activities lose focus, the user expects their UI to continue updating.

You should not use onPause() to save application or user data, make network calls, or execute
database transactions.

Once onPause() finishes executing, the next callback is either onStop() or onResume(), depending
on what happens after the activity enters the Paused state.

onStop()
The system calls onStop() when the activity is no longer visible to the user.

This may happen because:

 the activity is being destroyed.

 a new activity is starting.

 Or an existing activity is entering a Resumed state and is covering the stopped activity.

In all of these cases, the stopped activity is no longer visible at all.


The next callback that the system calls is either onRestart(), if the activity is coming back to
interact with the user, or by onDestroy() if this activity is completely terminating.

onRestart()
The system invokes this callback when an activity in the Stopped state is about to restart.
onRestart() restores the state of the activity from the time that it was stopped.

This callback is always followed by onStart().

onDestroy()
The system invokes this callback before an activity is destroyed.

This callback is the final one that the activity receives. onDestroy() is usually implemented to
ensure that all of an activity’s resources are released when the activity, or the process containing
it, is destroyed.

_____________________________________________________________________________________

Process Lifecycle
The Android system attempts to keep an application process around for as long as possible, but
eventually will need to remove old processes when memory runs low.

As described in Activity Lifecycle, the decision about which process to remove is intimately tied
to the state of the user's interaction with it.

In general, there are FOUR states a process can be in based on the activities running in it.

The system will kill less important processes (the last ones) before it resorts to killing more
important processes (the first ones).

1. The foreground activity (the activity at the top of the screen that the user is currently interacting
with) is considered the most important.

Its process will only be killed as a last resort, if it uses more memory than is available on the
device.

Generally at this point the device has reached a memory paging state, so this is required in order
to keep the user interface responsive.
2. A Visible Activity (an activity that is visible to the user but not in the foreground, such as one
sitting behind a foreground dialog or next to other activities in multi-window mode) is
considered extremely important and will not be killed unless that is required to keep the
foreground activity running.

3. A Background Activity (an activity that is not visible to the user and has been stopped) is no
longer critical, so the system may safely kill its process to reclaim memory for other foreground
or visible processes.

If its process needs to be killed, when the user navigates back to the activity (making it visible on
the screen again), its onCreate(Bundle) method will be called with the savedInstanceState it had
previously supplied in onSaveInstanceState(Bundle) so that it can restart itself in the same state as
the user last left it.

4. An Empty Process is one hosting No Activities or other application components (such


as Service orBroadcastReceiver classes).

These are killed very quickly by the system as memory becomes low.

For this reason, any background operation you do outside of an activity must be executed in the
context of an activity BroadcastReceiver or Service to ensure that the system knows it needs to
keep your process around.

Sometimes an Activity may need to do a long-running operation that exists independently of the
activity lifecycle itself.

An example may be a camera application that allows you to upload a picture to a web site. The
upload may take a long time, and the application should allow the user to leave the application
while it is executing.

To accomplish this, your Activity should start a Service in which the upload takes place. This
allows the system to properly prioritize your process (considering it to be more important than
other non-visible applications) for the duration of the upload, independent of whether the original
activity is paused, stopped, or finished.

Understand the Activity Lifecycle


https://developer.android.com/guide/components/activities/activity-lifecycle.html

_________________________________

2) Services
A service is a general-purpose entry point for keeping an app running in the background
for all kinds of reasons. It is a component that runs in the background to perform long-
running operations or to perform work for remote processes. A service does not provide a
user interface. For example, a service might play music in the background while the user
is in a different app, or it might fetch data over the network without blocking user
interaction with an activity. Another component, such as an activity, can start the service
and let it run or bind to it in order to interact with it. There are actually two very distinct
semantics services tell the system about how to manage an app: Started services tell the
system to keep them running until their work is completed. This could be to sync some
data in the background or play music even after the user leaves the app. Syncing data in
the background or playing music also represent two different types of started services that
modify how the system handles them:

 Music playback is something the user is directly aware of, so the app tells the system this
by saying it wants to be foreground with a notification to tell the user about it; in this case
the system knows that it should try really hard to keep that service's process running,
because the user will be unhappy if it goes away.
 A regular background service is not something the user is directly aware as running, so
the system has more freedom in managing its process. It may allow it to be killed (and
then restarting the service sometime later) if it needs RAM for things that are of more
immediate concern to the user.
Bound services run because some other app (or the system) has said that it wants to make
use of the service. This is basically the service providing an API to another process. The
system thus knows there is a dependency between these processes, so if process A is
bound to a service in process B, it knows that it needs to keep process B (and its service)
running for A. Further, if process A is something the user cares about, then it also knows
to treat process B as something the user also cares about. Because of their flexibility (for
better or worse), services have turned out to be a really useful building block for all kinds
of higher-level system concepts. Live wallpapers, notification listeners, screen savers,
input methods, accessibility services, and many other core system features are all built as
services that applications implement and the system binds to when they should be
running.

_______________________________________________________________________
Services overview
A Service is an application component that can perform long-running operations in the
background, and it doesn't provide a user interface.

Another application component can start a service, and it continues to run in the background
even if the user switches to another application.

Additionally, a component can bind to a service to interact with it and even perform interprocess
communication (IPC).

For Example:

 A service can handle network transactions.

 Play music.

 Perform file I/O.

 Interact with a content provider all from the background.

These are the THREE different types of services:

1) Foreground

A foreground service performs some operation that is noticeable to the user.

For Example:
An audio app would use a foreground service to play an audio track.

 Foreground services must display a Notification.


 Foreground services continue running even when the user isn't interacting with the app.

2) Background

A background service performs an operation that isn't directly noticed by the user.

For Example:

if an app used a service to Compact Its Storage, that would usually be a background service.
3) Bound

A service is bound when an application component binds to it by calling bindService().

A bound service offers a client-server interface that allows components to interact with the
service, send requests, receive results, and even do so across processes with interprocess
communication (IPC).

A bound service runs only as long as another application component is bound to it.

Note: Multiple components can bind to the service at once, but when all of them unbind, the
service is destroyed.

__________________________________________________________________________________

The basics
To create a service, you must create a subclass of Service or use one of its existing subclasses.

In your implementation, you must override some callback methods that handle key aspects of the
service lifecycle and provide a mechanism that allows the components to bind to the service, if
appropriate.

These are the most important callback methods that you should override:

onStartCommand()

The system invokes this method by calling startService() when another component (such as an
activity) requests that the service be started. When this method executes, the service is started and
can run in the background indefinitely.

If you implement this, it is your responsibility to stop the service when its work is complete by
calling stopSelf() or stopService(). If you only want to provide binding, you don't need to
implement this method.

onBind()

The system invokes this method by calling bindService() when another component wants to bind
with the service (such as to perform RPC).

In your implementation of this method, you must provide an interface that clients use to
communicate with the service by returning an IBinder. You must always implement this method;
however, if you don't want to allow binding, you should return null.
onCreate()

The system invokes this method to perform one-time setup procedures when the service is
initially created (before it calls either onStartCommand() or onBind()). If the service is already
running, this method is not called.

onDestroy()

The system invokes this method when the service is no longer used and is being destroyed. Your
service should implement this to clean up any resources such as threads, registered listeners, or
receivers. This is the last call that the service receives.

If a component starts the service by calling startService() (which results in a call


to onStartCommand()), the service continues to run until it stops itself with stopSelf() or another
component stops it by calling stopService().

If a component calls bindService() to create the service and onStartCommand() is not called, the
service runs only as long as the component is bound to it. After the service is unbound from all
of its clients, the system destroys it.

The Android system stops a service only when memory is low and it must recover system
resources for the activity that has user focus.

If the service is bound to an activity that has user focus, it's less likely to be killed; if the service
is declared to run in the foreground, it's rarely killed.

If the service is started and is long-running, the system lowers its position in the list of
background tasks over time, and the service becomes highly susceptible to killing—if your
service is started, you must design it to gracefully handle restarts by the system. If the system
kills your service, it restarts it as soon as resources become available, but this also depends on
the value that you return from onStartCommand().

__________________________________________________________________________
NOTE:

Lets see how to create the startService() and bindService() service methods, as well as how to use

them from other application components.

1) Declaring a service in the manifest


Note: You must declare all services in your application's manifest file, just as you do for
activities and other components.

To declare your service, add a <service> element as a child of the <application> element.

Here is an example:

<manifest ... >


...
<application ... >
<service android:name=".ExampleService" />
...
</application>
</manifest>

Creating a started service


A started service is one that another component starts by calling startService(), which results in a
call to the service's onStartCommand() method.

When a service is started, it has a lifecycle that's independent of the component that started it.

The service can run in the background indefinitely, even if the component that started it is
destroyed.

As such, the service should stop itself when its job is complete by calling stopSelf(), or another
component can stop it by calling stopService().

An application component such as an activity can start the service by calling startService() and
passing an Intent that specifies the service and includes any data for the service to use. The
service receives this Intent in the onStartCommand() method.
For instance, suppose an activity needs to save some data to an online database. The activity can
start a companion service and deliver it the data to save by passing an intent to startService(). The
service receives the intent in onStartCommand(), connects to the Internet, and performs the
database transaction. When the transaction is complete, the service stops itself and is destroyed.

Caution: A service runs in the same process as the application in which it is declared and in the main thread of
that application by default. If your service performs intensive or blocking operations while the user interacts
with an activity from the same application, the service slows down activity performance. To avoid impacting
application performance, start a new thread inside the service.

Traditionally, there are two classes you can extend to create a started service:

1) Service

This is the base class for all services. When you extend this class, it's important to create a new
thread in which the service can complete all of its work; the service uses your application's main
thread by default, which can slow the performance of any activity that your application is
running.

2) IntentService

This is a subclass of Service that uses a worker thread to handle all of the start requests, one at a
time. This is the best option if you don't require that your service handle multiple requests
simultaneously. Implement onHandleIntent(), which receives the intent for each start request so
that you can complete the background work.

Starting a service
You can start a service from an activity or other application component by passing
an Intent to startService() or startForegroundService(). The Android system calls the
service's onStartCommand() method and passes it the Intent, which specifies which service to start.

Note: If your app targets API level 26 or higher, the system imposes restrictions on using or creating
background services unless the app itself is in the foreground. If an app needs to create a foreground service,
the app should call startForegroundService(). That method creates a background service, but the method signals
to the system that the service will promote itself to the foreground. Once the service has been created, the
service must call its startForeground() method within five seconds.
For example, an activity can start the example service in the previous section (HelloService) using
an explicit intent with startService(), as shown here:

Intent(this, HelloService::class.java).also { intent ->


startService(intent)
}

The startService() method returns immediately, and the Android system calls the
service's onStartCommand() method. If the service isn't already running, the system first
calls onCreate(), and then it calls onStartCommand().

If the service doesn't also provide binding, the intent that is delivered with startService() is the
only mode of communication between the application component and the service. However, if
you want the service to send a result back, the client that starts the service can create
a PendingIntent for a broadcast (with getBroadcast()) and deliver it to the service in the Intent that
starts the service. The service can then use the broadcast to deliver a result.

Multiple requests to start the service result in multiple corresponding calls to the
service's onStartCommand(). However, only one request to stop the service
(with stopSelf() or stopService()) is required to stop it.

Stopping a service
A started service must manage its own lifecycle. That is, the system doesn't stop or destroy the
service unless it must recover system memory and the service continues to run
after onStartCommand() returns. The service must stop itself by calling stopSelf(), or another
component can stop it by calling stopService().

Once requested to stop with stopSelf() or stopService(), the system destroys the service as soon as
possible.

If your service handles multiple requests to onStartCommand() concurrently, you shouldn't stop
the service when you're done processing a start request, as you might have received a new start
request (stopping at the end of the first request would terminate the second one). To avoid this
problem, you can use stopSelf(int)to ensure that your request to stop the service is always based
on the most recent start request. That is, when you call stopSelf(int), you pass the ID of the start
request (the startId delivered to onStartCommand()) to which your stop request corresponds. Then,
if the service receives a new start request before you are able to call stopSelf(int), the ID doesn't
match and the service doesn't stop.

Caution: To avoid wasting system resources and consuming battery power, ensure that your application stops
its services when it's done working. If necessary, other components can stop the service by
calling stopService(). Even if you enable binding for the service, you must always stop the service yourself if it
ever receives a call to onStartCommand().

Creating a bound service


A bound service is one that allows application components to bind to it by calling bindService() to
create a long-standing connection. It generally doesn't allow components to start it by
calling startService().

Create a bound service when you want to interact with the service from activities and other
components in your application or to expose some of your application's functionality to other
applications through interprocess communication (IPC).

To create a bound service, implement the onBind() callback method to return an IBinder that
defines the interface for communication with the service. Other application components can then
call bindService() to retrieve the interface and begin calling methods on the service. The service
lives only to serve the application component that is bound to it, so when there are no
components bound to the service, the system destroys it. You do not need to stop a bound service
in the same way that you must when the service is started through onStartCommand().

To create a bound service, you must define the interface that specifies how a client can
communicate with the service. This interface between the service and a client must be an
implementation of IBinder and is what your service must return from the onBind() callback
method. After the client receives the IBinder, it can begin interacting with the service through that
interface.

Multiple clients can bind to the service simultaneously. When a client is done interacting with
the service, it calls unbindService() to unbind. When there are no clients bound to the service, the
system destroys the service.

There are multiple ways to implement a bound service, and the implementation is more
complicated than a started service. For these reasons, the bound service discussion appears in a
separate document about Bound Services.
Topic: Notification Overview

A notification is a message that Android displays outside your app's UI to provide the user with
reminders, communication from other people, or other timely information from your app. Users
can tap the notification to open your app or take an action directly from the notification.

This page provides an overview of where notifications appear and the available features.

Appearances on a device
Notifications appear to users in different locations and formats, such as an icon in the status bar,
a more detailed entry in the notification drawer, as a badge on the app's icon, and on paired
wearables automatically.

Notification anatomy
The design of a notification is determined by system templates—your app simply defines the
contents for each portion of the template. Some details of the notification appear only in the
expanded view.

Figure 7. A notification with basic details

The most common parts of a notification are indicated in figure 7 as follows:

1. Small icon: This is required and set with setSmallIcon().


2. App name: This is provided by the system.
3. Time stamp: This is provided by the system but you can override with setWhen() or hide it
with setShowWhen(false).
4. Large icon: This is optional (usually used only for contact photos; do not use it for your app icon)
and set with setLargeIcon().
5. Title: This is optional and set with setContentTitle().
6. Text: This is optional and set with setContentText().

Create a Notification
Notifications provide short, timely information about events in your app while it's not in use.
This page teaches you how to create a notification with various features for Android 4.0 (API
level 14) and higher.

Create a basic notification


A notification in its most basic and compact form (also known as collapsed form) displays an
icon, a title, and a small amount of content text.

Set the notification content


To get started, you need to set the notification's content and channel using
aNotificationCompat.Builder object. The following example shows how to create a notification
with the following:

 A small icon, set by setSmallIcon(). This is the only user-visible content that's required.
 A title, set by setContentTitle().
 The body text, set by setContentText().
 The notification priority, set by setPriority(). The priority determines how intrusive the notification should
be on Android 7.1 and lower.

 NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)


.setSmallIcon(R.drawable.notification_icon)
.setContentTitle(textTitle)
.setContentText(textContent)
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
By default, the notification's text content is truncated to fit one line. If you want your notification to

be longer, you can enable an expandable notification by adding a style template with setStyle().

For example, the following code creates a larger text area:

NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)


.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Much longer text that cannot fit one line...")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText("Much longer text that cannot fit one line..."))
.setPriority(NotificationCompat.PRIORITY_DEFAULT);

Sending notifications to the user


When a service is running, it can notify the user of events using Toast Notifications or Status Bar
Notifications.

A toast notification is a message that appears on the surface of the current window for only a
moment before disappearing. A status bar notification provides an icon in the status bar with a
message, which the user can select in order to take an action (such as start an activity).

Usually, a status bar notification is the best technique to use when background work such as a
file download has completed, and the user can now act on it. When the user selects the
notification from the expanded view, the notification can start an activity (such as to display the
downloaded file).
See the Toast Notifications or Status Bar Notifications developer guides for more information.

Running a service in the foreground


A foreground service is a service that the user is actively aware of and isn't a candidate for the
system to kill when low on memory. A foreground service must provide a notification for the
status bar, which is placed under the Ongoing heading. This means that the notification cannot be
dismissed unless the service is either stopped or removed from the foreground.

Caution: Limit your app's use of foreground services.

You should only use a foreground service when your app needs to perform a task that is noticeable by the user
even when they're not directly interacting with the app. For this reason, foreground services must show a status
bar notification with a priority of PRIORITY_LOW or higher, which helps ensure that the user is aware of
what your app is doing. If the action is of low enough importance that you want to use a minimum-priority
notification, you probably shouldn't be using a service; instead, consider using a scheduled job.

Every app that runs a service places an additional load on the system, consuming system resources. If an app
tries to hide its services by using a low-priority notification, this can impair the performance of the app the user
is actively interacting with. For this reason, if an app tries to run a service with a minimum-priority
notification, the system calls out the app's behavior in the notification drawer's bottom section.

For example, a music player that plays music from a service should be set to run in the
foreground, because the user is explicitly aware of its operation. The notification in the status bar
might indicate the current song and allow the user to launch an activity to interact with the music
player. Similarly, an app to let users track their runs would need a foreground service to track the
user's location.

Note: Apps that target Android 9 (API level 28) or higher and use foreground services must
request theFOREGROUND_SERVICE permission. This is a normal permission, so the system
automatically grants it to the requesting app.

If an app that targets API level 28 or higher attempts to create a foreground service without
requesting FOREGROUND_SERVICE, the system throws a SecurityException.

To request that your service run in the foreground, call startForeground(). This method takes two
parameters: an integer that uniquely identifies the notification and the Notification for the status
bar. The notification must have a priority of PRIORITY_LOW or higher. Here is an example:

val pendingIntent: PendingIntent =


Intent(this, ExampleActivity::class.java).let { notificationIntent ->
PendingIntent.getActivity(this, 0, notificationIntent, 0)
}

val notification: Notification = Notification.Builder(this, CHANNEL_DEFAULT_IMPORTANCE)


.setContentTitle(getText(R.string.notification_title))
.setContentText(getText(R.string.notification_message))
.setSmallIcon(R.drawable.icon)
.setContentIntent(pendingIntent)
.setTicker(getText(R.string.ticker_text))
.build()

startForeground(ONGOING_NOTIFICATION_ID, notification)

Caution: The integer ID that you give to startForeground() must not be 0.

To remove the service from the foreground, call stopForeground(). This method takes a boolean,
which indicates whether to remove the status bar notification as well. This method does not stop
the service. However, if you stop the service while it's still running in the foreground, the
notification is also removed.

For more information about notifications, see Creating Status Bar Notifications.

Managing the lifecycle of a service


The lifecycle of a service is much simpler than that of an activity. However, it's even more
important that you pay close attention to how your service is created and destroyed because a
service can run in the background without the user being aware.

The service lifecycle—from when it's created to when it's destroyed—can follow either of these
two paths:

 A started service
The service is created when another component calls startService(). The service then runs
indefinitely and must stop itself by calling stopSelf(). Another component can also stop the
service by calling stopService(). When the service is stopped, the system destroys it.
 A bound service
The service is created when another component (a client) calls bindService(). The client then
communicates with the service through an IBinder interface. The client can close the connection
by calling unbindService(). Multiple clients can bind to the same service and when all of them
unbind, the system destroys the service. The service does not need to stop itself.

These two paths aren't entirely separate. You can bind to a service that is already started
with startService(). For example, you can start a background music service by
calling startService() with an Intent that identifies the music to play. Later, possibly when the user
wants to exercise some control over the player or get information about the current song, an
activity can bind to the service by calling bindService(). In cases such as
this, stopService() or stopSelf() doesn't actually stop the service until all of the clients unbind.

Implementing the lifecycle callbacks


Like an activity, a service has lifecycle callback methods that you can implement to monitor
changes in the service's state and perform work at the appropriate times. The following skeleton
service demonstrates each of the lifecycle methods:

KOTLIN

class ExampleService : Service() {


private var startMode: Int = 0 // indicates how to behave if the service is killed
private var binder: IBinder? = null // interface for clients that bind
private var allowRebind: Boolean = false // indicates whether onRebind should be used

override fun onCreate() {


// The service is being created
}

override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {


// The service is starting, due to a call to startService()
return mStartMode
}

override fun onBind(intent: Intent): IBinder? {


// A client is binding to the service with bindService()
return mBinder
}

override fun onUnbind(intent: Intent): Boolean {


// All clients have unbound with unbindService()
return mAllowRebind
}

override fun onRebind(intent: Intent) {


// A client is binding to the service with bindService(),
// after onUnbind() has already been called
}

override fun onDestroy() {


// The service is no longer used and is being destroyed
}
}

Note: Unlike the activity lifecycle callback methods, you are not required to call the superclass
implementation of these callback methods.

Figure 2. The service lifecycle. The diagram on the left shows the lifecycle when the service is created
with startService()and the diagram on the right shows the lifecycle when the service is created
with bindService().

Figure 2 illustrates the typical callback methods for a service. Although the figure separates
services that are created by startService() from those created by bindService(), keep in mind that
any service, no matter how it's started, can potentially allow clients to bind to it. A service that
was initially started with onStartCommand() (by a client calling startService()) can still receive a
call to onBind() (when a client calls bindService()).

By implementing these methods, you can monitor these two nested loops of the service's
lifecycle:
 The entire lifetime of a service occurs between the time that onCreate() is called and the time
that onDestroy() returns. Like an activity, a service does its initial setup in onCreate() and releases all
remaining resources in onDestroy(). For example, a music playback service can create the thread where
the music is played in onCreate(), and then it can stop the thread in onDestroy().
Note: The onCreate() and onDestroy() methods are called for all services, whether they're created
by startService() or bindService().
 The active lifetime of a service begins with a call to either onStartCommand() or onBind(). Each method
is handed the Intent that was passed to either startService() or bindService().
If the service is started, the active lifetime ends at the same time that the entire lifetime ends (the
service is still active even after onStartCommand() returns). If the service is bound, the active
lifetime ends when onUnbind() returns.
Note: Although a started service is stopped by a call to either stopSelf() or stopService(), there isn't a respective
callback for the service (there's no onStop() callback). Unless the service is bound to a client, the system
destroys it when the service is stopped—onDestroy() is the only callback received.

For more information about creating a service that provides binding, see the Bound
Services document, which includes more information about the onRebind() callback method in
the section about Managing the lifecycle of a bound service.

____________________________________

3) Broadcast receivers
A broadcast receiver is a component that enables the system to deliver events to the app outside
of a regular user flow, allowing the app to respond to system-wide broadcast announcements.
Because broadcast receivers are another well-defined entry into the app, the system can deliver
broadcasts even to apps that aren't currently running. So, for example, an app can schedule an
alarm to post a notification to tell the user about an upcoming event... and by delivering that
alarm to a BroadcastReceiver of the app, there is no need for the app to remain running until the
alarm goes off. Many broadcasts originate from the system—for example, a broadcast
announcing that the screen has turned off, the battery is low, or a picture was captured. Apps can
also initiate broadcasts—for example, to let other apps know that some data has been downloaded
to the device and is available for them to use. Although broadcast receivers don't display a user
interface, they may create a status bar notification to alert the user when a broadcast event occurs.
More commonly, though, a broadcast receiver is just a gateway to other components and is
intended to do a very minimal amount of work. For instance, it might schedule a JobService to
perform some work based on the event with JobScheduler
Broadcasts overview
Android apps can send or receive broadcast messages from the Android system and other
Android apps, similar to the publish-subscribe design pattern. These broadcasts are sent when an
event of interest occurs. For example, the Android system sends broadcasts when various system
events occur, such as when the system boots up or the device starts charging. Apps can also send
custom broadcasts, for example, to notify other apps of something that they might be interested
in (for example, some new data has been downloaded).

Apps can register to receive specific broadcasts. When a broadcast is sent, the system
automatically routes broadcasts to apps that have subscribed to receive that particular type of
broadcast.

Generally speaking, broadcasts can be used as a messaging system across apps and outside of the
normal user flow. However, you must be careful not to abuse the opportunity to respond to
broadcasts and run jobs in the background that can contribute to a slow system performance, as
described in the following video.

About system broadcasts


The system automatically sends broadcasts when various system events occur, such as when the
system switches in and out of airplane mode. System broadcasts are sent to all apps that are
subscribed to receive the event.

The broadcast message itself is wrapped in an Intent object whose action string identifies the
event that occurred (for example android.intent.action.AIRPLANE_MODE). The intent may also
include additional information bundled into its extra field. For example, the airplane mode intent
includes a boolean extra that indicates whether or not Airplane Mode is on.

For more information about how to read intents and get the action string from an intent,
see Intents and Intent Filters.

For a complete list of system broadcast actions, see the BROADCAST_ACTIONS.TXT file in the
Android SDK. Each broadcast action has a constant field associated with it. For example, the
value of the
constantACTION_AIRPLANE_MODE_CHANGED is android.intent.action.AIRPLANE_MODE.
Documentation for each broadcast action is available in its associated constant field.
Changes to system broadcasts
As the Android platform evolves, it periodically changes how system broadcasts behave. Keep
the following changes in mind if your app targets Android 7.0 (API level 24) or higher, or if it's
installed on devices running Android 7.0 or higher.

Android 9

Beginning with Android 9 (API level 28),


The NETWORK_STATE_CHANGED_ACTION broadcast doesn't receive information about the
user's location or personally identifiable data.

In addition, if your app is installed on a device running Android 9 or higher, system broadcasts
from Wi-Fi don't contain SSIDs, BSSIDs, connection information, or scan results. To get this
information, callgetConnectionInfo() instead.

Android 8.0

Beginning with Android 8.0 (API level 26), the system imposes additional restrictions on
manifest-declared receivers.

If your app targets Android 8.0 or higher, you cannot use the manifest to declare a receiver for
most implicit broadcasts (broadcasts that don't target your app specifically). You can still use
a context-registered receiverwhen the user is actively using your app.

Android 7.0

Android 7.0 (API level 24) and higher don't send the following system broadcasts:

 ACTION_NEW_PICTURE
 ACTION_NEW_VIDEO

Also, apps targeting Android 7.0 and higher must register


the CONNECTIVITY_ACTION broadcast using registerReceiver(BroadcastReceiver, IntentFilter).
Declaring a receiver in the manifest doesn't work.

Receiving broadcasts
Apps can receive broadcasts in two ways: through manifest-declared receivers and context-
registered receivers.
Manifest-declared receivers
If you declare a broadcast receiver in your manifest, the system launches your app (if the app is
not already running) when the broadcast is sent.

Note: If your app targets API level 26 or higher, you cannot use the manifest to declare a receiver
for implicitbroadcasts (broadcasts that do not target your app specifically), except for a few implicit
broadcasts that are exempted from that restriction. In most cases, you can use scheduled jobs instead.

To declare a broadcast receiver in the manifest, perform the following steps:

1. Specify the <receiver> element in your app's manifest.


2. <receiver android:name=".MyBroadcastReceiver" android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="android.intent.action.INPUT_METHOD_CHANGED" />
</intent-filter>
</receiver>

1. The intent filters specify the broadcast actions your receiver subscribes to.
2. Subclass BroadcastReceiver and implement onReceive(Context, Intent). The broadcast receiver in
the following example logs and displays the contents of the broadcast:

private const val TAG = "MyBroadcastReceiver"

class MyBroadcastReceiver : BroadcastReceiver() {

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


StringBuilder().apply {
append("Action: ${intent.action}\n")
append("URI: ${intent.toUri(Intent.URI_INTENT_SCHEME)}\n")
toString().also { log ->
Log.d(TAG, log)
Toast.makeText(context, log, Toast.LENGTH_LONG).show()
}
}
}
}
The system package manager registers the receiver when the app is installed. The receiver then
becomes a separate entry point into your app which means that the system can start the app and
deliver the broadcast if the app is not currently running.

The system creates a new BroadcastReceiver component object to handle each broadcast that it
receives. This object is valid only for the duration of the call to onReceive(Context, Intent). Once
your code returns from this method, the system considers the component no longer active.

Context-registered receivers
To register a receiver with a context, perform the following steps:

1. Create an instance of BroadcastReceiver.


val br: BroadcastReceiver = MyBroadcastReceiver()

2.Create an IntentFilter and register the receiver by calling registerReceiver(BroadcastReceiver, IntentFilter)

val filter = IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION).apply {


addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED)
}
registerReceiver(br, filter)

2. Context-registered receivers receive broadcasts as long as their registering context is valid. For
an example, if you register within an Activity context, you receive broadcasts as long as the
activity is not destroyed. If you register with the Application context, you receive broadcasts as
long as the app is running.
3. To stop receiving broadcasts, call unregisterReceiver(android.content.BroadcastReceiver). Be sure
to unregister the receiver when you no longer need it or the context is no longer valid.
Be mindful of where you register and unregister the receiver, for example, if you register a
receiver in onCreate(Bundle) using the activity's context, you should unregister it in onDestroy() to
prevent leaking the receiver out of the activity context. If you register a receiver in onResume(),
you should unregister it in onPause() to prevent registering it multiple times (If you don't want to
receive broadcasts when paused, and this can cut down on unnecessary system overhead). Do not
unregister in onSaveInstanceState(Bundle), because this isn't called if the user moves back in the
history stack.
Sending broadcasts
Android provides three ways for apps to send broadcast:

 The sendOrderedBroadcast(Intent, String) method sends broadcasts to one receiver at a time. As each
receiver executes in turn, it can propagate a result to the next receiver, or it can completely abort the
broadcast so that it won't be passed to other receivers. The order receivers run in can be controlled with
the android:priority attribute of the matching intent-filter; receivers with the same priority will be run in
an arbitrary order.
 The sendBroadcast(Intent) method sends broadcasts to all receivers in an undefined order. This is called a
Normal Broadcast. This is more efficient, but means that receivers cannot read results from other
receivers, propagate data received from the broadcast, or abort the broadcast.
 The LocalBroadcastManager.sendBroadcast method sends broadcasts to receivers that are in the same app
as the sender. If you don't need to send broadcasts across apps, use local broadcasts. The implementation
is much more efficient (no interprocess communication needed) and you don't need to worry about any
security issues related to other apps being able to receive or send your broadcasts.

The following code snippet demonstrates how to send a broadcast by creating an Intent and
calling sendBroadcast(Intent).

Intent().also { intent ->


intent.setAction("com.example.broadcast.MY_NOTIFICATION")
intent.putExtra("data", "Notice me senpai!")
sendBroadcast(intent)
}

The broadcast message is wrapped in an Intent object. The intent's action string must provide the app's
Java package name syntax and uniquely identify the broadcast event. You can attach additional
information to the intent with putExtra(String, Bundle). You can also limit a broadcast to a set of apps in
the same organization by calling setPackage(String) on the intent.

Restricting broadcasts with permissions


Permissions allow you to restrict broadcasts to the set of apps that hold certain permissions. You
can enforce restrictions on either the sender or receiver of a broadcast.

Sending with permissions


When you call sendBroadcast(Intent, String) or sendOrderedBroadcast(Intent, String,
BroadcastReceiver, Handler, int, String, Bundle), you can specify a permission parameter. Only
receivers who have requested that permission with the tag in their manifest (and subsequently
been granted the permission if it is dangerous) can receive the broadcast. For example, the
following code sends a broadcast:

sendBroadcast(Intent("com.example.NOTIFY"), Manifest.permission.SEND_SMS)

<uses-permission android:name="android.permission.SEND_SMS"/>

You can specify either an existing system permission like SEND_SMS or define a custom
permission with the<permission> element. For information on permissions and security in
general, see the System Permissions.

Note: Custom permissions are registered when the app is installed. The app that defines the custom
permission must be installed before the app that uses it.

Receiving with permissions


If you specify a permission parameter when registering a broadcast receiver (either
with registerReceiver(BroadcastReceiver, IntentFilter, String, Handler) or in <receiver> tag in your
manifest), then only broadcasters who have requested the permission with the <uses-
permission> tag in their manifest (and subsequently been granted the permission if it is
dangerous) can send an Intent to the receiver.

For example, assume your receiving app has a manifest-declared receiver as shown below:

<receiver android:name=".MyBroadcastReceiver"
android:permission="android.permission.SEND_SMS">
<intent-filter>
<action android:name="android.intent.action.AIRPLANE_MODE"/>
</intent-filter>
</receiver>

Or your receiving app has a context-registered receiver as shown below:

var filter = IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED)


registerReceiver(receiver, filter, Manifest.permission.SEND_SMS, null )

Then, to be able to send broadcasts to those receivers, the sending app must request the permission as
shown below:

<uses-permission android:name="android.permission.SEND_SMS"/>
______________________________________

4) Content providers
A content provider manages a shared set of app data that you can store in the file system, in a
SQLite database, on the web, or on any other persistent storage location that your app can access.
Through the content provider, other apps can query or modify the data if the content provider
allows it. For example, the Android system provides a content provider that manages the user's
contact information. As such, any app with the proper permissions can query the content
provider, such as 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 allows the
system to do in managing an app:

 Assigning a URI doesn't require that the app remain running, so URIs can persist after their
owning apps have exited. The system only needs to make sure that an owning app is still running
when it has to retrieve the app's data from the corresponding URI.
 These URIs also provide an important fine-grained security model. For example, an app can place
the URI for an image it has on the clipboard, but leave its content provider locked up so that other
apps cannot freely access it. When a second app attempts to access that URI on the clipboard,the
system can allow that app to access the data via a temporary URI permission grant so that it is
allowed to access the data only behind that URI, but nothing else in the second app.

Content providers are also useful for reading and writing data that is private to your app
and not shared.

Content providers
Content providers can help an application manage access to data stored by itself, stored by other
apps, and provide a way to share data with other apps. They encapsulate the data, and provide
mechanisms for defining data security. Content providers are the standard interface that connects
data in one process with code running in another process. Implementing a content provider has
many advantages. Most importantly you can configure a content provider to allow other
applications to securely access and modify your app data as illustrated in figure 1.
Figure 1. Overview diagram of how content providers manage access to storage.

Use content providers if you plan to share data. If you don’t plan to share data, you may still use
them because they provide a nice abstraction, but you don’t have to. This abstraction allows you
to make modifications to your application data storage implementation without affecting other
existing applications that rely on access to your data. In this scenario only your content provider
is affected and not the applications that access it. For example, you might swap out a SQLite
database for alternative storage as illustrated in figure 2.
Figure 2. Illustration of migrating content provider storage.

A number of other classes rely on the ContentProvider class:

 AbstractThreadedSyncAdapter
 CursorAdapter
 CursorLoader

If you are making use of any of these classes you also need to implement a content provider in
your application. Note that when working with the sync adapter framework you can also create a
stub content provider as an alternative. For more information about this topic, see Creating a stub
content provider. In addition, you need your own content provider in the following cases:

 You want to implement custom search suggestions in your application


 You need to use a content provider to expose your application data to widgets
 You want to copy and paste complex data or files from your application to other applications

The Android framework includes content providers that manage data such as audio, video,
images, and personal contact information. You can see some of them listed in the reference
documentation for theandroid.provider package. With some restrictions, these providers are
accessible to any Android application.

A content provider can be used to manage access to a variety of data storage sources, including
both structured data, such as a SQLite relational database, or unstructured data such as image
files. For more information on the types of storage available on Android, see Storage options, as
well as Designing data storage.

Advantages of content providers


Content providers offer granular control over the permissions for accessing data. You can choose
to restrict access to a content provider from solely within your application, grant blanket
permission to access data from other applications, or configure different permissions for reading
and writing data. For more information on using content providers securely, see Security tips for
storing data, as well as Content provider permissions.

You can use a content provider to abstract away the details for accessing different data sources in
your application. For example, your application might store structured records in a SQLite
database, as well as video and audio files. You can use a content provider to access all of this
data, if you implement this development pattern in your application.

Also note that CursorLoader objects rely on content providers to run asynchronous queries and
then return the results to the UI layer in your application. For more information on using a
CursorLoader to load data in the background, see Running a query with a CursorLoader.

The following topics describe content providers in more detail:

Content provider basics

How to access and update data using an existing content provider.

Creating a content provider

How to design and implement your own content provider.

Calendar provider

How to access the Calendar provider that is part of the Android platform.

Contacts provider

How to access the Contacts provider that is part of the Android platform.

For sample code related to this page, refer to the Basic Sync Adapter sample application
Store data
The most common security concern for an application on Android is whether the data that you
save on the device is accessible to other apps. There are three fundamental ways to save data on
the device:

 Internal storage.
 External storage.
 Content providers.
The following paragraphs describe the security issues associated with each approach.

Use internal storage


By default, files that you create on internal storage are accessible only to your app. Android
implements this protection, and it's sufficient for most applications.

Generally, avoid the MODE_WORLD_WRITEABLE or MODE_WORLD_READABLE modes


for IPC files because they do not provide the ability to limit data access to particular
applications, nor do they provide any control of data format. If you want to share your data with
other app processes, instead consider using a content provider, which offers read and write
permissions to other apps and can make dynamic permission grants on a case-by-case basis.

To provide additional protection for sensitive data, you can encrypt local files using a key that is
not directly accessible to the application. For example, you can place a key in a KeyStore and
protect it with a user password that is not stored on the device. While this does not protect data
from a root compromise that can monitor the user inputting the password, it can provide
protection for a lost device without file system encryption.

Use external storage


Files created on external storage, such as SD cards, are globally readable and writable. Because
external storage can be removed by the user and also modified by any application, don't store
sensitive information using external storage.

You should Perform input validation when handling data from external storage as you would
with data from any untrusted source. You should not store executables or class files on external
storage prior to dynamic loading. If your app does retrieve executable files from external storage,
the files should be signed and cryptographically verified prior to dynamic loading.
Use content providers
Content providers offer a structured storage mechanism that can be limited to your own
application or exported to allow access by other applications. If you do not intend to provide
other applications with access to your ContentProvider, mark them as android:exported=false in the
application manifest. Otherwise, set the android:exported attribute to true to allow other apps to
access the stored data.

When creating a ContentProvider that is exported for use by other applications, you can specify a
singlepermission for reading and writing, or you can specify distinct permissions for reading and
writing. You should limit your permissions to those required to accomplish the task at hand.
Keep in mind that it’s usually easier to add permissions later to expose new functionality than it
is to take them away and impact existing users.

If you are using a content provider for sharing data between only your own apps, it is preferable
to use theandroid:protectionLevel attribute set to signature protection. Signature permissions do not
require user confirmation, so they provide a better user experience and more controlled access to
the content provider data when the apps accessing the data are signed with the same key.

Content providers can also provide more granular access by declaring


the android:grantUriPermissionsattribute and using
the FLAG_GRANT_READ_URI_PERMISSION and FLAG_GRANT_WRITE_URI_PERMISSION fla
gs in the Intent object that activates the component. The scope of these permissions can be further
limited by the <grant-uri-permission> element.

When accessing a content provider, use parameterized query methods such as query(), update(),
anddelete() to avoid potential SQL injection from untrusted sources. Note that using
parameterized methods is not sufficient if the selection argument is built by concatenating user
data prior to submitting it to the method.

Don't have a false sense of security about the write permission. The write permission allows SQL
statements that make it possible for some data to be confirmed using creative WHERE clauses
and parsing the results. For example, an attacker might probe for the presence of a specific phone
number in a call log by modifying a row only if that phone number already exists. If the content
provider data has predictable structure, the write permission may be equivalent to providing both
reading and writing.

____________________

Activating components
Three of the four component types—activities, services, and broadcast receivers—are activated
by an asynchronous message called an intent. Intents bind individual components to each other at
runtime. You can think of them as the messengers that request an action from other components,
whether the component belongs to your app or another.

An intent is created with an Intent object, which defines a message to activate either a specific
component (explicit intent) or a specific type of component (implicit intent).

For activities and services, an intent defines the action to perform (for example,
to view or send something) and may specify the URI of the data to act on, among other things
that the component being started might need to know. For example, an intent might convey a
request for an activity to show an image or to open a web page. In some cases, you can start an
activity to receive a result, in which case the activity also returns the result in an Intent. For
example, you can issue an intent to let the user pick a personal contact and have it returned to
you. The return intent includes a URI pointing to the chosen contact.

For broadcast receivers, the intent simply defines the announcement being broadcast. For
example, a broadcast to indicate the device battery is low includes only a known action string
that indicates battery is low.

Unlike activities, services, and broadcast receivers, content providers are not activated by intents.
Rather, they are activated when targeted by a request from a ContentResolver. The content
resolver handles all direct transactions with the content provider so that the component that's
performing transactions with the provider doesn't need to and instead calls methods on
the ContentResolver object. This leaves a layer of abstraction between the content provider and
the component requesting information (for security).

There are separate methods for activating each type of component:

 You can start an activity or give it something new to do by passing


an Intent to startActivity() or startActivityForResult() (when you want the activity to return a result).
 With Android 5.0 (API level 21) and later, you can use the JobScheduler class to schedule actions. For
earlier Android versions, you can start a service (or give new instructions to an ongoing service) by
passing an Intent to startService(). You can bind to the service by passing an Intent tobindService().
 You can initiate a broadcast by passing an Intent to methods such
as sendBroadcast(), sendOrderedBroadcast(), or sendStickyBroadcast().
 You can perform a query to a content provider by calling query() on a ContentResolver.

For more information about using intents, see the Intents and Intent Filters document. The
following documents provide more information about activating specific
components: Activities, Services, BroadcastReceiver, andContent Providers.
The manifest file
Before the Android system can start an app component, the system must know that the
component exists by reading the app's manifest file, AndroidManifest.xml. Your app must declare
all its components in this file, which must be at the root of the app project directory.

The manifest does a number of things in addition to declaring the app's components, such as the
following:

 Identifies any user permissions the app requires, such as Internet access or read-access to the user's
contacts.
 Declares the minimum API Level required by the app, based on which APIs the app uses.
 Declares hardware and software features used or required by the app, such as a camera, bluetooth
services, or a multitouch screen.
 Declares API libraries the app needs to be linked against (other than the Android framework APIs), such
as the Google Maps library.

Declaring components
The primary task of the manifest is to inform the system about the app's components. For
example, a manifest file can declare an activity as follows:

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


<manifest ... >
<application android:icon="@drawable/app_icon.png" ... >
<activity android:name="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 do not declare in
the manifest are not visible to the system and, consequently, can never run. However, broadcast
receivers can be either declared in the manifest or created dynamically in code
as BroadcastReceiver objects and registered with the system by calling registerReceiver().

For more about how to structure the manifest file for your app, see The AndroidManifest.xml
Filedocumentation.

Declaring component capabilities


As discussed above, in Activating components, you can use an Intent to start activities, services,
and broadcast receivers. You can use an Intent by explicitly naming the target component (using
the component class name) in the intent. You can also use an implicit intent, which describes the
type of action to perform and, optionally, the data upon which you’d like to perform the action.
The implicit intent allows the system to find a component on the device that can perform the
action and start it. If there are multiple components that can perform the action described by the
intent, the user selects which one to use.

Caution: If you use an intent to start a Service, ensure that your app is secure by using an explicit intent. Using
an implicit intent to start a service is a security hazard because you cannot be certain what service will respond
to the intent, and the user cannot see which service starts. Beginning with Android 5.0 (API level 21), the
system throws an exception if you call bindService() with an implicit intent. Do not declare intent filters for
your services.

The system identifies the components that can respond to an intent by comparing the intent
received to the intent filters provided in the manifest file of other apps on the device.

When you declare an activity in your app's manifest, you can optionally include intent filters that
declare the capabilities of the activity so it can respond to intents from other apps. You can
declare an intent filter for your component by adding an <intent-filter> element as a child of the
component's declaration element.

For example, if you build an email app with an activity for composing a new email, you can
declare an intent filter to respond to "send" intents (in order to send a new email), as shown in
the following example:

<manifest ... >


...
<application ... >
<activity android:name="com.example.project.ComposeEmailActivity">
<intent-filter>
<action android:name="android.intent.action.SEND" />
<data android:type="*/*" />
<category android: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 may start your activity so the user can draft and send an email.

For more about creating intent filters, see the Intents and Intent Filters document.

Declaring app requirements


There are a variety of devices powered by Android and not all of them provide the same features
and capabilities. To prevent your app from being installed on devices that lack features needed
by your app, it's important that you clearly define a profile for the types of devices your app
supports by declaring device and software requirements in your manifest file. Most of these
declarations are informational only and the system does not read them, but external services such
as Google Play do read them in order to provide filtering for users when they search for apps
from their device.

For example, if your app requires a camera and uses APIs introduced in Android 2.1 (API
Level 7), you must declare these as requirements in your manifest file as shown in the following
example:

<manifest ... >


<uses-feature android:name="android.hardware.camera.any"
android:required="true" />
<uses-sdk android:minSdkVersion="7" android:targetSdkVersion="19" />
...
</manifest>

App resources
An Android app is composed of more than just code—it requires resources that are separate from
the source code, such as images, audio files, and anything relating to the visual presentation of
the app. For example, you can define animations, menus, styles, colors, and the layout of activity
user interfaces with XML files. Using app resources makes it easy to update various
characteristics of your app without modifying code. Providing sets of alternative resources
enables you to optimize your app for a variety of device configurations, such as different
languages and screen sizes.

For every resource that you include in your Android project, the SDK build tools define a unique
integer ID, which you can use to reference the resource from your app code or from other
resources defined in XML. For example, if your app contains an image file
named logo.png (saved in the res/drawable/ directory), the SDK tools generate a resource ID
named R.drawable.logo. This ID maps to an app-specific integer, which you can use to reference
the image and insert it in your user interface.

One of the most important aspects of providing resources separate from your source code is the
ability to provide alternative resources for different device configurations. For example, by
defining UI strings in XML, you can translate the strings into other languages and save those
strings in separate files. Then Android applies the appropriate language strings to your UI based
on a language qualifier that you append to the resource directory's name (such as res/values-fr/ for
French string values) and the user's language setting.

Android supports many different qualifiers for your alternative resources. The qualifier is a short
string that you include in the name of your resource directories in order to define the device
configuration for which those resources should be used. For example, you should create different
layouts for your activities, depending on the device's screen orientation and size. When the
device screen is in portrait orientation (tall), you might want a layout with buttons to be vertical,
but when the screen is in landscape orientation (wide), the buttons could be aligned horizontally.
To change the layout depending on the orientation, you can define two different layouts and
apply the appropriate qualifier to each layout's directory name. Then, the system automatically
applies the appropriate layout depending on the current device orientation.

For more about the different kinds of resources you can include in your application and how to
create alternative resources for different device configurations, read Providing Resources. To
learn more about best practices and designing robust, production-quality apps, see Guide to App
Architecture.

______________________________________________
Contents: Data & File Storage Techniques
Android provides several options for you to save your app data.

The solution you choose depends on your specific needs such as:

 How much space your data requires.

 What kind of data you need to store.

 Whether the data should be private to your app or accessible to other apps and the user.

Here are different data storage options available on Android:

1. Internal file storage: Store app-private files on the device file system.
2. External file storage: Store files on the SHARED external file system. This is usually for
shared user files, such as photos.
3. Shared preferences: Store private primitive data in key-value pairs.
4. Databases: Store structured data in a private database.

If you want to expose your app's data to other apps, you can use a ContentProvider.
Content providers give you full control of what read/write access is available to other
apps, regardless of the storage medium you've chosen for the data (though it's usually a
database).

Save files on device storage


Android uses a file system that's similar to disk-based file systems on other platforms.

Now you would learn that how to work with the Android file system to read and write files with
the File APIs.

A File object works well for reading or writing large amounts of data in start-to-finish order
without skipping around.

For example, it's good for image files or anything exchanged over a network.
Choose internal or external storage
All Android devices have two file storage areas: "internal" and "external" storage.

These names come from the early days of Android, when most devices offered built-in non-

volatile memory (internal storage), plus a removable storage medium such as a micro SD card
(external storage).

Many devices now divide the permanent storage space into separate "internal" and "external"

partitions. So even without a removable storage medium, these two storage spaces always exist,

and the API behavior is the same regardless of whether the external storage is removable.

Because the external storage might be removable, there are some differences between these two

options as follows.

1) Internal storage:

 It's always available.

 Files saved here are accessible by only your app.

 When the user uninstalls your app, the system removes all your app's files from internal
storage.

 Internal storage is best when you want to be sure that neither the user nor other apps can
access your files.

2) External storage:

 It's not always available, because the user can mount the external storage as USB storage.

 In some cases remove it from the device.

 It's world-readable, so files saved here may be read outside of your control.
 When the user uninstalls your app, the system removes your app's files from here only if
you save them in the directory from getExternalFilesDir().

 External storage is the best place for files that don't require access restrictions.

 Also for files that you want to share with other apps or allow the user to access with a
computer.

Internal cache files


If you'd like to keep some data temporarily, rather than store it persistently, you should use the
special cache directory to save the data.

Each App has a private cache directory specifically for these kinds of files.

When the device is low on internal storage space, Android may delete these cache files to
recover space.

However, you should not rely on the system to clean up these files for you.

You should always maintain the cache files yourself and stay within a reasonable limit of space
consumed, such as 1MB.

Note: When the user uninstalls your app, these files are removed.

2) External storage
Every Android device supports a shared "external storage" space that you can use to save files.

This space is called external because it's not guaranteed to be accessible.

it is a storage space that users can mount to a computer as an external storage device and it might
even be physically removable (such as an SD card).

Files saved to the external storage are world-readable and can be modified by the user when they
enable USB mass storage to transfer files on a computer.

So before you attempt to access a file in external storage in your app, you should check for the
availability of the external storage directories as well as the files you are trying to access.

Most often, you should use external storage for USER DATA that should be accessible to other
apps and saved even if the user uninstalls your app, such as captured photos or downloaded files.
The system provides standard public directories for these kinds of files, so the user has one
location for all their photos, ringtones, music, and such.

You can also save files to the external storage in an app-specific directory that the system deletes
when the user uninstalls your app.

Note: This might be a useful alternative to internal storage if you need more space, but the files

here aren't guaranteed to be accessible because the user might remove the storage SD card and

the files are still world readable; they're just saved to a location that's not shared with other apps.

3) Shared preferences
If you don't need to store a lot of data and it doesn't require structure, you should use
SharedPreferences.

The SharedPreferences APIs allow you to read and write persistent key-value pairs of primitive
data types: booleans, floats, ints, longs, and strings.

The key-value pairs are written to XML files that persist across user sessions, even if your app is
killed.

You can manually specify a name for the file or use per-activity files to save your data.

The API name "shared preferences" is a bit misleading because the API is not strictly for
saving "user preferences," such as what ringtone a user has chosen.

You can use SharedPreferences to save any kind of simple data, such as the user's high score.

However, if you do want to save user preferences for your app, then you should read how to
create a settings UI, which uses the AndroidX Preference Library to build a settings screen and
automatically persist the user's settings.

NOTE:

To learn how to store any type of key-value data, read Save Key-Value Data with
SharedPreferences.
4) Databases

Android provides full support for SQLite databases. Any database you create is accessible only
by your app.

However, instead of using SQLite APIs directly, we recommend that you create and interact with
your databases with the Room persistence library.

The Room library provides an object-mapping abstraction layer that allows fluent database
access while harnessing the full power of SQLite.

Although you can still save data directly with SQLite, the SQLite APIs are fairly low-level and
require a great deal of time and effort to use.

For example:

 There is no compile-time verification of raw SQL queries.


 As your schema changes, you need to update the affected SQL queries manually. This process can be
time consuming and error prone.
 You need to write lots of boilerplate code to convert between SQL queries and Java data objects.

The Room persistence library takes care of these concerns for you while providing an abstraction
layer over SQLite.

______________________________________________
Contents: Permissions Overview

The purpose of a permission is to protect the privacy of an Android user. Android apps must
request permission to access sensitive user data (such as contacts and SMS), as well as certain
system features (such as camera and internet). Depending on the feature, the system might grant
the permission automatically or might prompt the user to approve the request.

A central design point of the Android security architecture is that no app, by default, has
permission to perform any operations that would adversely impact other apps, the operating
system, or the user. This includes reading or writing the user's private data (such as contacts or
emails), reading or writing another app's files, performing network access, keeping the device
awake, and so on.

This page provides an overview to how Android permissions work, including: how permissions
are presented to the user, the difference between install-time and runtime permission requests,
how permissions are enforced, and the types of permissions and their groups.

Permission approval
An app must publicize the permissions it requires by including <uses-permission> tags in the app
manifest. For example, an app that needs to send SMS messages would have this line in the
manifest:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.snazzyapp">

<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.INTERNET"/>

<application ...>
...
</application>
</manifest>

If your app lists normal permissions in its manifest (that is, permissions that don't pose much risk
to the user's privacy or the device's operation), the system automatically grants those permissions
to your app.
If your app lists dangerous permissions in its manifest (that is, permissions that could potentially
affect the user's privacy or the device's normal operation), such as the SEND_SMS permission
above, the user must explicitly agree to grant those permissions.

Install-time requests

If the device is running Android 5.1.1 (API level 22) or lower, or the
app's targetSdkVersion is 22 or lower while running on any version of Android,
the system automatically asks the user to grant all dangerous permissions for your
app at install-time

Install-time permission dialog

If the user clicks Accept, all permissions the app requests are granted. If the user
denies the permissions request, the system cancels the installation of the app.

If an app update includes the need for additional permissions the user is prompted
to accept those new permissions before updating the app.

Runtime requests (Android 6.0 and higher)

Only dangerous permissions require user agreement. The way Android asks the
user to grant dangerous permissions depends on the version of Android running
on the user's device, and the system version targeted by your app.
If the device is running Android 6.0 (API level 23) or higher, and the
app's targetSdkVersion is 23 or higher, the user isn't notified of any app
permissions at install time.

Your app must ask the user to grant the dangerous permissions at runtime.

When your app requests permission, the user sees a system dialog telling the user
which permission group your app is trying to access.

The dialog includes a Deny and Allow button.

If the user denies the permission request, the next time your app requests the
permission, the dialog contains a checkbox that, when checked, indicates the user
doesn't want to be prompted for the permission again.

Initial permission dialog (left) and secondary permission request with option to turn off further
requests (right)

If the user checks the Never ask again box and taps Deny, the system no longer prompts the
user if you later attempt to requests the same permission.
Protection levels
Permissions are divided into several protection levels. The protection level affects whether
runtime permission requests are required.

There are three protection levels that affect third-party apps: normal, signature, and dangerous
permissions.

Normal permissions
Normal permissions cover areas where your app needs to access data or resources outside the
app's sandbox, but where there's very little risk to the user's privacy or the operation of other
apps. For example, permission to set the time zone is a normal permission.

If an app declares in its manifest that it needs a normal permission, the system automatically
grants the app that permission at install time. The system doesn't prompt the user to grant normal
permissions, and users cannot revoke these permissions.

As of Android 9 (API level 28), the following permissions are classified as


PROTECTION_NORMAL:

 ACCESS_LOCATION_EXTRA_COMMANDS
 ACCESS_NETWORK_STATE
 ACCESS_NOTIFICATION_POLICY
 ACCESS_WIFI_STATE
 BLUETOOTH
 BLUETOOTH_ADMIN
 BROADCAST_STICKY
 CHANGE_NETWORK_STATE
 CHANGE_WIFI_MULTICAST_STATE
 CHANGE_WIFI_STATE
 DISABLE_KEYGUARD
 EXPAND_STATUS_BAR
 FOREGROUND_SERVICE
 GET_PACKAGE_SIZE
 INSTALL_SHORTCUT
 INTERNET
 KILL_BACKGROUND_PROCESSES
 MANAGE_OWN_CALLS
 MODIFY_AUDIO_SETTINGS
 NFC
 READ_SYNC_SETTINGS
 READ_SYNC_STATS
 RECEIVE_BOOT_COMPLETED
 REORDER_TASKS
 REQUEST_COMPANION_RUN_IN_BACKGROUND
 REQUEST_COMPANION_USE_DATA_IN_BACKGROUND
 REQUEST_DELETE_PACKAGES
 REQUEST_IGNORE_BATTERY_OPTIMIZATIONS
 SET_ALARM
 SET_WALLPAPER
 SET_WALLPAPER_HINTS
 TRANSMIT_IR
 USE_FINGERPRINT
 VIBRATE
 WAKE_LOCK
 WRITE_SYNC_SETTINGS

Signature permissions
The system grants these app permissions at install time, but only when the app that attempts to
use a permission is signed by the same certificate as the app that defines the permission.

Note: Some signature permissions aren't for use by third-party apps.

As of Android 8.1 (API level 27), the following permissions that third-party apps can use are
classified as PROTECTION_SIGNATURE:

 BIND_ACCESSIBILITY_SERVICE
 BIND_AUTOFILL_SERVICE
 BIND_CARRIER_SERVICES
 BIND_CHOOSER_TARGET_SERVICE
 BIND_CONDITION_PROVIDER_SERVICE
 BIND_DEVICE_ADMIN
 BIND_DREAM_SERVICE
 BIND_INCALL_SERVICE
 BIND_INPUT_METHOD
 BIND_MIDI_DEVICE_SERVICE
 BIND_NFC_SERVICE
 BIND_NOTIFICATION_LISTENER_SERVICE
 BIND_PRINT_SERVICE
 BIND_SCREENING_SERVICE
 BIND_TELECOM_CONNECTION_SERVICE
 BIND_TEXT_SERVICE
 BIND_TV_INPUT
 BIND_VISUAL_VOICEMAIL_SERVICE
 BIND_VOICE_INTERACTION
 BIND_VPN_SERVICE
 BIND_VR_LISTENER_SERVICE
 BIND_WALLPAPER
 CLEAR_APP_CACHE
 MANAGE_DOCUMENTS
 READ_VOICEMAIL
 REQUEST_INSTALL_PACKAGES
 SYSTEM_ALERT_WINDOW
 WRITE_SETTINGS
 WRITE_VOICEMAIL

Dangerous permissions
Dangerous permissions cover areas where the app wants data or resources that involve the user's
private information, or could potentially affect the user's stored data or the operation of other
apps. For example, the ability to read the user's contacts is a dangerous permission. If an app
declares that it needs a dangerous permission, the user has to explicitly grant the permission to
the app. Until the user approves the permission, your app cannot provide functionality that
depends on that permission.

To use a dangerous permission, your app must prompt the user to grant permission at runtime.
For more details about how the user is prompted, see Request prompt for dangerous permission.

For a list of dangerous permissions, see table 1 below.


Special permissions
There are a couple of permissions that don't behave like normal and dangerous permissions.
SYSTEM_ALERT_WINDOW and WRITE_SETTINGS are particularly sensitive, so most apps
should not use them. If an app needs one of these permissions, it must declare the permission in
the manifest, and send an intent requesting the user's authorization. The system responds to the
intent by showing a detailed management screen to the user.

For details on how to request these permissions, see the SYSTEM_ALERT_WINDOW and
WRITE_SETTINGS reference entries.

All permissions provided by the Android system can be found at Manifest.permission.

Contents: Broadcast Receiver

Broadcasts overview
Android apps can send or receive broadcast messages from the Android system and
other Android apps, similar to the publish-subscribe design pattern. These broadcasts
are sent when an event of interest occurs. For example, the Android system sends
broadcasts when various system events occur, such as when the system boots up or
the device starts charging. Apps can also send custom broadcasts, for example, to
notify other apps of something that they might be interested in (for example, some new
data has been downloaded).

Apps can register to receive specific broadcasts. When a broadcast is sent, the system
automatically routes broadcasts to apps that have subscribed to receive that particular
type of broadcast.

Generally speaking, broadcasts can be used as a messaging system across apps and
outside of the normal user flow. However, you must be careful not to abuse the
opportunity to respond to broadcasts and run jobs in the background that can contribute
to a slow system performance, as described in the following video.

About system broadcasts


The system automatically sends broadcasts when various system events occur, such as
when the system switches in and out of airplane mode. System broadcasts are sent to
all apps that are subscribed to receive the event.

The broadcast message itself is wrapped in an Intent object whose action string
identifies the event that occurred (for example
android.intent.action.AIRPLANE_MODE). The intent may also include additional
information bundled into its extra field. For example, the airplane mode intent includes a
boolean extra that indicates whether or not Airplane Mode is on.

Receiving broadcasts
Apps can receive broadcasts in two ways: through manifest-declared receivers and
context-registered receivers.

Manifest-declared receivers
If you declare a broadcast receiver in your manifest, the system launches your app (if
the app is not already running) when the broadcast is sent.

Receiving broadcasts
Apps can receive broadcasts in two ways: through manifest-declared receivers and context-
registered receivers.

1) Manifest-declared receivers

If you declare a broadcast receiver in your manifest, the system launches your app (if the app is
not already running) when the broadcast is sent.

Note: If your app targets API level 26 or higher, you cannot use the manifest to declare a
receiver for implicit broadcasts (broadcasts that do not target your app specifically), except for a
few implicit broadcasts that are exempted from that restriction. In most cases, you can use
scheduled jobs instead.

To declare a broadcast receiver in the manifest, perform the following steps:

1. Specify the <receiver> element in your app's manifest.

<receiver android:name=".MyBroadcastReceiver" android:exported="true">


<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="android.intent.action.INPUT_METHOD_CHANGED" />
</intent-filter>
</receiver>

The intent filters specify the broadcast actions your receiver subscribes to.

2. Subclass BroadcastReceiver and implement onReceive(Context, Intent). The broadcast receiver in


the following example logs and displays the contents of the broadcast:

KotlinJavaMore

private const val TAG = "MyBroadcastReceiver"

class MyBroadcastReceiver : BroadcastReceiver() {

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


StringBuilder().apply {
append("Action: ${intent.action}\n")
append("URI: ${intent.toUri(Intent.URI_INTENT_SCHEME)}\n")
toString().also { log ->
Log.d(TAG, log)
Toast.makeText(context, log, Toast.LENGTH_LONG).show()
}
}
}
}

public class MyBroadcastReceiver extends BroadcastReceiver {


private static final String TAG = "MyBroadcastReceiver";
@Override
public void onReceive(Context context, Intent intent) {
StringBuilder sb = new StringBuilder();
sb.append("Action: " + intent.getAction() + "\n");
sb.append("URI: " + intent.toUri(Intent.URI_INTENT_SCHEME).toString() + "\n");
String log = sb.toString();
Log.d(TAG, log);
Toast.makeText(context, log, Toast.LENGTH_LONG).show();
}
}

The system package manager registers the receiver when the app is installed. The receiver then
becomes a separate entry point into your app which means that the system can start the app and
deliver the broadcast if the app is not currently running.

The system creates a new BroadcastReceiver component object to handle each broadcast that it
receives. This object is valid only for the duration of the call to onReceive(Context, Intent). Once
your code returns from this method, the system considers the component no longer active.

2) Context-registered receivers
To register a receiver with a context, perform the following steps:

1. Create an instance of BroadcastReceiver.


KOTLINJAVA
BroadcastReceiver br = new MyBroadcastReceiver();

2. Create an IntentFilter and register the receiver by calling registerReceiver(BroadcastReceiver,


IntentFilter):
KOTLINJAVA
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
this.registerReceiver(br, filter);

Note: To register for local broadcasts, call LocalBroadcastManager.registerReceiver(BroadcastReceiver,


IntentFilter) instead.

Context-registered receivers receive broadcasts as long as their registering context is valid. For
an example, if you register within an Activity context, you receive broadcasts as long as the
activity is not destroyed. If you register with the Application context, you receive broadcasts as
long as the app is running.
3. To stop receiving broadcasts, call unregisterReceiver(android.content.BroadcastReceiver). Be sure to
unregister the receiver when you no longer need it or the context is no longer valid.
Be mindful of where you register and unregister the receiver, for example, if you register a
receiver in onCreate(Bundle) using the activity's context, you should unregister it in onDestroy() to
prevent leaking the receiver out of the activity context. If you register a receiver in onResume(),
you should unregister it in onPause() to prevent registering it multiple times (If you don't want to
receive broadcasts when paused, and this can cut down on unnecessary system overhead). Do not
unregister in onSaveInstanceState(Bundle), because this isn't called if the user moves back in the
history stack.

Sending broadcasts
Android provides three ways for apps to send broadcast:

 The sendOrderedBroadcast(Intent, String) method sends broadcasts to one receiver at a time. As


each receiver executes in turn, it can propagate a result to the next receiver, or it can completely
abort the broadcast so that it won't be passed to other receivers. The order receivers run in can be
controlled with the android:priority attribute of the matching intent-filter; receivers with the same
priority will be run in an arbitrary order.
 The sendBroadcast(Intent) method sends broadcasts to all receivers in an undefined order. This is
called a Normal Broadcast. This is more efficient, but means that receivers cannot read results
from other receivers, propagate data received from the broadcast, or abort the broadcast.
 The LocalBroadcastManager.sendBroadcast method sends broadcasts to receivers that are in the
same app as the sender. If you don't need to send broadcasts across apps, use local broadcasts.
The implementation is much more efficient (no interprocess communication needed) and you
don't need to worry about any security issues related to other apps being able to receive or send
your broadcasts.

The following code snippet demonstrates how to send a broadcast by creating an Intent and
calling sendBroadcast(Intent).

Intent intent = new Intent();


intent.setAction("com.example.broadcast.MY_NOTIFICATION");
intent.putExtra("data","Notice me senpai!");
sendBroadcast(intent);

The broadcast message is wrapped in an Intent object. The intent's action string must provide the
app's Java package name syntax and uniquely identify the broadcast event. You can attach
additional information to the intent with putExtra(String, Bundle). You can also limit a broadcast
to a set of apps in the same organization by calling setPackage(String) on the intent.

Note: Although intents are used for both sending broadcasts and starting activities with
startActivity(Intent), these actions are completely unrelated. Broadcast receivers can't see or capture
intents used to start an activity; likewise, when you broadcast an intent, you can't find or start an activity.

Restricting broadcasts with permissions


Permissions allow you to restrict broadcasts to the set of apps that hold certain permissions. You
can enforce restrictions on either the sender or receiver of a broadcast.

Sending with permissions

When you call sendBroadcast(Intent, String) or sendOrderedBroadcast(Intent, String,


BroadcastReceiver, Handler, int, String, Bundle), you can specify a permission parameter. Only
receivers who have requested that permission with the tag in their manifest (and subsequently
been granted the permission if it is dangerous) can receive the broadcast. For example, the
following code sends a broadcast:

sendBroadcast(new Intent("com.example.NOTIFY"),
Manifest.permission.SEND_SMS);

To receive the broadcast, the receiving app must request the permission as shown below:

<uses-permission android:name="android.permission.SEND_SMS"/>

You can specify either an existing system permission like SEND_SMS or define a custom
permission with the <permission> element. For information on permissions and security in
general, see the System Permissions.

Note: Custom permissions are registered when the app is installed. The app that defines the custom
permission must be installed before the app that uses it.
Receiving with permissions

If you specify a permission parameter when registering a broadcast receiver (either with
registerReceiver(BroadcastReceiver, IntentFilter, String, Handler) or in <receiver> tag in your
manifest), then only broadcasters who have requested the permission with the <uses-permission>
tag in their manifest (and subsequently been granted the permission if it is dangerous) can send
an Intent to the receiver.

For example, assume your receiving app has a manifest-declared receiver as shown below:

<receiver android:name=".MyBroadcastReceiver"
android:permission="android.permission.SEND_SMS">
<intent-filter>
<action android:name="android.intent.action.AIRPLANE_MODE"/>
</intent-filter>
</receiver>

Or your receiving app has a context-registered receiver as shown below:

IntentFilter filter = new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED);


registerReceiver(receiver, filter, Manifest.permission.SEND_SMS, null );

Then, to be able to send broadcasts to those receivers, the sending app must request the
permission as shown below:

<uses-permission android:name="android.permission.SEND_SMS"/>

____________________________________________________________________________
SOME VALUED FEATURES OF AN ANDROID

Custom Home Screens

While it’s possible to hack certain phones to customize the home screen, Android
comes with this capability from the get-go. Download a third-party launcher like
Nova, Apex or Slide and you can add gestures, new shortcuts, or even performance
enhancements for older-model devices.

Infrared Transmission

The Android operating system supports a built-in infrared transmitter, allowing you
to use your phone or tablet as a remote control.

Near Field Communication (NFC)

Most Android devices support NFC, which allows electronic devices to easily
interact across short distances. The main aim here is to create a payment option that
is simpler than carrying credit cards or cash, and while the market hasn’t exploded as
many experts had predicted, there may be an alternative in the works, in the form
of Bluetooth Low Energy (BLE).

No-Touch Control

Using Android apps such as Wave Control, users can control their phones touch-
free, using only gestures. Have messy hands but need to turn off your screen or
change a song? Simple. This could prove especially useful if you’re driving, so you
can keep both eyes on the road.

Storage and Battery Swap

Android phones also have unique hardware capabilities. Google’s OS makes it


possible to remove and upgrade your battery or to replace one that no longer holds a
charge. In addition, Android phones come with SD card slots for expandable
storage.
Contents: Property Animation

“Animation is the process of creating motion and shape changes”

The property animation system is a robust framework that allows you to animate almost
anything. You can define an animation to change any object property over time,
regardless of whether it draws to the screen or not. A property animation changes a
property's (a field in an object) value over a specified length of time. To animate
something, you specify the object property that you want to animate, such as an object's
position on the screen, how long you want to animate it for, and what values you want to
animate between.

Property animation system lets you define the following characteristics of an animation:

1) Duration: You can specify the duration of an animation. The default length is 300
ms.
2) Time interpolation: You can specify how the values for the property are calculated
as a function of the animation's current elapsed time.
3) Repeat count and behavior: You can specify whether or not to have an
animation repeat when it reaches the end of a duration and how many times to
repeat the animation. You can also specify whether you want the animation to play
back in reverse. Setting it to reverse plays the animation forwards then backwards
repeatedly, until the number of repeats is reached.
4) Animator sets: You can group animations into logical sets that play together or
sequentially or after specified delays.
5) Frame refresh delay: You can specify how often to refresh frames of your
animation. The default is set to refresh every 10 ms, but the speed in which your
application can refresh frames is ultimately dependent on how busy the system is
overall and how fast the system can service the underlying timer.

How property animation works


First, let's go over how an animation works with a simple example. Figure 1 depicts a
hypothetical object that is animated with its x property, which represents its horizontal
location on a screen. The duration of the animation is set to 40 ms and the distance to
travel is 40 pixels. Every 10 ms, which is the default frame refresh rate, the object
moves horizontally by 10 pixels. At the end of 40ms, the animation stops, and the object
ends at horizontal position 40. This is an example of an animation with linear
interpolation, meaning the object moves at a constant speed.
Figure 1. Example of a linear animation

You can also specify animations to have a non-linear interpolation. Figure 2 illustrates a
hypothetical object that accelerates at the beginning of the animation, and decelerates
at the end of the animation. The object still moves 40 pixels in 40 ms, but non-linearly.
In the beginning, this animation accelerates up to the halfway point then decelerates
from the halfway point until the end of the animation. As Figure 2 shows, the distance
traveled at the beginning and end of the animation is less than in the middle.

Figure 2. Example of a non-linear animation

Let's take a detailed look at how the important components of the property animation
system would calculate animations like the ones illustrated above. Figure 3 depicts how
the main classes work with one another.

Figure 3. How animations are calculated


The ValueAnimator object keeps track of your animation's timing, such as how long
the animation has been running, and the current value of the property that it is
animating.

Contents: View Animation

You can use the view animation system to perform tweened animation on Views. Tween
animation calculates the animation with information such as the start point, end point,
size, rotation, and other common aspects of an animation.

A tween animation can perform a series of simple transformations (position, size,


rotation, and transparency) on the contents of a View object. So, if you have
a TextView object, you can move, rotate, grow, or shrink the text. If it has a background
image, the background image will be transformed along with the text. The animation
package provides all the classes used in a tween animation.

In order to apply this animation to an object , we will just call the


startAnimation() method of the object. Its syntax is −

ImageView image1 = (ImageView)findViewById(R.id.imageView1);

image.startAnimation(animation);

This animation class has many useful functions which are listed below −

Sr.No Method & Description

start()
1
This method starts the animation.

setDuration(long duration)
2
This method sets the duration of an animation.
getDuration()
3
This method gets the duration which is set by above method

end()
4
This method ends the animation.

cancel()
5
This method cancels the animation.

_________________________________________________________
LAYOUTS

A layout defines the structure for a user interface in your app, such as in an activity.

All elements in the layout are built using a hierarchy of View and ViewGroup objects.

A View usually draws something the user can see and interact with. Whereas a ViewGroup is an

invisible container that defines the layout structure for View and other ViewGroup objects, as

below:

view hierarchy defining a UI layout

The View objects are usually called "widgets" and can be one of many subclasses, such

as Button or TextView.

The ViewGroup objects are usually called "layouts" can be one of many types that provide a

different layout structure, such as LinearLayout or ConstraintLayout .


You can declare a layout in TWO ways:

1. Declare UI elements in XML

 Android provides a straightforward XML vocabulary that corresponds to the View classes and

subclasses, such as those for widgets and layouts.

 You can also use Android Studio's Layout Editor to build your XML layout using a drag-
and-drop interface.
2. Instantiate layout elements at runtime

 Your app can create View and ViewGroup objects (and manipulate their properties)
programmatically.

Declaring your UI in XML allows you to separate the presentation of your app from the code
that controls its behavior.

Using XML files also makes it easy to provide different layouts for different screen sizes and
orientations.

The Android framework gives you the flexibility to use either or both of these methods to build
your app's UI.

For example, you can declare your app's default layouts in XML, and then modify the layout at
runtime.

Tip:To debug your layout at runtime, use the Layout Inspector tool.

Write the XML


Using Android's XML vocabulary, you can quickly design UI layouts and the screen elements
they contain.

Each Layout File must contain exactly one root element, which must be a View or ViewGroup
object.

Once you've defined the root element, you can add additional layout objects or widgets as child
elements to gradually build a View hierarchy that defines your layout.
For example, here's an XML layout that uses a vertical LinearLayoutto hold a TextView and
a Button:

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<TextView android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="IS THIS YOUR ANDROID EXAM..?" />

<Button android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="YES" />

</LinearLayout>

NOTE:

After you've declared your layout in XML, save the file with the .xml extension, in your Android

project's res/layout/ directory, so it will properly compile.

Load the XML Resource


When you compile your app, each XML layout file is compiled into a View resource.

You should load the layout resource from your app code, in your Activity.onCreate() callback
implementation.

Do so by calling setContentView(), passing it the reference to your layout resource in the form
of:R.layout.layout_file_name.
For example, if your XML layout is saved as main_layout.xml, you would load it for your
Activity like so:

JAVA

public void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
}

The onCreate() callback method in your Activity is called by the Android framework when your

Activity is launched (see the discussion about lifecycles, in the Activities document).

Attributes
Every View and ViewGroup object supports their own variety of XML attributes. Some
attributes are specific to a View object (for example, TextView supports the textSize attribute),
but these attributes are also inherited by any View objects that may extend this class. Some are
common to all View objects, because they are inherited from the root View class (like
the id attribute). And, other attributes are considered "layout parameters," which are attributes
that describe certain layout orientations of the View object, as defined by that object's parent
ViewGroup object.

ID
Any View object may have an integer ID associated with it, to uniquely identify the View within
the tree. When the app is compiled, this ID is referenced as an integer, but the ID is typically
assigned in the layout XML file as a string, in the id attribute. This is an XML attribute common
to all View objects (defined by the View class) and you will use it very often. The syntax for an
ID, inside an XML tag is:

android:id="@+id/my_button"
In order to create views and reference them from the app, a common pattern is to:

1. Define a view/widget in the layout file and assign it a unique ID:

<Button android:id="@+id/my_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/my_button_text"/>

2. Then create an instance of the view object and capture it from the layout (typically in
the onCreate()method):

Button myButton = (Button) findViewById(R.id.my_button);

Defining IDs for view objects is important when creating a RelativeLayout. In a relative layout,
sibling views can define their layout relative to another sibling view, which is referenced by the
unique ID.

An ID need not be unique throughout the entire tree, but it should be unique within the part of
the tree you are searching (which may often be the entire tree, so it's best to be completely
unique when possible).

Layout Parameters
XML layout attributes named layout_something define layout parameters for the View that are
appropriate for the ViewGroup in which it resides.

Every ViewGroup class implements a nested class that extends ViewGroup.LayoutParams. This
subclass contains property types that define the size and position for each child view, as
appropriate for the view group. As you can see in figure 2, the parent view group defines layout
parameters for each child view (including the child view group).
Figure 2. Visualization of a view hierarchy with layout parameters associated with each view

Note that every LayoutParams subclass has its own syntax for setting values. Each child element
must define LayoutParams that are appropriate for its parent, though it may also define different
LayoutParams for its own children.

All view groups include a width and height (layout_width and layout_height), and each view is
required to define them. Many LayoutParams also include optional margins and borders.

You can specify width and height with exact measurements, though you probably won't want to
do this often. More often, you will use one of these constants to set the width or height:

 wrap_content tells your view to size itself to the dimensions required by its content.
 match_parent tells your view to become as big as its parent view group will allow.

In general, specifying a layout width and height using absolute units such as pixels is not
recommended. Instead, using relative measurements such as density-independent pixel units
(dp), wrap_content, ormatch_parent, is a better approach, because it helps ensure that your app
will display properly across a variety of device screen sizes. The accepted measurement types are
defined in the Available Resources document.

Layout Position
The geometry of a view is that of a rectangle. A view has a location, expressed as a pair
of left and topcoordinates, and two dimensions, expressed as a width and a height. The unit for
location and dimensions is the pixel.

It is possible to retrieve the location of a view by invoking the methods getLeft() and getTop().
The former returns the left, or X, coordinate of the rectangle representing the view. The latter
returns the top, or Y, coordinate of the rectangle representing the view. These methods both
return the location of the view relative to its parent. For instance, when getLeft() returns 20, that
means the view is located 20 pixels to the right of the left edge of its direct parent.

In addition, several convenience methods are offered to avoid unnecessary computations,


namely getRight()and getBottom(). These methods return the coordinates of the right and bottom
edges of the rectangle representing the view. For instance, calling getRight() is similar to the
following computation: getLeft() + getWidth().

Size, Padding and Margins


The size of a view is expressed with a width and a height. A view actually possesses two pairs of
width and height values.

The first pair is known as measured width and measured height. These dimensions define how
big a view wants to be within its parent. The measured dimensions can be obtained by
calling getMeasuredWidth() and getMeasuredHeight().

The second pair is simply known as width and height, or sometimes drawing width and drawing
height. These dimensions define the actual size of the view on screen, at drawing time and after
layout. These values may, but do not have to, be different from the measured width and height.
The width and height can be obtained by calling getWidth() and getHeight().

To measure its dimensions, a view takes into account its padding. The padding is expressed in
pixels for the left, top, right and bottom parts of the view. Padding can be used to offset the
content of the view by a specific number of pixels. For instance, a left padding of 2 will push the
view's content by 2 pixels to the right of the left edge. Padding can be set using the setPadding(int,
int, int, int) method and queried by
callinggetPaddingLeft(), getPaddingTop(), getPaddingRight() and getPaddingBottom().

Even though a view can define a padding, it does not provide any support for margins. However,
view groups provide such a support. Refer to ViewGroup and ViewGroup.MarginLayoutParams for
further information.

For more information about dimensions, see Dimension Values.


Common Layouts
Each subclass of the ViewGroup class provides a unique way to display the views you nest within
it. Below are some of the more common layout types that are built into the Android platform.

Note: Although you can nest one or more layouts within another layout to achieve your UI design, you should
strive to keep your layout hierarchy as shallow as possible. Your layout draws faster if it has fewer nested
layouts (a wide view hierarchy is better than a deep view hierarchy).

Linear Layout

A layout that organizes its children into a single horizontal or vertical row. It creates a scrollbar
if the length of the window exceeds the length of the screen.

Relative Layout

Enables you to specify the location of child objects relative to each other (child A to the left of
child B) or to the parent (aligned to the top of the parent).
Web View

Displays web pages.

Building Layouts with an Adapter


When the content for your layout is dynamic or not pre-determined, you can use a layout that
subclasses AdapterView to populate the layout with views at runtime. A subclass of
the AdapterView class uses an Adapter to bind data to its layout. The Adapter behaves as a
middleman between the data source and the AdapterView layout—the Adapter retrieves the data
(from a source such as an array or a database query) and converts each entry into a view that can
be added into the AdapterView layout.

Common layouts backed by an adapter include:

List View

Displays a scrolling single column list.


Grid View

Displays a scrolling grid of columns and rows.

Filling an adapter view with data


You can populate an AdapterView such as ListView or GridView by binding
the AdapterView instance to an Adapter, which retrieves data from an external source and creates
a View that represents each data entry.

Android provides several subclasses of Adapter that are useful for retrieving different kinds of
data and building views for an AdapterView. The two most common adapters are:

ArrayAdapter

Use this adapter when your data source is an array. By default, ArrayAdapter creates a view for
each array item by calling toString() on each item and placing the contents in a TextView.

For example, if you have an array of strings you want to display in a ListView, initialize a
new ArrayAdapter using a constructor to specify the layout for each string and the string
array:

KOTLINJAVA

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,


android.R.layout.simple_list_item_1, myStringArray);

The arguments for this constructor are:

 Your app Context


 The layout that contains a TextView for each string in the array
 The string array

Then simply call setAdapter() on your ListView:


ListView listView = (ListView) findViewById(R.id.listview);
listView.setAdapter(adapter);

To customize the appearance of each item you can override the toString() method for the
objects in your array. Or, to create a view for each item that's something other than
a TextView (for example, if you want an ImageView for each array item), extend
the ArrayAdapter class and override getView() to return the type of view you want for each
item.

SimpleCursorAdapter

Use this adapter when your data comes from a Cursor. When using SimpleCursorAdapter, you
must specify a layout to use for each row in the Cursor and which columns in the Cursor should
be inserted into which views of the layout. For example, if you want to create a list of people's
names and phone numbers, you can perform a query that returns a Cursor containing a row for
each person and columns for the names and numbers. You then create a string array specifying
which columns from the Cursoryou want in the layout for each result and an integer array
specifying the corresponding views that each column should be placed:

String[] fromColumns = {ContactsContract.Data.DISPLAY_NAME,


ContactsContract.CommonDataKinds.Phone.NUMBER};
int[] toViews = {R.id.display_name, R.id.phone_number};

When you instantiate the SimpleCursorAdapter, pass the layout to use for each result,
the Cursorcontaining the results, and these two arrays:

SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,


R.layout.person_name_and_number, cursor, fromColumns, toViews, 0);
ListView listView = getListView();
listView.setAdapter(adapter);

The SimpleCursorAdapter then creates a view for each row in the Cursor using the provided
layout by inserting each fromColumns item into the corresponding toViews view.
.

If, during the course of your app's life, you change the underlying data that is read by your
adapter, you should call notifyDataSetChanged(). This will notify the attached view that the data
has been changed and it should refresh itself.
Handling click events
You can respond to click events on each item in an AdapterView by implementing
the AdapterView.OnItemClickListener interface. For example:

// Create a message handling object as an anonymous class.


private OnItemClickListener messageClickedHandler = new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id) {
// Do something in response to the click
}
};

listView.setOnItemClickListener(messageClickedHandler);

____________________________________________________________

NOTE: MORE ABOUT MENIFEST RESOURCE……

In an android system, every APP project must have an AndroidManifest.xml file

The manifest file describes essential information about your app to the Android
build tools, the Android operating system, and Google Play.

Before the Android system can start an app component, the system must know
that the component exists by reading the app's manifest file.

The manifest does a number of things in addition to declaring the app's


components, such as the following:

i. The primary task of the manifest is to inform the system about the app's
components.

Example (Declaring Activity Component)

<manifest ... >

<application android:icon="@drawable/app_icon.png" ... >

<activity android:name="com.example.project.ExampleActivity"

android:label="@string/example_label" ... >

</activity>
</application>

</manifest>

ii. Identifies any user permissions the app requires, such as Internet access or read-
access to the user's contacts.

Example (user permission)

<manifest ... >

<uses-permission android:name="android.permission.SEND_SMS"/>

</manifest>

iii. Declares minimum API Level required by the app.

Example (API Level)

<manifest>
<uses-sdk android:minSdkVersion="5" />
</manifest>

iv. The manifest file is also where you can declare what types of hardware or software
features your app requires, and thus, which types of devices your app is compatible with.
Google Play Store does not allow your app to be installed on devices that don't provide
the features or system version that your app requires.
There are several manifest tags that define which devices your app is compatible
with. Most common are here.

<manifest ... >

<uses-feature android:name="android.hardware.sensor.compass"

android:required="true" />

<uses-sdk android:minSdkVersion="integer"

android:targetSdkVersion="integer"

android:maxSdkVersion="integer" />

</manifest>

Declares API libraries the app needs to be linked against (other than the Android framework APIs), such
as the Google Maps library.

____________________________________________________________
Intent & Intent Filter

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
theService 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 application will satisfy the intent, by supplying either the target app's
package name or a fully-qualified component class name. 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.

Figure 1 shows how an intent is used when starting an activity. When the Intent object names a
specific activity component explicitly, the system immediately starts that component.

Figure 1. How an implicit intent is delivered through the system to start another activity: [1] Activity A creates
anIntent with an action description and passes it to startActivity(). [2] The Android System searches all apps for
an intent filter that matches the intent. When a match is found, [3] the system starts the matching activity
(Activity B) by invoking its onCreate() method and passing it the Intent.

When you use an implicit intent, the Android system finds the appropriate component to start by
comparing the contents of the intent to the intent filters declared in the manifest file of other apps
on the device. If the intent matches an intent filter, the system starts that component and delivers
it the Intent object. If multiple intent filters are compatible, the system displays a dialog so the
user can pick which app to use.

An intent filter is an expression in an app's manifest file that specifies the type of intents that the
component would like to receive. For instance, by declaring an intent filter for an activity, you
make it possible for other apps to directly start your activity with a certain kind of intent.
Likewise, if you do notdeclare any intent filters for an activity, then it can be started only with an
explicit intent.
An Intent object carries information that the Android system uses to determine which component
to start plus information that the recipient component uses in order to properly perform the action.

The primary information contained in an Intent is given as below:

1) Component Name
 The name of the component to start.
2) Action
 A string that specifies the generic action to perform (such as view or pick).
 In the case of a broadcast intent, this is the action that took place and is being
reported

Here are some common actions for starting an activity:

ACTION_VIEW

Use this action in an intent with startActivity() when you have some
information that an activity can show to the user, such as a photo to view in
a gallery app, or an address to view in a map app.

ACTION_SEND

Also known as the share intent, you should use this in an intent with
startActivity() when you have some data that the user can share through
another app, such as an email app or social sharing app.

3) Data

The URI (a Uri object) that references the data to be acted on and/or the
MIME type of that data. The type of data supplied is generally dictated by
the intent's action. For example, if the action is ACTION_EDIT, the data
should contain the URI of the document to edit

4) Category
A string containing additional information about the kind of component that
should handle the intent.

Here are some common categories:

CATEGORY_BROWSABLE

The target activity allows itself to be started by a web browser to display


data referenced by a link, such as an image or an e-mail message.

CATEGORY_LAUNCHER

The activity is the initial activity of a task and is listed in the system's
application launcher.

5) Extras

Key-value pairs that carry additional information required to accomplish the


requested action. Just as some actions use particular kinds of data URIs,
some actions also use particular extras.

You can add extra data with various putExtra() methods, each accepting
two parameters:

(i) key name

(ii) value

For example, when creating an intent to send an email with


ACTION_SEND, you can specify the to recipient with the
EXTRA_EMAIL key, and specify the subject with the EXTRA_SUBJECT
key.

6) Flags

Flags are defined in the Intent class that function as metadata for the intent. The flags may
instruct the Android system how to launch an activity (for example, which task the activity
should belong to) and how to treat it after it's launched (for example, whether it belongs in the
list of recent activities).

Android APP Publication

Publishing is the general process that makes your Android applications available to users. When
you publish an Android application you perform two main tasks:

1) Prepare the application for release.

During the preparation step you build a release version of your application, which
users can download and install on their Android-powered devices.

2) Release the application to users.

During the release step you publicize, sell, and distribute the release version of
your application to users

Steps to Publish Your Android App on Google Play Store

1) Create an account
Firstly, To publish your app on google play store, you need to have account on

google. You may have already personal email account with them but for your app

it's better to separate one for manage your app(s) easily. You would have to pay a

registration fees of 25 USD, using Google payments, While registering your

publisher account. After that, a verification mail would be sent to you and then you

sign in to your developer console, where all action would take place.

2. Familiarize yourself with Developer Console

Developer console is starting point and main dashboard for publishing tools and

operations. Before you go ahead, familiarize yourself with list of merchant

countries and developer countries. You need to review list of merchant countries if
you want to sell apps or in app purchases or have subscriptions and list of developer

countries will tell you about locations where distribution to Google play users is

supported. Apart from this, also looks the Google Play’s Terms and conditions.

3. Fill in the necessary account details

After this, you have to provide your complete account details like you have to

provide your developer name, the name which would be displayed in Google Play

Store. You will have to wait for anything between just a little and 48 hours, after

filling the details for Google play developer registration to be processed.

4. Link your merchant account

If you have a paid app or subscription or in app purchases, then you have to inter

link you google payments merchant account and developer profile. It can be used

for tax and financial identification as well as monthly payout from sale.

5. Upload your app

When you are sign in your Google Play developer console, click on “Add new

application” from “All Applications tab”. After this select correct “Default

Language” from drop down menu and then type “title” of your app which would

be appear on Google Play store. Then, select “Upload APK” button to view on new

page which would be your homepage for app. Time taken to upload file depend on

your app size. App will be in drafts until or unless you publish it.
6. Alpha and beta testing of app

It is essential to test it with sample of end users to get feedback of app before launch

your app even Google play take care of this as well. In section of your app “APK”

of developer console, you will find option related to “Alpha Testing” and “Beta

Testing”. After you uploaded your app’s “APK” file you can use these options for

receive URL that can be shared with testers. By using this link, Testers can

download app beta or alpha version. Your testers can not provide reviews and

feedback on app page. Now you use this feedback to make relevant changes and

optimize your app before publishing in app store.

7. Provide details for store listing

After uploading “APK” file go to “Store listing” tab. Over there you need to add

details of app like “Full description” and “Short description”. Along with this add

categorization, contact details, link of promo video if you have, add screenshots

and other necessary details to app. After complete mandatory fields click on “Save”

button. You can update your store listing anytime.

8. Add pricing and distribution details

Now move on next tab, which is “Pricing and Distribution” and select it is “Paid”

or “Free” app. You also select distribution countries and check boxes stating your

app complies with content guidelines. If your app is an game one, then you can put

in limelight using “Google Play for Game” option. Now save changes and move on

next step.
9. Publishing the application

When all three tabs “Pricing and Distribution”, “Store Listing” and “APK” have

been filled then appear a green check mark next to them you are all ready to publish

app in Google Play. After then click on “Publish this app” button under “Ready to

Publish” drop down menu at top right corner of Developer console. A confirmation

bar would show up stating your app would appear shortly in Google Play Store.

10. Device Filtering option

There are series of extra option that might not seem to be important to publish the

app but they can prevent app from negative feedback. There is also option to

manually filter non compatible devices or problematic so make the most use of it

to filter out any negativities and stay on the top.

You might also like