tools:targetApi="m"有什么用?

What's the usage of tools:targetApi="m"?

我有一个应用程序在 Android-客户端和服务器之间使用 Retrofit,并且在 Android 9+ 中不允许使用 clearText

忽略我在 Manifest 中添加的 android:usesCleartextTraffic="true" 但它警告:tools:ignore="GoogleAppIndexingWarning" 并建议添加 tools:targetApi="m".

有点乱:

我的清单:

...
<application
    android:name=".ApplicationClass"
    android:allowBackup="true"
    android:fullBackupContent="false"
    android:hardwareAccelerated="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="false"
    android:theme="@style/AppTheme.NoActionBar"
    android:usesCleartextTraffic="true"
    tools:ignore="GoogleAppIndexingWarning"
    tools:targetApi="m">
    ...

docs你可以读到:

Indicates that Lint should treat this type as targeting a given API level, no matter what the project target is

这意味着它将 影响注释的那个。

其他带有tools的属性不会受到影响。 tools是命名空间,可以从中获取属性,一个属性不会影响整个命名空间。

通过将 tools:targetApi="m" 添加到元素,您告诉 lint that the element won't be used on API level below 23 (M). See the attribute documentation

This tells the tools that you believe this element (and any children) will be used only on the specified API level or higher. This stops lint from warning you if that element or its attributes are not available on the API level you specify as your minSdkVersion.

在这种特殊情况下,<application> 使用 android:usesCleartextTraffic 属性,该属性从 API 23 开始可用,但应用程序 minSdkVersion 小于 23,因此 lint 会警告您。尽管在这种情况下指定 tools:targetApi 删除了警告,但它不是正确的解决方案,因为如果 minSdkVersion 允许,<application> 可以用于较旧的 API 级别。但是这样的技巧不会造成伤害,因为如果不支持 android:usesCleartextTraffic 将被忽略,请参阅 了解更多详细信息。

一般来说,tools 命名空间怎么样,它包含构建 tools 使用的属性,不会影响运行时行为。有关详细信息,请参阅 the docs

Android Studio supports a variety of XML attributes in the tools namespace that enable design-time features (such as which layout to show in a fragment) or compile-time behaviors (such as which shrinking mode to apply to your XML resources). When you build your app, the build tools remove these attributes so there is no effect on your APK size or runtime behavior.