You are on page 1of 19

Android

Android is an operating system that is built basically for Mobile phones. It is based on the Linux
Kernel and other open-source software and is developed by Google. It is used for touchscreen
mobile devices such as smartphones and tablets. But nowadays these are used in Android Auto cars,
TV, watches, camera, etc. It has been one of the best-selling OS for smartphones. Android OS was
developed by Android Inc. which Google bought in 2005. Various applications (apps) like games,
music player, camera, etc. are built for these smartphones for running on Android. Google Play store
features more than 3.3 million apps. The app is developed on an application known as Android
Studio. These executable apps are installed through a bundle or package called APK(Android
Package Kit).

Android History

 2003: The platform was originally founded by a start-up “Android Inc.” which aimed to build a
mobile OS operating system (similar to what Nokia’s Symbian was doing at the time)
 2005: Android was acquired by Google, who was looking to get into mobile

 2007: Google announces the Open Handset Alliance, a group of tech companies working together
to develop “open standards” for mobile platforms.
 2008: First Android device is released: the HTC Dream (a.k.a. T-Mobile G1)

 2010: First Nexus device is released: the Nexus One. These are Google-developed “flagship”
devices, intended to show off the capabilities of the platform.
 2014: Android Wear, a version of Android for wearable devices (watches) is announced.

 2016: Daydream, a virtual reality (VR) platform for Android is announced.

Android Versions

Android has gone through a large number of “versions” since it’s release:
Date Version Nickname API Level

Sep 2008 1.0 Android 1

Apr 2009 1.5 Cupcake 3

Sep 2009 1.6 Donut 4

Oct 2009 2.0 Éclair 5

May 2010 2.2 Froyo 8

Dec 2010 2.3 Gingerbread 9

Feb 2011 3.0 Honeycomb 11

Oct 2011 4.0 Ice Cream Sandwich 14

July 2012 4.1 Jelly Bean 16

Oct 2013 4.4 KitKat 19

Nov 2014 5.0 Lollipop 21

Oct 2015 6.0 Marshmallow 23

Aug 2016 7.0 Nougat 24

Aug 2017 8.0 Oreo 26

Aug 2018 9.0 Pie 28


Building Apps

 While Android applications can be developed using any programming environment, the
official and best IDE for Android programming is Android Studio.

 This is a fork of JetBrain’s IntelliJ IDEA application—a Java IDE customized for Android
development. Need to download and install this IDE.

 Be sure to download the Android Studio bundle that includes the Android SDK (Standard
Development Kit): the tools and libraries needed for Android development. In particular, the
SDK comes with a number of useful command line tools.
 Useful Command Line Tools include: adb, emulator

 adb, the “Android Device Bridge”, which is a connection between your computer and the
device (physical or virtual). This tool is used for console output!

 emulator, which runs the Android emulator: a virtual machine of an Android device.

Creating a Project

To begin the first application, launch Android Studio (it may take a few minutes to open). From the
Welcome screen, choose to “Start a new Android Studio Project”. This will open up a wizard to
walk the through setting up the project.

 The “Company domain” should be a unique domain for us. For this course, we include UW
NetID, e.g., joelross.uw.edu.
 Make a mental note of the project location so that we can find the work later (e.g., if it’s
in Desktop or Documents).
 If we choose to “Include Kotlin Support”, the application will be created with Kotlin rather than
Java. Since we haven’t learned Kotlin yet, we’ll start with a Java example so the little code we look
at is more familiar.

 On the next screen, you will need to pick the Minimum SDK level that to support—that is, what is
the oldest version of Android your application will be able to run on? For this course, unless
otherwise specified, we should target API 19 KitKat (4.4) as a minimum, allowing your application
to run on pretty much any Android device.

Note that the Minimum SDK is different than the Target SDK, which is the version of Android your
application has been tested and designed against. The Target SDK indicates what set of API
features you have considered/coded against, even if your app can fall back to older devices that
don’t include those features. In many ways, the Target SDK is the “highest SDK I’ve worked with”.
For most of this course we will target API 24 (Nougat).

 On the next screen, select to start with an Empty Activity. Activities are the basic component of
Android, each of which acts as a “screen” or “page” in your app.

 Stick with the default name (MainActivity) on the next screen, and hit “Finish”. Android Studio will
take a few minutes to create your project and get everything set up. (Keep an eye on the bottom
status bar to wait for everything to be finished). Once it is done, you have a complete (if simple)
app!
Dalvik

On a desktop, Java code needs to be compiled into bytecode and runs on a virtual machine
(the Java Virtual Machine (JVM)). Pre-Lollipop (5.0), Android code run on a virtual machine
called Dalvik.

 Fun fact for people with a Computer Science background: Dalvik uses a register-based
architecture rather than a stack-based one!

A developer would write Java code, which would then be compiled into JVM bytecode, which
would then be translated into DVM (Dalvik Virtual Machine) bytecode, that could be run on Android
devices. This DVM bytecode is stored in .dex or .odex (“[Optimized] Dalvik Executable”) files,
which is what was loaded onto the device. The process of converting from Java code to dex files is
called “dexing” (so code that has been compiled and converted is called “dexed”).
Dalvik does include JIT (“Just In Time”) compilation to native code that runs much faster than the
code interpreted by the virtual machine, similar to the Java HotSpot. This native code is faster
because no translation step is needed to talk to the actual hardware (via the OS).

However, from Lollipop (5.0) on, Android instead uses Android Runtime (ART) to run code. ART’s
biggest benefit is that it compiles the .dex bytecode into native code at installation using AOT
(“Ahead of Time”) compilation. ART continues to accept .dex bytecode for backwards compatibility
(so the same dexing process occurs), but the code that is actually installed and run on a device is
native. This allows for applications to have faster execution, but at the cost of longer install times—
and since you only install an application once, this is a pretty good trade.
(Kotlin also is compiled into .dex bytecode, so it ends up in the same place as Java).

.APK FILE

After being built, an Android application (the source, dexed bytecode, and any non-code resources
such as images) are packaged into an .apk file. This are basically zip files (it uses the same gzip
compression); if you rename the file to be .zip and you can uncompress it! The .apk file is
then cryptographically signed to specify its authenticity, and either “side-loaded” onto the device or
uploaded to an App Store for deployment.
 In short: the signed .apk file is basically the “executable” version of your program!
 Google is in the process of deprecating .apk files and replacing them with Android App Bundles.
These contain all of the compiled source code, but offloads APK generation and app signing to the
Play Store.
 Note that the Android application framework code (e.g., the base Activity class) is actually “pre-
DEXed” (pre-compiled) on the device; when you write code, you’re compiling against empty code
stubs (rather than needing to include those classes in your .apk)! That said, any other 3rd-party
libraries you include will be copied into your built app, which can increase its file size both for
installation and on the device.
 Usefully, since Android code is written for a virtual machine anyway, Android apps can be
developed and built on any computer’s operating system (unlike some other mobile OS…).
Android Fundamentals

1. Android Programming Languages

In Android, basically, programming is done in two languages JAVA or C++ and XML (Extension
Markup Language). Nowadays KOTLIN is also preferred. The XML file deals with the design,
presentation, layouts, blueprint, etc (as a front-end) while the JAVA or KOTLIN deals with the working
of buttons, variables, storing, etc (as a back-end).

2. Android Components

The App components are the building blocks of Android. Each component has its own role and life
cycles i.e from launching of an app till the end. Some of these components depend upon others also.
Each component has a definite purpose. The four major app components are:

 Activities
 Services
 Broadcast Receivers:
 Content Provider:

Activities: It deals with the UI and the user interactions to the screen. In other words, it is a User
Interface that contains activities. These can be one or more depending upon the App. It starts when
the application is launched. At least one activity is always present which is known as MainActivity.
The activity is implemented through the following.

Syntax:

public class MainActivity extends Activity{


// processes
}

Services: Services are the background actions performed by the app, these might be long-running
operations like a user playing music while surfing the Internet. A service might need other sub-
services so as to perform specific tasks. The main purpose of the Services is to provide non-stop
working of the app without breaking any interaction with the user.

Syntax:

public class MyServices extends Services{


// code for the services
}

Broadcast Receivers: A Broadcast is used to respond to messages from other applications or from
the System. For example, when the battery of the phone is low, then the Android OS fires a
Broadcasting message to launch the Battery Saver function or app, after receiving the message the
appropriate action is taken by the app. Broadcast Receiver is the subclass of BroadcastReceiver
class and each object is represented by Intent objects.

Syntax:

public class MyReceiver extends BroadcastReceiver{


public void onReceive(context,intent){
}

Content Provider: Content Provider is used to transferring the data from one application to the
others at the request of the other application. These are handled by the class ContentResolver class.
This class implements a set of APIs(Application Programming Interface) that enables the other
applications to perform the transactions. Any Content Provider must implement the Parent Class of
ContentProvider class.

Syntax:

public class MyContentProvider extends ContentProvider{


public void onCreate()
{}
}

3. Structural Layout Of Android Studio

The basic structural layout of Android Studio is given below:


The above figure represents the various structure of an app.

Manifest Folder: Android Manifest is an XML file that is the root of the project source set. It
describes the essential information about the app and the Android build tools, the Android Operating
System, and Google Play. It contains the permission that an app might need in order to perform a
specific task. It also contains the Hardware and the Software features of the app, which determines
the compatibility of an app on the Play Store. It also includes special activities like services, broadcast
receiver, content providers, package name, etc.

Java Folder: The JAVA folder consists of the java files that are required to perform the background
task of the app. It consists of the functionality of the buttons, calculation, storing, variables,
toast(small popup message), programming function, etc. The number of these files depends upon the
type of activities created.

Resource Folder: The res or Resource folder consists of the various resources that are used in the
app. This consists of sub-folders like drawable, layout, mipmap, raw, and values. The drawable
consists of the images. The layout consists of the XML files that define the user interface layout.
These are stored in res.layout and are accessed as R.layout class. The raw consists of the
Resources files like audio files or music files, etc. These are accessed through R.raw.filename.
values are used to store the hardcoded strings(considered safe to store string values) values,
integers, and colors. It consists of various other directories like:

 R.array :arrays.xml for resource arrays


 R.integer : integers.xml for resource integers
 R.bool : bools.xml for resource boolean
 R.color :colors.xml for color values
 R.string : strings.xml for string values
 R.dimen : dimens.xml for dimension values
 R.style : styles.xml for styles

Gradle Files: Gradle is an advanced toolkit, which is used to manage the build process, that allows
defining the flexible custom build configurations. Each build configuration can define its own set of
code and resources while reusing the parts common to all versions of your app. The Android plugin
for Gradle works with the build toolkit to provide processes and configurable settings that are specific
to building and testing Android applications. Gradle and the Android plugin run independently of
Android Studio. This means that you can build your Android apps from within Android Studio. The
flexibility of the Android build system enables you to perform custom build configurations without
modifying your app’s core source files.

Basic Layout Can be defined in a tree structure as:

Project/
app/
manifest/
AndroidManifest.xml
java/
MyActivity.java
res/
drawable/
icon.png
background.png
drawable-hdpi/
icon.png
background.png
layout/
activity_main.xml
info.xml
values/
strings.xml

4. Lifecycle of Activity in Android App

The Lifecycle of Activity in Android App can be shown through this diagram:
States of Android Lifecycle:

1. OnCreate: This is called when activity is first created.


2. OnStart: This is called when the activity becomes visible to the user.
3. OnResume: This is called when the activity starts to interact with the user.
4. OnPause: This is called when activity is not visible to the user.
5. OnStop: This is called when activity is no longer visible.
6. OnRestart: This is called when activity is stopped, and restarted again.
7. OnDestroy: This is called when activity is to be closed or destroyed.

Top Android UI Controls that you must know about!

Android UI Controls are those components of Android that are used to design the UI in a more
interactive way. It helps us to develop an application that makes user interaction better with the view
components. Android provides us a huge range of UI controls of many types such as buttons, text
views, etc.

As we know UI is the only thing that a user interacts with within an Application. This is the reason that
we make our Application look aesthetic and, more and more connective. To do so, we need to add
the UI controls or we say Input controls in the respective application.

Check the Android Application Components you didn’t know about.

Moving forth we will see some important Android UI controls for our applications:

 TextView
 EditText
 Button
 ImageButton
 ToggleButton
 RadioButton
 RadioGroup
 CheckBox
 AutoCompleteTextView
 ProgressBar
 Spinner
 TimePicker
 DatePicker
 SeekBar
 AlertDialog
 Switch
 RatingBar
VIEW
A View is an object that draws something on the screen that the user can interact with and
a ViewGroup is an object that holds other View (and ViewGroup) objects in order to define the
layout of the user interface.
You define your layout in an XML file which offers a human-readable structure for the layout, similar
to HTML. For example, a simple vertical layout with a text view and a button looks like this −

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:orientation="vertical" >

<TextView android:id="@+id/text"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="I am a TextView" />

<Button android:id="@+id/button"

android:layout_width="wrap_content"

NOTIFICATION

A notification is a message you can display to the user outside of your application's normal UI.
When you tell the system to issue a notification, it first appears as an icon in the notification area. To
see the details of the notification, the user opens the notification drawer. Both the notification area
and the notification drawer are system-controlled areas that the user can view at any time.

Android Toast class provides a handy way to show users alerts but problem is that these alerts are
not persistent which means alert flashes on the screen for a few seconds and then disappears.

To see the details of the notification, you will have to select the icon which will display notification
drawer having detail about the notification. While working with emulator with virtual device, you will
have to click and drag down the status bar to expand it which will give you detail as follows. This will
be just 64 dp tall and called normal view.

Above expanded form can have a Big View which will have additional detail about the notification.
You can add upto six additional lines in the notification. The following screen shot shows such
notification.

Create and Send Notifications

You have simple way to create a notification. Follow the following steps in your application to create a
notification −

Step 1 - Create Notification Builder


As a first step is to create a notification builder using NotificationCompat.Builder.build(). You will use
Notification Builder to set various Notification properties like its small and large icons, title, priority etc.

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)

Step 2 - Setting Notification Properties

Once you have Builder object, you can set its Notification properties using Builder object as per your
requirement. But this is mandatory to set at least following −

 A small icon, set by setSmallIcon()


 A title, set by setContentTitle()
 Detail text, set by setContentText()

Step 3 - Attach Actions

This is an optional part and required if you want to attach an action with the notification. An action
allows users to go directly from the notification to an Activity in your application, where they can look
at one or more events or do further work.

The action is defined by a PendingIntent containing an Intent that starts an Activity in your
application. To associate the PendingIntent with a gesture, call the appropriate method of
NotificationCompat.Builder. For example, if you want to start Activity when the user clicks the
notification text in the notification drawer, you add the PendingIntent by calling setContentIntent().

Step 4 - Issue the notification

Finally, you pass the Notification object to the system by calling NotificationManager.notify() to send
your notification. Make sure you call NotificationCompat.Builder.build() method on builder object
before notifying it. This method combines all of the options that have been set and return a new
Notification object.
Components for communication -Intents & Intent Filters

What is Intent

Android provides an Intent mechanism to assist the interaction and communication between
applications. Intent can promote communication between components in a variety of ways, and its
basic use cases mainly include the following three: Start Activity . Use Context.startActivity() or
Activity.startActivityForResult() to pass in an intent to start an activity. Use Activity.setResult() to pass
in an intent to return the result from the activity.

Start the service . Pass the intent object to Context.startService() to start a service or send a
message to a running service. Pass the intent object to Context.bindService() to bind a service.

Pass the broadcast . Pass the intent object to Context.sendBroadcast(),


Context.sendOrderedBroadcast(), or Context.sendStickyBroadcast() and other broadcast methods,
then they are passed to the broadcast receiver.

Intent category

Explicit Intent : You need to specify the component to be started by name (fully qualified class
name). Usually use explicit Intent to start the component in your own application, because you know
the class name of the Activity or service to start.

Implicit Intent : Does not specify a specific component, but declares the general operation to be
performed, thereby allowing components in other applications to handle it.

When an explicit Intent is created to start an Activity or service, the system will immediately start the
application component specified in the Intent object. When creating an implicit Intent, the Android
system compares the content of the Intent with the Intent filters declared in the manifest files of other
applications on the device to find the corresponding components to be launched. If multiple Intent
filters are compatible, the system will display a dialog box to allow the user to select the application to
use.

Intent properties

Component (component) The Component attribute clearly specifies the class name of the target
component of the Intent. This attribute is optional and only used to display the Intent. If not specified,
the Intent is implicit.
You can set the component name using setComponent(), setClass(), setClassName(), or the Intent
constructor.
For example, start an Activity:

Intent intent = new Intent();


//Create components and respond through components
ComponentName component = new ComponentName(MainActivity.this, AnotherActivity.class);
intent.setComponent(component);
startActivity(intent);

//Or can be abbreviated as


Intent intent = new Intent();
intent.setClass(MainActivity.this, SecondActivity.class);
startActivity(intent);

Intent intent = new Intent(MainActivity.this,SecondActivity.class);


startActivity(intent);

Action (action) isused to specify a string of general operations to be performed. For example, if you
want to eat or sleep, these are actions. Action can be customized, or you can use operation constants
defined by the Intent class (such as ACTION_VIEW, ACTION_PICK, etc.) or other framework
classes. The more motions applied, the more precise.

category Thecategory is a string that contains additional information about the intent that the
component of that type needs to handle. The addCategory() method adds categories to the intent
object, the removeCategory() method deletes the previously added categories, and getCategories()
gets all the categories set to the intent object.
Category and action are declared as child elements, for example:

Manifest code:

<activity
android:name=".AnotherActivity">
<intent-filter>
<action android:name="com.example.testIntent.ACTION_TEST"/>
<category android:name="android.intent.category.CATEGORY_TEST"/>
</intent-filter>
</activity>

MainActivity code:

Intent intent = new Intent();


intent.setAction("com.example.testIntent.ACTION_TEST");
intent.addCategory("com.example.testIntent.CATEGORY_TEST");
startActivity(intent);

Only when action and Category match at the same time can the Intent be responded to. If the
category is not specified in the intent Filter, the default must be used. When the category is not added
in the intent setting, the default category is automatically added. Only one action can be specified in
each Intent, but multiple categories can be specified. An Intent Filter can contain multiple actions and
categories.

data (data) and type (data type)data is the data to be accessed, represented by URI. Usually, a
combination of action+data attributes is used to describe an intention: what to do. The reputation in
the intent filter can be just a data type (type), a URI, or both data type and URI.
The setData() method can only specify data by URI, setType() can only specify data by meta type,
and setDataAndType() can specify both URI and meta type. The URI is read by getData(), and the
type is read by getType(). If the Intent object contains both Uri and Type, then it must also contain
both in order to pass.

The relationship between the Data attribute and the Type attribute is subtle. These two attributes will
override each other. For example, if you set the Data attribute for the Intent first, and then set the
Type attribute, the Type attribute will override the Data attribute.
If you set the Type property for the Intent first, and then set the Data property, the Data property will
override the Type property.
If you want the Intent to have both the Data property and the Type property, you should call the
setDataAndType() method of the Intent.

Note: Uri string is always full format: scheme://host:port/path, such as


content://com.android.contacts/contacts/1tel:4536, where content is the scheme part and
com.android.contacts is the host part , The port part is omitted, and/contacts/1 is the path part.

The Data attribute does not require that the elements android:scheme, android:host, android:port,
and android:path in the <intent-filter.../> of the activated component are fully satisfied. For example: if
the <data.../> child element of the target component only specifies the android:scheme attribute, then
as long as the scheme part of the Intent's Data attribute is the same as the android:scheme attribute
value, the component can be started.

There are two points to note here:

If the <data.../> child element has only the android:port attribute and no android:host attribute is
specified, then the android.port attribute will not work. If the <data.../> child element has only the
android:path attribute and no android:host attribute is specified, then the android:path attribute will not
work.

Several common Data attributes:

tel://: Number data format, followed by phone number. mailto://: Email data format, followed by the
email recipient address.
smsto://: SMS data format, followed by the SMS receiving number.
content://: content data format, followed by the content to be read.
file://: File data format, followed by file path.

extra (extended information)This is the additional information described in key-value pairs that is
passed to the component that needs to process the intent. Set by the putExtras() method, each
method accepts two parameters: key name and value. You can also create a Bundle object
containing all extra data, and then read it with the getExtras() method.

Intent intent = new Intent(Intent.ACTION_SEND);


Bundle extra = new Bundle();
extra.putString(Intent.EXTRA_EMAIL,"lalala@domain.com");
extra.putString(Intent.EXTRA_SUBJECT,"Subject");
extra.putString(Intent.EXTRA_TEXT,"Hello");
intent.putExtras(extra);
startActivity(intent);

The flag (flag)describes how the Android system starts the activity, and how to deal with it after the
start. After a program is started, the system will assign a task to the program for its use, and the same
task can have activities of different applications.
So, can the same program have multiple tasks? This involves loading the start mode of the activity.
Note: A group of logically together activity in android is called task, which can be understood as an
activity stack.

Intent intent = new Intent(MainActivity.this,SecondActivity.class);


intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//Equivalent to singleTask
//intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);//Equivalent to singleTop
startActivity(intent);
4.start modes of activity

1. Standard mode Standard mode is the default startup mode of Android. In this mode, Activity can
have multiple instances. Every time you start Activity, regardless of whether there is already an
instance of this Activity in the task stack, the system will create a new Activity instance. . In most
cases, this mode should be used, and when there are special needs, other modes should be
considered.

2. SingleTop mode SingleTop mode is very similar to standard mode. The main difference is that
when a singleTop mode Activity is already at the top of the task stack, when you start it again, no new
instances will be created. If it is not at the top of the stack, it will A new instance will be created.

3. SingleTask mode The Activity of SingleTask mode has only one instance in the same Task. If the
Activity is already at the top of the stack, the system will not create a new Activity instance, just like
the singleTop mode. But when the Activity already exists but is not on the top of the stack, the system
will move the Activity to the top of the stack and pop the activity above it.

4. SingleInstance mode singleInstance mode is also singleton, but different from singleTask,
singleTask is only a singleton in the task stack, there can be multiple instances of singleTask Activity
in the system, and singleInstance Activity has only one instance in the entire system, start a
singleInstanceActivity When, the system will create a new task stack, and this task stack has only one
Activity.

Start android common built-in components

dial number

Uri uri = Uri.parse("tel:10086");


Intent intent = new Intent(Intent.ACTION_DIAL, uri);
startActivity(intent);

Open the browser to visit the website

Uri uri = Uri.parse("http://www.baidu.com");


Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);

send messages

Uri uri = Uri.parse("smsto:10000");


Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
intent.putExtra("sms_body", "Hello");
startActivity(intent);

Play multimedia

Intent intent = new Intent(Intent.ACTION_VIEW);


Uri uri = Uri.parse("file:///sdcard/11.mp3");
intent.setDataAndType(uri, "audio/mp3");
startActivity(intent);
Take and store pictures

Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);


long time = Calendar.getInstance().getTimeInMillis();
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment
.getExternalStorageDirectory().getAbsolutePath()+"/tucue", time + ".jpg")));
startActivityForResult(intent, ACTIVITY_GET_CAMERA_IMAGE);

send email

Intent intent = new Intent(Intent.ACTION_SEND);


intent.putExtra(Intent.EXTRA_EMAIL, "l1245265290@163.com");
intent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
intent.putExtra(Intent.EXTRA_TEXT, "Hello");
intent.setType("text/plain");
startActivity(intent);
Intent Filter

IntentFilter translated into Chinese is "intent filter", mainly used to filter implicit intent. When the user
performs an operation, the Android system will look for components and services that can respond to
the operation according to the configured "intent filter". The claim is in the manifest file. Purpose
Intent Filter is used by each component to describe its function. Through the Intent Filter information
of the component, Android component management applications can understand and master the
capabilities of each component and the requests that can be processed and match the qualified Intent
objects.
Each component can have any number of Intent Filters. The more Intent Filter objects a component
contains, the wider the range of Intent requests it can accept, and the more complicated its
implementation will be.

Intent Filter matching rulesIntentFilter filtering information includes action, category, and data. A
component can contain multiple intent-filters. As long as an intent can completely match a set of
intent-filters, the corresponding component can be successfully started.

1. Action matching If there


is an action in the IntentFilter, there must be an action in the Intent. The action in the Intent must exist
in the corresponding IntentFilter
. Only one action and the same in the IntentFilter are
required. 2. The matching of category is
different from action and data. The categories in the Intent must all appear in the Intent Filter to be
considered a successful match. Intent can not specify the category, if the category is not specified in
the Intent, the system will automatically bring it "android.intent.category.DEFAULT". Therefore,
components that want to receive implicit Intent must add the default category to the Intent Filter
declaration in the manifest file.
3. The matching
of data is similar to action, as long as the data of the Intent is as long as any data in the Intent Filter.
Same can match successfully. If the data declaration part of the Intent Filter does not specify a uri,
the default uri is content or file, and the scheme part of the uri in the Intent must be content or file to
match;

IntentFilter matching algorithm Theinput of the algorithm is the Intent object and the Intent Filter
object to be compared, and the output is a 32-bit integer value that is used to characterize the degree
of matching between the two. The entire matching algorithm process can be divided into 3 steps 1.
Action comparison: Each IntentFilter object must contain Action information, if not, any Intent object
will fail to match 2. Data and Type comparison: Data and Type Information is the most complex data
item in the Intent Filter, and its comparison algorithm is the key to determining the degree of matching
between Intent and Intent Filter objects. 3. Category comparison

Selection of matching components

If there are multiple Intent Filter objects that match the Intent objects issued by the calling component,
you need to filter in all eligible Intent Filter objects, and select the implementation component that
best meets the calling component and user needs. This is the matching component. select.

It can be set by setting the priority of the Intent Filter object, that is, through the android:priority
attribute in the configuration item, or dynamically modified through the IntentFilter.setPriority function.
The range is -1000 to 1000, and the default is 0. The larger the value, the higher the priority.

Matching optimizationIn the Intent mechanism, by introducing third-party component management


services, the coupling between calling components and implementation components is reduced, the
flexibility of the entire system and the reusability of components are improved, and application
development becomes simpler Fast. But at the same time, it is precisely due to the intervention of
third-party services that increase the cost of connection between components, which may make the
calls between components not smooth. Therefore, in the component management service, the
system performs a lot of optimizations on the matching and selection process of components to
improve the efficiency of component calling, including:

(1) Index The component management service uses a hash table to build indexes for the Action,
Type and other data items of all Intent Filter objects. Each index item corresponds to a group of Intent
Filter objects with the same Action, the same Type or the same other data items. The Intent is first
compared with the index item, and the Intent Filter object that may match the Intent is quickly
selected. To speed up the matching speed.

(2) Cache Record the matching results of Intent and Intent Filter. When the same Intent is called
again, the last recorded result can be directly returned, thereby skipping the process of intent
matching and accelerating the calling of components. Service components, component management
services will retain the service components corresponding to each Intent in the form of a hash table in
memory.

You might also like