Android advanced three: Intent and IntentFilter matching rules

insert image description here

Intent

Intent is a messaging object that we can use to initiate other application components to perform specific tasks.

We can start the following three components through Intent:

  1. Activity
    • public void startActivity(Intent intent)
  2. Service
    • public ComponentName startService(Intent service)
    • public boolean bindService(Intent service, ServiceConnection conn, int flags)
  3. BroadcastReceiver
    • public void sendBroadcast(Intent intent)
    • public void sendOrderedBroadcast(Intent intent, String receiverPermission)
    • sendStickyBroadcast(Intent intent)

Information carried by Intent

The information carried by the Intent is roughly as follows:

img

  • Component name mComponent
    • The component name can be set using setComponent()the , setClass(), setClassName()or Intent constructor
    • Implicit Intent if no name
  • Action to be performed mAction
    • It can be defined by the system or customized
    • Actions can be specified for an Intent using setAction()the or Intent constructor
  • Data mData
    • Information such as the data to be operated or the type of data
    • To set only the data URI, callsetData()
    • To set only the MIME type, callsetType()
    • If you set both of the above points at the same time, use setDataAndType()both to explicitly set both
  • CategorymCategories
    • Indicates which category the Intent belongs to
    • An Intent can belong to multiple categories, if not declared, it belongs to the default category default
    • You can use the addCategory()specified category
  • Additional data mExtras
    • Intent can carry the data required to complete the requested operation, in the format of key-value pairs
    • Data can be added using various putExtra()methods
    • You can also create a Bundle object that contains all the data, and then insert the Bundle into the Intent putExtras()using
  • flag mFlags
    • The flag bit can instruct the Android system how to start the Activity and how to deal with it after starting
    • Flags can be added using addFlags()the method

Note: 1. The component name should always be specified when starting the Service. Otherwise it is impossible to determine which service will respond to the Intent, and the user cannot see which service has started. 2. To set the URI and MIME types at the same time, do not call setData() and setType(), because they will cancel each other's values. 3. The Intent class will specify multiple EXTRA_* constants for standardized data types. For example, when using ACTION_SEND to create an Intent to send an email, you can use the EXTRA_EMAIL key to specify the "target" recipient and the EXTRA_SUBJECT key to specify the "subject".

Intent type

Intents are divided into two types:

  1. Explicit Intent
  2. Implicit Intent

Explicit Intent is to directly specify the class name of the component to be started. It is generally used to call internal components in the application, so I won't go into details here.

Implicit Intent

Implicit Intent does not directly specify the component to be started, but allows the system to find the matching component for us by specifying the operation to be performed.

For example:

Uri uri = Uri.parse("smsto:18789999999");
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SENDTO);
intent.setData(uri);
intent.putExtra("sms_body", "Hello");
startActivity(intent);

The above code builds an Intent, then sets action, data and extra data for it, and then invokes it startActivity().

The system will then check all installed applications to determine which ones can handle this Intent (in this case: an Intent with ACTION_SENDTOan action and carrying SMS data):

  • If only one app is able to handle it, that app will open immediately and give it the Intent
  • If more than one Activity accepts the Intent, the system displays a dialog that enables the user to choose which application to use

img

In the process of checking whether each Activity can handle the Intent, you need to access the Intent filter (IntentFilter).

Intent filter IntentFilter

We can set an IntentFilter attribute for Activity in AndroidManifest.xml, such as this:

<activity
    android:name=".activity.launchmode.SingleTaskActivity"
    android:alwaysRetainTaskState="true"
    android:label="singleTask"
    android:launchMode="singleTask"
    android:taskAffinity="top.shixinzhang.task2">
    <intent-filter>
        <action android:name="top.shixinzhang.action.test"/>
        <category android:name="top.shixinzhang.category.test"/>
        <data android:mimeType="text/plain"/>
    </intent-filter>
</activity>

Action, category and data can be set in IntentFilter, and each type of information can have more than one.

An Activity can also have multiple IntentFilter, equivalent to a few more filters, the possibility of being filtered is greater.

<activity
    android:name=".activity.launchmode.SingleTaskActivity"
    android:alwaysRetainTaskState="true"
    android:label="singleTask"
    android:launchMode="singleTask"
    android:taskAffinity="top.shixinzhang.task2">
    <intent-filter>
        <action android:name="top.shixinzhang.action.test"/>

        <category android:name="android.intent.category.DEFAULT"/>
        <category android:name="top.shixinzhang.category.test"/>

        <data android:mimeType="text/plain"/>
    </intent-filter>
    <intent-filter>
        <action android:name="android.intent.action.VIEW"/>

        <category android:name="android.intent.category.DEFAULT"/>
        <category android:name="android.intent.category.BROWSABLE"/>

        <data
            android:host="myapp.mycompany.com"
            android:scheme="myapp"/>
    </intent-filter>
</activity>

The above code adds an additional filter to the Activity, which allows it to be used as a browser when loading a specific URI.

We will introduce three matching rules for filtering information respectively.

IntentFilter matching rules

1. Action matching rules

Action can be understood as a component with functions and what operations it can perform. The system provides us with many built-in actions, which of course can also be customized.

There can be multiple actions in an Intent-filter, just like a person has multiple talents.

<intent-filter>
    <action android:name="android.intent.action.EDIT" />
    <action android:name="android.intent.action.VIEW" />
    ...
</intent-filter>

The action in the Intent must have at least one match with the filter to call the component where the filter is located, otherwise it cannot be hit.

Take the above intentFilter as an example, startActivity(intent)the intent must have at android.intent.action.EDITleast android.intent.action.VIEWone action in and , and then there can be unmatched actions.

Note: Case sensitive.

List some commonly used system built-in actions as follows:

action name effect Remark
android.intent.action.MAIN Identify Activity as the start of a program
android.intent.action.CALL Call the specified phone number
android.intent.action.DIAL dial panel
andriod.intent.action.ALL_APPS list all applications
android.intent.action.ANSWER handle incoming calls
android.intent.action.VIEW display user data Generic, can be phone, browser, etc.
android.intent.action.SENDTO Send a message It can be SMS, MMS, email, etc.
android.intent.action.EDIT Editable access to given data
android.intent.action.PICK select information from list Generally used to select contacts or pictures, etc.
android.intent.action.CHOOSER Show an Activity picker For example, where do common choices share

Note: 1.android.intent.action.VIEW opens the corresponding Activity according to the data type. For example, tel:13400010001 will open the dialer, http://www.baidu.com will open the browser, etc. 2.android.intent. action.SENDTO For more actions, please refer to the official document: https://developer.android.com/reference/android/content/Intent.html

2. Category matching rules

category is a category, and like action, a filter can contain multiple categories:

<intent-filter>
    <category android:name="android.intent.category.DEFAULT" />
    <category android:name="android.intent.category.BROWSABLE" />
    ...
</intent-filter>

Different from the action matching rule (only one match is required), when category matches, the category in your Intent must exactly match the one declared in the filter.

Take the above intentFilter as an example, startActivity(intent)the category of the intent in it cannot android.intent.category.DEFAULTbe android.intent.category.BROWSABLEother than and .

Note: Android automatically passes android.intent.category.DEFAULTthe class to all implicit intents ofstartActivity() and . startActivityForResult()Therefore, even if no classification is passed startActivity(intent)in , the above filter can be hit.

The system provides us with many categories, and we can also customize them.

Note: Don't forget to add it in AndroidManifest.xml when customizing the category android.intent.category.DEFAULT, because the reason mentioned above is that the system will add this category startActivity()for .

The following are some common categories provided by the system (picture transferred from: http://www.2cto.com/kf/201603/492421.html):

img

3. Data matching rules

data indicates the data format and type that the component can support.

Similarly, a filter can also have multiple data:

<intent-filter>
    <data android:mimeType="video/mpeg" android:scheme="http" ... />
    <data android:mimeType="audio/mpeg" android:scheme="http" ... />
    ...
</intent-filter>

A data consists of two parts:

  • mimeType
  • scheme

mimeType refers to the supported data types and formats, common ones are:

  • text/plain
  • image/jpeg
  • video/*
  • audio/*

The data type in front of the / sign is followed by the specific format.

scheme is a common URI format:

<scheme>://<host>:<port>/<path>

The specific parts and their importance are as follows:

  • scheme: protocol type
    • Most importantly, the protocol type determines how to access data, such as local or network
  • host: host
    • The second important thing is that the host address determines the specific ip
  • port: port
    • The third important thing is that a host may have multiple network card ports, and the specific
  • path: specific path
    • The last level, indicating the folder path to be accessed

for example:

http://www.baidu.com:80/search/info
file://emulator/0/sdcard/shixinzhang

In the intent-filter, the scheme must be declared from the front to the back, gradually narrowing the range.

You can only declare a protocol, which means that you can process all data under this protocol; you can also only declare the host address, which means that you can process all data under this host using this protocol.

scheme and mimeType form a data. The data matching rule is: the data in the intent can match at least one of the filters .

That is to say:

  • If the intent-filter only declares scheme, then your intent must contain only scheme and match at least one scheme in intent-filter
  • If the intent-filter only declares the mimeType, then in addition to the type being consistent with the intent-filter in your intent, you also need to include contentor filescheme, because the intent-filter includes these two schemes by default
  • If the intent-filter declares multiple schemes and mimeTypes at the same time, your intent must match at least one of them

Note the intent-filter's default contentor filescheme, which means that the default component can get local data from a file or content provider.

For example, the following intent-filter indicates that the component can obtain and display image data from the content provider:

<intent-filter>
    <data android:mimeType="image/*" />
    ...
</intent-filter>

Another common configuration is that the scheme only declares the protocol, and also declares the filter of the data type.

For example, the following elements indicate to Android that the component can retrieve video data from the network to perform an action:

<intent-filter>
    <data android:scheme="http" android:mimeType="video/*" />
    ...
</intent-filter>

Summarize filter rules

If we compare a component to an Android programmer, we need three conditions to filter out the one we want:

  1. What kind of development are you good at, UI, network, audio and video? (corresponding action)
    • At least one of the requirements must be met
  2. What kind of programmer is it, curious and self-driven? (corresponding to category)
    • It must be fully consistent with the requirements
  3. What tools are used for development, AS, Eclipse, Notepad? (corresponding to data)
    • At least one of the requirements must be met

Notice

If there is no current device that matches the implicit Intent you sent to startActivity(), the call will fail and the app will crash.

So we need to call resolveActivity() on the Intent object:

  • If the result is non-null, at least one app is capable of handling the Intent and it is safe to call startActivity()
  • If the result is empty, the Intent should not be used
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, textMessage);
sendIntent.setType("text/plain");

//验证当前 Intent 是否可以被处理
if (sendIntent.resolveActivity(getPackageManager()) != null) {
    
    
    startActivity(sendIntent);
}

epilogue

More Android advanced materials can be scanned for free!

Table of contents

img

1. Essential Skills for Architects

1. In-depth understanding of Java generics 2. Annotations in simple terms 3. Concurrent programming 4. Data transmission and serialization 5. Java virtual machine principles 6. Efficient IO...img

2. Source Code Analysis of Top 100 Android Frameworks

1.Retrofit 2.0 source code analysis2.Okhttp3 source code analysis3.ButterKnife source code analysis4.MPAndroidChart source code analysis5.Glide source code analysis6.Leakcanary source code analysis7.Universal-lmage-Loader source code analysis8.EventBus 3.0 source code analysis9.zxing source code Analysis 10. Picasso source code analysis 11. LottieAndroid use detailed explanation and source code analysis 12. Fresco source code analysis - picture loading process

3. Actual analysis of Android performance optimization

1. Tencent Bugly: A Little Understanding of String Matching Algorithms

2. iQiyi: Android APP crash capture solution - xCrash

3. Bytedance: In-depth understanding of one of the Gradle frameworks: Plugin, Extension, buildSrc

4. Baidu APP technology: Android H5 first screen optimization practice

5. Analysis of Alipay client architecture: Android client startup speed optimization "garbage collection"

6. Ctrip: From the Zhixing Android project to see the practice of component architecture

7. Netease news construction optimization: how to make your construction speed "like lightning"?

4. Advanced kotlin strengthens actual combat

1. Kotlin Introductory Tutorial 2. Kotlin Practical Pit Avoidance Guide 3. Project Combat "Kotlin Jetpack Combat"

​ ● Start with a demo that worships a great god

​ ● What is the experience of writing Gradle scripts in Kotlin?

​ ● The Triple Realm of Kotlin Programming

​ ● Kotlin higher order functions

​ ● Kotlin Generics

​ ● Kotlin Extensions

​ ● Kotlin delegates

​ ● Coroutine "unknown" debugging skills

​ ● Graphical coroutine: suspendimg

5. Advanced decryption of Android advanced UI open source framework

1. Use of SmartRefreshLayout 2. Android PullToRefresh control source code analysis 3. Basic usage of Android-PullToRefresh pull-down refresh library 4. LoadSir - efficient and easy-to-use loading feedback page management framework 5. Android general LoadingView loading framework detailed explanation 6. MPAndroidChart implements LineChart ( Line chart) 7. Hellocharts-android usage guide 8. SmartTable usage guide 9. Open source project android-uitableview introduction 10. ExcelPanel usage guide 11. Android open source project SlidingMenu in-depth analysis 12. MaterialDrawer usage guideimg

Guess you like

Origin blog.csdn.net/Misdirection_XG/article/details/130828229