显式Intent与隐式Intent

ChatGPT 说:

在 Android 中,Intent(意图) 是组件(Activity、Service、BroadcastReceiver)之间进行通信的机制。Intent 主要分为两种类型:

1. 显式 Intent(Explicit Intent)

显式 Intent 直接指定目标组件(Activity、Service)的 类名,用于在 应用内部 启动组件。

示例

1
2
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);

特点:

  • 适用于应用内部 组件间的交互,比如从 MainActivity 跳转到 SecondActivity
  • 指定目标类名,不会让系统去匹配 intent-filter
  • 性能更高,因为不需要系统查找匹配的组件。

2. 隐式 Intent(Implicit Intent)

隐式 Intent 不指定 目标组件的类名,而是使用 动作(Action)、类别(Category)、数据(Data) 让系统找到符合条件的组件。

示例

打开网页:

1
2
3
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("https://www.example.com"));
startActivity(intent);

拨打电话:

1
2
3
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:123456789"));
startActivity(intent);

特点:

  • 适用于调用其他应用的功能,例如打开浏览器、拨号、分享文本等。

  • 需要在 AndroidManifest.xml 中声明 intent-filter,例如:

    1
    2
    3
    4
    5
    6
    7
    <activity android:name=".ThirdActivity">
    <intent-filter>
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.DEFAULT" />
    <data android:scheme="https" />
    </intent-filter>
    </activity>
  • 系统会自动匹配 适合的应用来处理这个 Intent。


对比总结

特性 显式 Intent 隐式 Intent
目标组件 明确指定 类名,如 SecondActivity.class 不指定 类名,使用 Action + Data 让系统匹配
适用场景 应用内部跳转,如 ActivityA → ActivityB 调用系统/其他应用功能,如打开网页、拨打电话
匹配方式 直接找到组件 并启动 系统匹配 intent-filter 找到合适的组件
性能 更快,因为不需要匹配 稍慢,需要查询可能的匹配组件