Error:android:exported needs to be explicitly specified for <activity>. Apps targeting Android 12 and higher are required to specify an explicit value for android:exported when the corresponding component has an intent filter defined. See https://developer.android.com/guide/topics/manifest/activity-element#exported for details.
这个错误是由于 Android 12(API 31)及以上版本 的新规范导致的:当 Activity、Service、Receiver 等组件声明了 <intent-filter> 时,必须显式指定 android:exported 属性(值为 true 或 false),否则编译会失败。
修复方法:为带 <intent-filter> 的组件添加 android:exported
- 步骤 1:定位问题组件
在 AndroidManifest.xml 中找到所有声明了 <intent-filter> 的 <activity> 标签(错误提示已明确是 <activity>)。
- 步骤 2:添加
android:exported属性
根据组件是否需要被 其他应用启动 来设置值:
android:exported="true"允许被其他应用启动(如 launcher 主页面 Activity,通常带有 ACTION_MAIN 和 CATEGORY_LAUNCHER 的 intent-filter)。
android:exported="false"仅允许应用内部启动,不允许被其他应用访问(如普通页面 Activity,即使有 intent-filter 也建议设为 false,除非明确需要外部调用)。
- 示例(修复前后对比)
- 错误写法(缺少 android:exported):
<activity
android:name=".MainActivity">
<!-- 有 intent-filter 但未指定 exported -->
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".ShareActivity">
<!-- 有 intent-filter 但未指定 exported -->
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
</activity>
- 正确写法(添加
android:exported):
<!-- 主页面 Activity(允许被系统 launcher 启动,设为 true) -->
<activity
android:name=".MainActivity"
android:exported="true"> <!-- 显式指定 -->
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- 分享页面 Activity(仅内部使用,设为 false) -->
<activity
android:name=".ShareActivity"
android:exported="false"> <!-- 显式指定 -->
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
</activity>
- 关键说明
仅对有 <intent-filter> 的组件生效:如果组件没有声明 <intent-filter>,android:exported 可以省略(默认值为 false)。
Launcher Activity 必须设为 true:带有 ACTION_MAIN + CATEGORY_LAUNCHER 的 Activity 是应用入口,需要被系统 launcher 启动,因此必须设为 android:exported="true"。
其他组件(Service/Receiver)同理:如果 Service 或 Receiver 声明了<intent-filter> 且 targetSdkVersion ≥ 31,也需要添加 android:exported(例如推送服务的 Receiver)。
- 总结
修复核心就是:给所有带<intent-filter> 的<activity>显式添加 android:exported 属性,根据是否需要被外部访问设置 true 或 false。修改后重新编译即可解决错误。