如何修复错误: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

2021年11月29日19:50:13 发表评论 3,730 次浏览

了解导致此异常的原因以及如何在 Android Studio 中解决它。

如何修复错误: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
Apps targeting Android 12 and higher are required解决办法

当我尝试创建一个沙箱项目来试验 Android 时,将 Android 样板启动到模拟器引发了上述 Manifest 合并失败:针对 Android 12 及更高版本的应用程序需要指定一个明确的值,以便android:exported相应组件具有意图过滤器定义。

如何修复错误Apps targeting Android 12 and higher are required?经过一番研究,我找到了解决方案,但是不清楚为什么这是必要的,以及为什么在 Android Studio 中应该从一开始就自动工作的新项目会出现异常。在本文中,我将与您分享此异常的解释和解决方案。

将 android:exported 属性添加到意图和接收器

Apps targeting Android 12 and higher are required解决办法:正如在关于Android 12行为变化的官方注释中提到的,特别是安全组件,如果你的应用针对Android 12并包含使用意图过滤器的活动、服务或广播接收器,你必须为这些应用组件明确声明Android:exported属性。

此属性 设置活动是否可以由其他应用程序的组件启动:

  • 如果是“ true”,则任何应用都可以访问该活动,并且可以通过其确切的类名启动。
  • 如果为“ false”,则活动只能由相同应用程序的组件、具有相同用户 ID 的应用程序或特权系统组件启动。这是没有意图过滤器时的默认值。

如果你的应用程序中有一个活动包含意图过滤器,将此元素设置为“true”以允许其他应用程序启动它。例如,如果活动是应用程序的主要活动,并包含类别"android.intent.category.LAUNCHER"。如果该元素被设置为“false”,并且应用程序试图启动该活动,系统会抛出一个ActivityNotFoundException异常。

此属性不是限制活动暴露于其他应用程序的唯一方法。权限还可用于限制可以调用活动的外部实体(请参阅 permission 属性):

<!-- Either set it to true -->
<activity android:name=".MainActivity" android:exported="true">
</activity>

<!-- Either set it to false -->
<activity android:name=".MainActivity" android:exported="false">
</activity>

修复错误Apps targeting Android 12 and higher are required - 根据你的需要,你的 Android 清单中的此修复程序将如下所示:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.sandbox">
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.Sandbox">

        <!-- 
            Solution: add the android:exported attribute and set it to true or false
            to every activity or receiver that you may have
        -->
        <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>
    </application>
</manifest>

快乐编码❤️!

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: