Android official documentation-Introduction
In front of the article: It's not too short to get started with Android. I listened to the video, read the book, typed the code, wrote a blog, and made a demo... But there is still a long way to go to make an excellent APP (even if it is encapsulated with a good function. So some days ago, I planned to study Android at the underlying layer and in the source code more deeply. I just bought a copy of "Android group English Biography" to read it. When I first read the preface, I found that the author recommended the official Training and Guide, and I realized that the Android knowledge from all the channels I used was actually from the official documentation. Instead of having a deeper understanding of Android, it is better to read the content of the official document. It is the best teaching material. From today on, I will try to translate the official Android documents. Of course, it is not all about the content, but what I think is important. Some basic content will be skipped.
This article will start with Introduction.
To access the original official text, click this link: Introduction to Android.
Android Introduction (Introduction to Android)
Android applications provide multiple access Portals
An Android application consists of different independent components and can be called independently. For example, an Activity can provide a screen UI display and a Service can be used to execute tasks in the background.
Start another component in one component. You can use intent or even use intent to start other general applications. This allows an application to have multiple access portals, in addition, you can make a component of another application look like a part of your application.
One application can adapt to different devices
Android provides an adaptive framework. A resource can adapt to different devices. For example, a layout automatically matches the screen of different devices. Developers can view the permissions required by the application when the application is running. developers can also declare the required permissions in their own applications. Google Play can automatically filter devices that support the permissions required by the application, this reduces unnecessary adaptation issues.
Application Fundamentals)
Android applications are mainly written in Java. Android SDK Tools Package code, resource files, and data into APK files. The APK file contains all the components of the application. The APK file can be installed and used on devices that support Android.
Once the installation is successful, the application will be protected by the sandbox mechanism:
The Android operating system is a multi-user Linux operating system. Each application represents a user.
By default, the system assigns a user ID to each APP (this user ID is invisible to the APP and only visible to the system). The system uses an APP to manage all files, this APP also has a user ID, which can be used to access these permissions.
Each application has an independent virtual machine, which allows each application to run without interference.
By default, each APP has its own Linux Process. If a component of an application needs to be executed, Android will start the process of the application. On the contrary, when the application is no longer used or the system memory is insufficient, the process of the application will be stopped.
According to the preceding requirements, Android is a system that meets the principle of minimum permission (principle of least privilege). That is to say, by default, each APP can only start the required functional components, if the system does not grant its permission to the content, the APP will not be able to access it.
However, using the following method, applications can share data or programs can access system services:
Apps can share Linux user IDs. In this way, apps can share data. To save system resources, apps that share the same Linux user IDs use the same process, and run on the same Virtual Machine (the APP must have the same signature ). Apps can apply for system data access permissions, such as user contacts, short messages, SD cards, Bluetooth, and cameras. You must explicitly grant these Permissions to the application. For more information, visit this link: Working with System Permissions. for more information, see my translated blog "Introduction to runtime permissions for Android 6.0 and later versions".
The following describes the core components of the APP, the manifest file, the resource file separated from the code, and how to use the resource file modifier to adapt to different devices.
APP Components)
That is to say, the four major components, each of which has its own independent life cycle, the Manager component creation and destruction.
Activities
Activity represents the UI that interacts with users (it is not a UI, but a carrier used to present the UI). The content on the screen you see is carried by Activity. To access the official Activity documentation, click this link: Activities. Of course, I will also translate this document in subsequent blog posts.
Services
A Service is a component running in the background. It is mainly used for persistent connections and remote operations. It does not have a UI interface to interact with users. For example, a Service can run music in the background or download data from the Internet without affecting user UI operations. You can start or bind a Service to the Activity for communication.
Content providers
Content provider manages data information in an APP. You can store data in any persistent storage location, such as the SQLite database, file system, and network. Other applications can access the data of this application through content provider. For example, the Content Provider in the Contact application of the system provides the address book information. You can access the address book information of the system by using the ContactsContract. Data class (with Content Resolver.
Content Provider provides better protection for data privacy of applications.
Broadcast receivers
Broadcast receivers is used to receive various Broadcast messages from the system. There are many broadcast systems, such as: when the screen is turned off, when the power is low, when the image is obtained. Applications can also customize broadcasts. For example, when an APP downloads some information and needs to notify other apps that "the information has been downloaded for use", the APP can issue a broadcast, other applications can intercept the broadcast. Broadcast receivers cannot be displayed in the UI, but a Notification is displayed, indicating that a Broadcast is sent. To put it simply, Broadcast receivers only initiates an intent, which can guide the application that is interested in the intent to do something.
One unique design of the Android system is that any APP can use the components of another APP. For example, if you want to use the system camera to take a photo, you can use your own APP to start the APP, without having to write the code for the camera function from the beginning, you do not need to associate the code of your APP with the code of the photo APP. You only need to use your own activity to start the activity with the camera function and return the photo result. This activity with the camera function is like a part of its own application.
When you start an APP component, you start the process where the APP is located and initialize the component class. For example, your APP starts the activity in the camera application, the activity will run in the Process of the camera application, rather than in your APP. Therefore, the Android application does not have a unique entry (for example, the main () method is not available ).
Activating Components)
With the asynchronous request of intent, you can start activities, services, and broadcast receivers. Intent binds different components at runtime, regardless of whether these components come from the same application. There are two ways to start a component through intent: Implicit intent and explicit intent. These two methods will be described in the future.
For starting an activity or service, intent can append some actions or some Uris pointing to specific data content. For example, some intents want to start an activity with the function of displaying images, or they want to open a webpage. In some cases, the started component will return some data through intent (for example, if you want intent to open a contact in the address book and return the contact information, the returned information will be included in the intent, it also contains the URI information pointing to this contact ).
For broadcast receivers, you can declare in intent-filter what type of broadcast you want to receive. For example, you want to receive a "low-power" broadcast from the system in your application, you only need to configure the "Low Power" message in your broadcast receivers.
Intent cannot be started for content provider. The Content Provider must be paired with ContentResolver. Content resolver is responsible for processing ContentProvider transactions with the object. Therefore, ContentProvider can transmit data without explicitly calling methods in contentResolver. This method separates the data in the application from the method used to access the data, improving the security of the application.
You can start the corresponding components using the following methods:
Start Activity: startActivity () or startActivityForResult () Start Service: startService (); bind Service: bindService () Start Broadcast: sendBroadcast (), sendOrderedBroadcast (), or sendStickyBroadcast () to query the data information provided by the content provider, you can call ContentResolver. query () method. Manifest File (The Manifest File)
Before using a component, you must register the component in the Manifest file. In addition to registering components, the Manifest file can also do the following:
To apply for required permissions for an application (such as system contacts and intent access), you must configure use-permissions to define the minimum API, you need to configure the minimum SDK Version to declare the hardware and software configurations required for the application (such as Bluetooth, cameras, and multi-touch screens). You need to use the API library that the-features application needs to connect, for example, for Google Maps library, Declaring components is required)
The method for configuring an activity is as follows:
...
Where
The icon attribute of the tag is used to configure the startup icon.
The name attribute of the tag is used to register the child class of the activity in the application. You must use the fully qualified name for registration.
In addition to static registration in the ManiFest file, broadcast receivers can also be dynamically registered using the registerReceiver () method in the code. For more information about the ManiFest file, click this link: App Manifest, which will be translated in subsequent articles.
Declaring component capabilities)
The true strength of intent lies in its implicit start. The implicit intent can describe the features of the target component to be started without specifying the name of the target component.
By configuring intent filters for a component, the component can be implicitly filtered by intent. Only when the filter matches the conditions in intent filters can the component be implicitly started by intent. For example, if you want to configure an email sending activity in the application so that the intent of "email sending" is indicated by implicit intent, you can configure intent filters for the activity as follows:
...
For more information about intent filter, visit this link: Intents and Intent Filters.
Declaring APP requirements)
Devices that support Android vary, and the underlying drivers they support have their own merits. To prevent applications that require an underlying Driver (such as applications with camera functions) install it on a device that does not support this function (the device does not have a camera) and configure it in the manifest file, this configuration information is only descriptive in the system (that is, the Android system does not read this configuration description), but when an application is published to a platform (such as Google play, the Platform reads these statements. For example, if your application needs to call the System camera and run on a device with the minimum Android 2.1 (API 7) version, you need to configure the following:
...
Devices lower than android 2.1 or not supporting cameras cannot search for the app on Google play.
You can also declare that your app uses a camera, but it is not required. Set the android: required attribute of the use-features tag to false, check whether the device has a camera in the code, and disable all camera-related functions.
APP Resources)
APP resources are separated from codes. These resources include visual resources such as images and videos. For example, you can define layout resources of animations, menus, styles, colors, or activity. Using resource configuration, You can decouple code and adapt it to more devices.
For each resource, the SDK tool sets a unique integer ID for it. With this ID, you can reference this resource in the code,
Adapting resources to different devices is the biggest advantage of APP resources. You can append a modifier (qualifier) to match different devices. For example, if the res/values-fr/folder contains French strings, the default res/values/directory contains the default string information, the system automatically matches the content of different files according to the system language of the device you have installed.
There are still many such delimiters. For example, you can append modifiers to adapt to different la s of horizontal and vertical screens. For the official documentation on resource modifiers, click this link: Providing Resources.
Device Compatibility)
Tens of millions of android devices require good compatibility with your android applications. Android provides modifiers to better adapt to various types of screens.
There are two types of compatibility: device compatibility and APP compatibility ).
You don't have to worry about device compatibility. android devices are compatible with apps that can be published on Google play.
However, you have to pay attention to APP compatibility because different devices have different hardware support. For example, some applications require the underlying support of the compass, devices that do not support the compass cannot run the application.
Check whether the device supports the compass function. If not, disable it:
PackageManager pm = getPackageManager();if (!pm.hasSystemFeature(PackageManager.FEATURE_SENSOR_COMPASS)) { // This device does not have a compass, turn off the compass feature disableCompassFeature();}
Every android version is backward compatible with the application. That is to say, you should adapt the application to a new version for forward compatibility (In my experience, assuming that the most popular version on the market is android 5.1, you should set the targetSDKVersion of the application to 23 (android 6.0 ), this setting indicates that your application can run properly on the android 5.1 device, which ensures that your application will not crash when the device with the highest share of android is upgraded to android. Therefore, you can set targetSDKVersion to 1-2 versions higher than the current version with the highest market share.)
System Permissions Security Architecture of Android)
By default, each application does not have any permissions to access other applications, system settings, and user private data. Including reading and writing users' private information (address book and email), reading and writing data from other applications, accessing the Internet, and keeping the device awake.
Based on the sandbox mechanism of the android system, the application must explicitly share data and resources. This requires explicit permission application: The application explicitly applies for permissions in the configuration, the user's consent is also required.
Application Signature
All apk files must be signed with a certificate and the developer holds a private key. This signed certificate is used to authenticate the application developer. Instead of being authenticated by an authority, this certificate is self-signed by development tools. Using this certificate can protect developers' rights and interests, in addition, the system can allow or deny the application's signature-level permissions ); the certificate can also allow or deny the application request to have the same Linux ID (request to be given the same Linux identity) with other applications.
User IDs and File Access)
During application installation, android assigns each package (android identifies different applications by package name) a specific Linux User ID (Linux User ID), from installation to uninstallation of the application, this ID always exists and remains unchanged. IDS may be different on different devices, but they are unique on the same device.
For security reasons, two different packages (applications) cannot be in the same process. However, you can. the sharedUserId attribute in the manifest label of the xml file configures the same User ID for different packages (applications). Then, the two packages (applications) are considered as an application, they have the same user ID and file permissions ). Note that, for the sake of security,The two applications have the same signature and are configured with the same sharedUserId attribute, so that the two applications have the same user ID.
Data stored by one application is assigned to the user ID of the application, which cannot be shared by other applications.
Using Permissions)
By default, an Android application is granted any permissions, which adversely affects user experience or data access. You must use
Label to add permissions.
For example, if you want the simulator to receive short messages, you can use the following code to add permissions:
...
If you apply for basic permissions (normal permission; basic permissions do not affect your privacy or the operation of your devices), the system automatically grants these permissions; if you apply for a dangerous permission (dangerous permission; dangerous permission means that this permission may have a potential impact on the user's privacy or the operation of the device (potentially affect )) [for an official introduction to permission levels, click this link: Normal and Dangerous Permissions]. The system will explicitly inform and request user authorization. The notification and request methods vary depending on the version of the device:
If your device is Android 6.0 (API level 23) or later and the targetSdkVersion set by the application is 23 or later, the application will request permissions from the user during the running stage, you can also revoke the granted permissions at any time, so the application will view its own permissions each time it runs. For more information about runtime permissions, visit my blog: Introduction to runtime permissions for Android 6.0 and later. If your device is Android 5.1 (API level 22) or earlier and the targetSdkVersion set by the application is 22 or below, the application will request the user to grant permissions during installation. If you add a new permission to the new APP version, the APP requests the user to grant the new permission when installing the new version. Once you have installed an application, you agree to grant all the requested permissions. to cancel any permissions, you can only uninstall the application.
In some cases, a SecurityException exception is thrown when the application fails to request permissions, but this exception will be thrown at any time. In most cases, when the request permission fails, only the Log is printed.
A special permission may be used in multiple places:
When calling some methods inside the system: the system will prevent applications from accessing some core methods inside the system; when starting an Activity of another APP; when sending and receiving a broadcast, this permission can determine who can receive the broadcast, or who can launch the broadcast to you; when the content provider is operated; when the service is started or bound. Automatic permission)
To ensure that your application can always adapt to the permissions added by the new API version, we recommend that you set targetSdkVersion as high as possible (as high as possible ).
Normal and Dangerous Permissions)
The system divides permissions into several levels. The most important two levels are basic permissions and dangerous permissions.
The basic permission is that your application needs to access data or resources outside the sandbox, but this will have almost no impact on user privacy and system operation. For example, the "Set Time Zone" permission is a basic permission. If you have configured basic permissions in the manifest file, the permissions are automatically granted without requiring users. Dangerous permissions refer to applications that may access users' privacy information, potentially affect users' stored data, or affect the operation of other apps. For example, "reading a user's contact" is a dangerous permission. If you have configured a dangerous permission in the manifest file, the permission must be explicitly granted to the user during use. Permission groups)
All dangerous permissions are divided into permission groups. If the device version is Android 6.0 (API level 23) or later and targetSdkVersion is 23 or higher. When your APP requests dangerous permission, the following actions will occur:
If your application is applying for dangerous permissions configured in manifest, a dialog box is displayed, which describes the permission group to which the Dangerous permission belongs, not just the permission. For example, if your application is requesting the READ_CONTACTS permission, the system will only pop up the dialog box that the application is requesting the device's contacts. If the user agrees to the request, the system only grants a single permission to the request. If your application is applying for dangerous permissions configured in manifest and the user has previously granted other permissions to the permission group to which the permission belongs, at this time, this dangerous permission will be automatically granted without the user's consent. For example, if the application has previously obtained the READ_CONTACTS permission, the permission is automatically granted when the application requests the WRITE _ CONTACTS permission, without the need to request the user.
In fact, both basic and dangerous permissions are divided into permission groups, but only the permission group where the dangerous permissions are located will happen. Therefore, you can ignore the basic permissions in the permission group.
If the device version is Android 5.1 (API level 22) or below and targetSdkVersion is 22 or below, the system will declare all required permissions during application installation, these declarations are presented to the user as permission groups, rather than individual permissions.
The following lists dangerous permissions and their permission groups:
Define and Enforcing Permissions)
To customize permissions, you must use
Label declaration.
For example, if you want to control the startup right of an Activity (who can start the Activity), you can configure the following code:
...
Where
Attribute cannot be default. This attribute indicates the level of the permission requested, or who can be allowed to hold this permission.
Attribute is optional. This attribute is only used to display permissions to users in groups. You can set this attribute to a standard permission group (android. manifest. permission_group), you can also set a custom permission group. The former is recommended because it can reduce the number of pop-up dialog boxes. Label and description are user-defined attributes. When you view the permissions of an application, the content in the label attribute is displayed, and the specific description of permissions is the content in the description. The custom property name label should be concise and clear, and can accurately represent the content protected by this permission, description should use a few words to describe what the permission allows the application to do and may bring about a snoop on user privacy. The following is an example of a custom CALL_PHONE label and description:
directly call phone numbers
Allows the application to call phone numbers without your intervention. Malicious applications may cause unexpected calls on your phone bill. Note that this does not allow the application to call emergency numbers.
Enforcing Permissions in AndroidManifest. xml)
If you declare High-level permissions in the manifest file, this permission is not available to all components. If you want to obtain high-level permissions for a certain component, you should use the android: permission attribute in the tag of this component to declare this advanced permission.
Activity permission: the advanced permissions declared in the activity tag can control who can start the activity. You should call Context. startActivity () and Activity. startActivityForResult () method to determine whether the activity can be started. If this permission is not granted, the two methods throw a SecurityException. Service permission: the advanced permissions declared in the service tag can control who can start or bind the service, you must call Context. startService (), Context. stopService () and Context. the bindService () method determines whether the service can be started or bound. If this permission is not granted, the three methods will throw a SecurityException; BroadcastReceiver permission: the advanced permissions declared in the receiver label can control who can send a broadcast to the BroadcastReceiver. you should. after the sendBroadcast () method is returned, the system checks whether the permission is granted, because it attempts to send the broadcast to other referers that meet the conditions. Therefore, if the referers declared with advanced permissions are not connected If broadcast or sendBroadcast () method is used, no exception is thrown. the registerReceiver () method dynamically registers the aggreger, which can also be granted with high-level permissions; ContentProvider permissions: the advanced permissions declared in the provider label can control who has the right to access the data provided by the provider (contentprovider also provides URI Permission, which will be described later ). Different from other components, the provider can declare two permission attributes: android: readPermission and android: writePermission. The former can control who can read the data of the provider, the latter can control who can write data to the provider. Only components with the permission to write to this provider can be read, and vice versa. When you retrieve the provider for the first time, this advanced permission will be detected (if you do not have the permission, SecurityException will be thrown), where ContentResolver. the query () method requires the android: readPermission attribute, ContentResolver. insert (), ContentResolver. update (), ContentResolver. delete () requires the android: writePermission permission. If the permission is not set, the above method throws a SecurityException. Enforcing Permissions when Sending Broadcasts)
In addition to the advanced permissions declared by the broadcast receiver, you can also pass in a String-type permission by calling Context. sendBroadcast.
Because both Broadcasts and javaser can be granted permissions, both permissions must be filtered by intent to match.
URI permission (URI Permissions)
For security reasons, you can declare the content provider to protect its read and write permissions. For example, you need permissions to obtain the email, but the URI is directed to an image browser. This browser cannot open the email because the browser is not granted the permission to open the email.
To solve this problem, you can set the intent. FLAG_GRANT_READ _ URI _ PERMISSION or Intent. FLAG_GRANT_WRITE_URI_PERMISSION field when you start the activity.