升级SDK至31后Android Studio报错:需显式指定android:exported
解决Android SDK 31升级后的android:exported报错
问题原因
Android 12(对应API 31)开始强制执行新规则:所有带有<intent-filter>的组件(Activity、Service、BroadcastReceiver)必须显式声明android:exported属性,不能依赖系统默认值。
具体修复步骤
- 打开项目的
AndroidManifest.xml文件 - 遍历所有组件标签:
- 找到所有包含
<intent-filter>的<activity>、<service>、<receiver> - 给每个组件添加
android:exported属性,取值规则:- 若组件需要接收外部应用的Intent(比如启动页Activity,带有
ACTION_MAIN+CATEGORY_LAUNCHER的filter),设为android:exported="true" - 若组件仅用于应用内部,不需要外部访问,设为
android:exported="false"
- 若组件需要接收外部应用的Intent(比如启动页Activity,带有
- 找到所有包含
示例代码
启动页Activity(需要外部可访问)
<activity android:name=".ui.MainActivity" android:exported="true"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity>
内部业务Activity(仅内部访问)
<activity android:name=".ui.InternalPayActivity" android:exported="false"> <intent-filter> <action android:name="com.cima.cima4u1.ACTION_PAY" /> </intent-filter> </activity>
第三方库兼容处理
如果报错来自依赖的第三方库(库的Manifest中组件未声明android:exported),可以在主Manifest中手动覆盖声明:
- 先在Manifest根标签添加tools命名空间:
<manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools">
- 然后针对冲突组件添加声明:
<activity android:name="com.thirdparty.sdk.SomeActivity" android:exported="false" tools:node="merge" />
内容的提问来源于stack exchange,提问作者Fady Sawairas
相关产品推荐
相关产品推荐

