Introduction of official Android documents

Source: Internet
Author: User
Tags set time least privilege

Written in front of the words: Touch Android Time is not short, listened to the video, read the book, hit the code, wrote a blog, did the demo ... But there is a long way to go to make a good app (even if it's a good feature). So I was going to go deeper to the bottom, and go to the source code direction. android--I bought a copy of "Android Heroes", and when I first read the preface, I found that the author recommended reading the official training and guide, and I realized that In fact, I have access to the various channels of Android knowledge, are from the official documents, and more in-depth understanding of Android, rather than the official documents to read the content, it is the best teaching materials. From today onwards, I will try to translate the official Android documents, of course not the whole content, but I think important knowledge points, some very basic content is skipped.

This article will start with the official document, "Introduction".
To access the official text, please click on this link: "Introduction to Android".

Android Introduction (Introduction to Android)
    • Android app offers a variety of access portals
      An Android application is made up of separate components and can be called independently, such as an activity that provides a one-screen UI display, and a service that can be used to perform tasks in the background.
      Starting another component in one component, you can use intent, and you can even start other generic programs with intent, which allows an application to have multiple access portals and can make a component of another application appear as part of its own application.

    • One application can be adapted to a different device
      Android provides a framework for adaptation and a resource that can be adapted to different devices. For example, a layout will automatically match the screen of different devices. Developers can view the permissions required by the application while the app is running, and developers can declare the required permissions in their own apps, and Google play automatically filters the devices that support the app's required permissions, reducing unnecessary adaptation issues.

Application Basics (Application Fundamentals)

Android apps are written primarily by Java, and the Android SDK tool packs code, resource files, and data content into APK files. The APK file contains all the components of the application, which can be installed and used on Android-enabled devices.
Once the installation is successful, the application is protected by the sandbox mechanism:

    • The Android operating system is a multi-user Linux operating system, and each application represents a user.

    • By default, each app is assigned a user ID (the user ID is not visible to the app, only the system is visible), and the system uses an app to manage permissions for all files, and the app has a user ID that is used to access these permissions.

    • Each application has a separate virtual machine, which allows each application to run with no interference.

    • By default, each app has its own Linux process. A component of an app needs to be executed, and Android launches the app's process, whereas the app's process will be stopped when the app is no longer in use or system memory is tight.

With these requirements, Android is a system that satisfies the principle of least privilege (principle of least privilege), which means that, by default, each app can only start the functional components it requires, and the content that the system does not give its permission, the app will not be accessible.
However, you can share data between applications by using the following methods, or programs can access system services:

    • Linux user IDs can be shared between apps, and in this way, apps can share data, and in order to conserve system resources, apps that share the same Linux user ID will use the same process and run on the same virtual machine (the app must have the same signature).
    • Apps can request access to system data such as user contacts, short messages, SD cards, Bluetooth, webcams, etc. Users must explicitly grant these permissions to be applied, for more information, please visit this link: "Working with System Permissions", or refer to my translated blog "Introduction to runtime permissions for Android 6.0 and above".

The following describes the core basic components of the app, the manifest file, the resource files that are separated from the code, and how to use the resource files to decorate the applies with different devices.

App components (APP)

The so-called four components, each with its own independent life cycle, the creation and destruction of management components.

    The
    • Activities
      Activity represents the UI that interacts with the user (it is not a UI, but a vector for rendering the UI), and the content on the screen you see is the activity carrier. To access the official documentation on activity, please click on this link: "Activities", and of course I will also translate the document in subsequent blog post. The

    • Services
      Service is a component that runs in the background and is used primarily for long and remote operations, and it has no UI interface to interact with the user. For example, the service can run music in the background or download data from the web without affecting the user's UI actions. You can start or bind the service in activity to communicate with it.

    • Content providers
      Content provider manages the data information in an app. You can store the data in any place that can be persisted, such as SQLite database, file system, network, etc. Other apps can access the app's data information through content provider. For example, content provider in the system's contact application provides address book information, and you can access the system's address book information using the Contactscontract.data class (with content Resolver). The
      Content provider provides a good protection of the data privacy of the application. The

    • Broadcast receivers
      Broadcast receivers is used to receive various broadcast messages from the system. There are many system broadcasts, such as: when the screen is off, when the battery is low, get the picture. Applications can also customize broadcasts, such as when the app downloads some information to notify other apps that "the information has been downloaded for use", the app can issue a broadcast, and other apps can intercept the broadcast. Broadcast receivers also fails to enter the UI display, but displays a notification indicating that a broadcast has been issued. More simply, broadcast receivers only initiated an intent to guide the application that is interested in the intent to do something.

A unique design of the Android system is that any app can be a component of another app, for example, if you're going to use a system camera to take a photo, use your own app to start it, without having to write the camera code from scratch, You also don't need to associate your app's code with the code of the Camera app. You only need to use your activity to start the activity with the camera function and return to the photographic results. This activity with a photographic function is like a part of your own application.
When you launch a component of an app, you start the process where the app is located and initialize the component's class, for example, your app launches the activity in the camera app, and the activity runs in the process that belongs to the camera app, not your app. Therefore, there is no unique entry for Android apps (such as without the main () method).

Starter Kit (activating components)

By intent this asynchronous request, you can start the three components of activities, services, and broadcast receivers, intent bind different components at run time, regardless of whether they come from the same application. There are two ways to start a component through intent: implicit intent and explicit intent, both of which are described in detail in subsequent poise.
You can attach some action to start activity or service,intent, or a URI that points to specific data content. For example, some intent intend to start an activity with a display image function, or to open a Web page, in some cases, the launched component will return some data via intent (for example, if you want intent to open a contact for an address book, and returns the information for this contact, the information returned is contained in intent, and also contains the URI information that points to the contact person.

For broadcast receivers, you can declare in Intent-filter what kind of broadcast you want to receive, for example, if you're going to receive a "low-power" broadcast from your app, you just need to be in your broadcast You can configure the "low power" message in the receivers.

For content provider, intent cannot be started. The Content provider needs to be paired with Contentresolver. The content resolver is responsible for handling the ContentProvider transaction with the object, so ContentProvider can pass the data without explicitly invoking the method in Contentresolver. This approach is a good way to separate the data in the application from the method of accessing the data, which improves the security of the application.

You can start the corresponding component using the following methods:

    • Start activity:startactivity () or Startactivityforresult ()
    • Start Service:startservice (); bind Service:bindservice ()
    • Start Broadcast:sendbroadcast (), Sendorderedbroadcast (), or sendstickybroadcast ()
    • You can call the Contentresolver.query () method if you want to query the data information provided in the content provider.
Manifest files (the Manifest file)

Before using the component, you need to register the component in the manifest file. In addition to registering components, the manifest file can do the following things:

    • To apply the required permissions for the application (such as system contacts, access intent, etc.), configure the Use-permissions
    • To define the minimum API, configure the minimum SDK Version
    • Declare the hardware and software configurations required to use the app (such as Bluetooth, camera, multi-touch screen), use-features
    • To apply the required links to the API library, such as the Google Maps Library, you need to configure Meta-data
    • Other
Declaration component (declaring components)

Here's how to configure activity:

<?xml version="1.0" encoding="utf-8"... >    <application android:icon="@drawable/app_icon.png"... >        <activity android:name="com.example.project.ExampleActivity"                  android:label="@string/example_label"... >        </activity>        ...    </application></manifest>

Where <application> the label's icon property is used to configure the startup icon. <activity>the label's Name property is used to register the subclass of activity in the app, and it needs to be registered with a fully qualified name.
Broadcast receivers can be dynamically registered in code by using the Registerreceiver () method in addition to being able to register statically in the manifest file. For more information about the Manifest file, please click on this link: "App Manifest", I will translate the document in a subsequent article.

Declaring the compatibility of components (declaring component capabilities)

The real strength of intent is its implicit startup, which implicitly intent can describe the features of the target component it wants to start without specifying the name of the target component.
By configuring intent filters for a component, the component has the ability to be implicitly intent filtered, and the component can be started implicitly filters only if it matches the conditions in the intent intent. For example, you intend to configure an activity for sending mail in your app so that the intent to "send mail" is indicated by an implicit intent, so you can configure intent filters for activity:

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

For more information about Intent filter, please visit this link: "Intents and Intent Filters"

Declare the software and hardware information required by the app (declaring app requirements)

Android-enabled devices vary, and the underlying drivers they support are also different, in order to prevent applications that require a certain underlying driver (such as apps with a camera feature) from being installed on devices that do not support the feature (the device does not have a webcam), and it needs to be configured in the manifest file. This configuration information is only descriptive in the system (that is, the Android system does not read the configuration instructions), but when the app is posted to a platform, such as Google Play, the platform reads the claims. For example, your app needs to call the system camera and run on a device with a minimum version of Android 2.1 (API 7), which you need to configure as follows:

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

Devices that are below Android 2.1 or do not support the camera will not be able to search for the app on Google Play.
You can also declare that your app is using a webcam but not necessary, which requires setting the Android:required property of the use-features tag to false, and in the code to detect if the device has a camera and turns off all camera-related features.

App resource (app resources)

The app resources are separated from the code, which includes visual resources such as pictures, videos, and more. For example, you can define animations, menus, styles, colors, or activity's layout resources, and use resource configurations to decouple the code and adapt it to more devices.
For each resource, the SDK tool sets a unique integer ID, which allows you to reference the resource in your code.
Adapting resources to a variety of devices is the biggest advantage of app resources, and you can append modifiers (qualifier) to the resource file name to match different devices. If you place the string information in French in the res/values-fr/folder, and the default string information is placed in the default res/values/directory, the system automatically matches the contents of different files according to the device system language you installed.
There are many more qualifiers like this, such as you can also append modifiers to different layouts that fit the screen. For official documentation of resource modifiers, please click on this link: "Providing resources".

Compatibility of devices (device compatibility)

Android device thousands, which requires good compatibility with your Android app. To better fit a variety of screens, Android provides modifiers.
There are two types of compatibility: Device compatibility and app compatibility (app compatibility).
For device compatibility, you don't have to worry that Android devices are compatible with apps that can be posted on Google Play.
But for app compatibility, you have to be aware of the fact that the hardware support for different devices varies, for example, if some applications require the compass's underlying support, then devices that do not support the compass will not be able to run the app.

The following is whether the detection device supports the COMPASS function, and if not, turn it off:

PackageManager pm = getPackageManager();if (!pm.hasSystemFeature(PackageManager.FEATURE_SENSOR_COMPASS)) {    //Thisnot have a compass, turn off the compass feature    disableCompassFeature();}

Each Android version is a backwards compatible adaptation for your app, meaning that you should adapt your application to a new version for forward compatibility ( in my experience, assuming the most current version of the market is Android 5.1, you should set the app's targetsdkversion to 6.0, which indicates that your application works on android6.0 devices, which guarantees the highest share of Android 5.1 of devices upgrade to android6.0, your application does not crash. Therefore, the targetsdkversion is generally set to a higher than the current market share of the highest version of the device 1-2 version can be. )

System permissions (Permissions) Android security Architecture (Architecture)

By default, each app has no permissions to access other apps, system settings, and user's privacy data. This includes reading and writing the user's private information (contacts and messages), reading and writing data from other applications, accessing the Internet, keeping the device awake, and so on.
Based on the sandbox mechanism of the Android system, the application must explicitly share the data and resources, which requires explicit permission to apply: The app explicitly applies permissions in the configuration and needs the user's consent.

The signature of the app

All apk files must be signed with a certificate and developed to hold a private key. This signed certificate is the application developer certification, this certificate does not need to be certified by the authority, but is self-signed by the development tool, the use of certificates to protect the interests of developers, and the system can allow or deny the application use of the signing level of permissions (Signature-level permissions); Certificates can also allow or deny app requests the right to hold the same Linux ID as other apps (request to be given the same Linux identity).

User IDs and file access

When the app is installed, Android gives each package (Android with the package name to differentiate between different apps) a certain Linux user ID (linux username), from the installation of the app to the uninstall, the ID is always present and remains the same. The ID may be different on different devices, but the ID will remain unique on the same device.

For security reasons, two different packages (applications) cannot be in the same process under normal circumstances; You can configure the same userid (user ID) for different packages (apps) in the Shareduserid attribute in the manifest tag of the Androidmanifest.xml file, when two packages (apps) are considered an application, They have the same user ID and file permissions as the users ID and document permissions. It is important to note that for security reasons, two apps have the same signature, and the same Shareduserid attribute is configured, and the two apps have the same user ID.

The data stored by an app is given the app's user ID, and other apps can't share it.

Usage rights (using Permissions)

By default, an Android application is given any permissions, which can adversely affect the user's experience or access to data. In order to use the features protected by the device, you must <uses-permission> add permissions using the tag.
For example, if you want the simulator to be able to receive short messages sent over, use the following code to add permissions:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.android.app.myapp" >    <uses-permission android:name="android.permission.RECEIVE_SMS" />    ...</manifest>

If you are applying for basic permissions (normal permission; Basic permissions mean that the permission does not negatively affect the user's privacy or the operation of the device), these permissions are automatically granted if you apply for dangerous permissions (dangerous permission A dangerous permission means that the permission may have a potential impact on the user's privacy or the operation of the device (potentially affect)) "For an official introduction to the permission level, please click on this link:" Normal and Dangerous Permissions ", The system explicitly informs and requests the user to authorize. The version of the device differs in the way it is communicated and requested:

    • If your device is Android 6.0 (API level 23) or above, and the app set Targetsdkversion is 23 or higher, the app will ask the user for permission at run time, and the user can revoke the assigned permission at any point. So the app will see its permissions every time it runs. For more information about runtime permissions, you can access my blog: Introduction to runtime permissions for Android version 6.0 and above.
    • If your device is Android 5.1 (API level 22) or the following version, and the app set Targetsdkversion is 22 or less, the app will ask the user to grant permission at the time of installation. If you add new permissions to the new app version, the app will ask the user to give that new permission when you install the newer version. Once you install the app, you agree to give all the requested permissions, and if you want to cancel any permissions, you can only uninstall the app.

Sometimes, when the application request permission fails, it throws a SecurityException exception, but this one is not always thrown, mostly in cases where the request permission fails, only the log is printed.

A particular privilege may be used in multiple places:

    • When calling some methods inside the system: The system prevents the application from accessing some core methods inside the system;
    • When activating activity for a different app;
    • When sending and receiving a broadcast, that permission can determine who can receive the broadcast, or who can initiate the broadcast to you;
    • When manipulating content provider;
    • When the service is started or bound.
Adaptive permissions (Automatic permission adjustments)

To ensure that your app always fits the new API version, it is recommended to set the targetsdkversion to as high as possible (as hi as possible).

Basic permissions and Dangerous permissions (Normal and Dangerous Permissions)

The system divides the permissions into several levels, the most important of which are the basic permissions and the dangerous permissions of the two levels.

    • Basic permissions say that your app needs to access data or resources outside of the sandbox, but this has little impact on user privacy and system operation. For example, the "Set time zone" permission is a basic permission. If you configure basic permissions in the manifest file, the permission is automatically assigned without requesting the user.
    • Dangerous permissions say that the application accesses the user's private information, has a potential impact on the data stored by the user, or affects the operation of other apps. For example, "read a user's contact" is a dangerous permission, if you configure a dangerous permission in the manifest file, then the permission needs to be explicitly given by the user when used.
Permission Group (Permission groups)

All dangerous permissions are divided into permission groups, if the device's version number is Android 6.0 (API level 23) or above, and targetsdkversion is 23 or higher. When your app requests dangerous permissions, the following behavior occurs:

    • If your app is requesting dangerous permissions that are configured in manifest, a dialog box appears that describes the permission group that the dangerous permission belongs to, not just the permission. For example, when your app is requesting read_contacts permissions, the system simply pops up a dialog box that the app is requesting device contacts (Devices ' s contacts). If the user agrees to the request, the system only gives the request a single permission.
    • If your app is requesting the dangerous permissions configured in manifest and the user has previously given other permissions to the permission group that the permission belongs to, then this dangerous permission will automatically be assigned without user consent. For example, if the application has previously obtained read_contacts permissions, then when the app requests the Write _contacts permission, the permission is automatically assigned without requesting the user.

In fact, both the basic and the dangerous permissions are divided into permission groups, but only the permission groups where the dangerous permissions are located will occur, so you can ignore the basic permissions in the permission group.

If the version of the device is Android 5.1 (API level 22) or below, and targetsdkversion is 22 or less, the system will declare all of the required permissions when the app is installed, which are presented to the user as permission groups rather than as individual permissions.
The following are the dangerous permissions and their permission groups:

Customize and Execute permissions (defining and enforcing Permissions)

If you intend to customize permissions, you need to use the label declaration in the manifest file <permission> .
For example, if you intend to control the start of an activity (who can initiate the activity), you can configure the following code:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.me.app.myapp" >    <permission android:name="com.me.app.myapp.permission.DEADLY_ACTIVITY"        android:label="@string/permlab_deadlyActivity"        android:description="@string/permdesc_deadlyActivity"        android:permissionGroup="android.permission-group.COST_MONEY"        android:protectionLevel="dangerous" />    ...</manifest>

which

    • <protectionLevel>A property cannot be defaulted, indicating the level at which the permission is requested, or who can be allowed to hold the permission.
    • <permissionGroup>property is optional and is used only as a group to display permissions to the user, you can set the property to a standard permission Group standard permission group (Android. Manifest.permission_group), you can also set a custom permission group. It is recommended to use the former because it reduces the number of pop-up dialog boxes.
    • Both label and description are user-defined properties, and when the user views the permissions that the app has, the content in the Label property is displayed, and the specific description of the permission is the content in description. Custom property names label should be concise and accurate to represent the rights-protected content, while description should describe permissions in a few words to allow the app to do things and to spy on the user's privacy. The following is an example of a custom Call_phone label and description:
<string name="Permlab_callphone">directly Call Phone numbers</string> <string name="Permdesc_callphone">allows the Application  toCall phone NumberswithoutYour intervention. Malicious applications may cause unexpected calls onYour phone bill. Note thatThisdoes  notAllow the Application  toCall Emergency numbers.</string>
Permissions enforced in the manifest (enforcing Permissions in androidmanifest.xml)

If you declare advanced permissions (high-level permissions) in the manifest file, this permission is not available to all components, and if you want to get advanced permissions for a component, you should do so in the label for that component Android:permission Property declares this advanced permission.

  • Activity permissions: The advanced permissions declared in the Activity tab control who can initiate the activity, and 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 will throw a SecurityException exception;
  • Service permissions: The advanced permissions declared in the service tag can control who can start or bind the service, and you need to call Context.startservice (), Context.stopservice (), and The Context.bindservice () method determines whether the service can be started or bound, and if this permission is not given, the three methods will throw a SecurityException exception;
  • Broadcastreceiver Permissions: The advanced permissions declared in the Receiver tab control who can send the broadcast to the Broadcastreceiver, and you should be in Context.sendbroadcast () The method returns to determine whether the permission is given, because it attempts to send the broadcast to other receiver that satisfies the condition, so if receiver that declares the advanced permission does not receive the Broadcast,sendbroadcast () The method does not throw an exception, and if you use the Context.registerreceiver () method to register receiver dynamically, you can also give the receiver advanced privileges;
  • ContentProvider Permissions: The advanced permissions declared in the Provider tab control who has access to the data provided by the provider (ContentProvider also provides the URI Permission, which will be described later). Slightly different from other components, provider can declare two permissions properties: Android:readpermission and Android:writepermission, which can control who can read the provider data. The latter can control who can write data to the provider. Only the components that write to the provider permission do not read for you, and vice versa. When you first retrieve the provider, the advanced permissions will be detected (if there is no permission, SecurityException will be thrown), where the Contentresolver.query () method requires Android: Readpermission Properties, Contentresolver.insert (), Contentresolver.update (), Contentresolver.delete () These three require Android: Writepermission permissions, the above method throws a SecurityException exception if the appropriate permissions are not set.
Permission to enforce when a broadcast is issued (enforcing Permissions when sending broadcasts)

In addition to the above mentioned advanced permissions for broadcast receiver, you can also pass in a string type of permission in the call Context.sendbroadcast () mode.
Since both broadcasts and receiver can be granted permissions, both permissions need to be intent filtered to match.

URI permission (URI Permissions)

For security reasons, for content provider, you can protect your read and write permissions for their claims. For example, getting a message requires permission, but the given URI points to a picture browser that cannot open the message because the browser is not given permission to open the message.
To solve this problem, you can set the Intent.flag_grant_read_ URI _permission or intent.flag_grant_write_uri_permission field for Intent when you start activity.

Introduction of official Android documents

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.