Android API 30及更高版本网络权限设置

目录

  • 一、网络权限设置
  • 二、配置步骤
    • [1、在 AndroidManifest.xml 文件中添加网络权限声明](#1、在 AndroidManifest.xml 文件中添加网络权限声明)
    • [2、在 AndroidManifest.xml 文件中的 application 节点下配置网络安全策略](#2、在 AndroidManifest.xml 文件中的 application 节点下配置网络安全策略)

一、网络权限设置

在 Android API 30 及更高版本中,Google 引入了更严格的网络安全策略,其中包括对应用程序的网络访问权限进行了更多的限制。如果您的应用程序需要进行网络访问:

  • 需要确保在清单文件(AndroidManifest.xml)中正确声明网络权限;

  • 并且在运行时请求网络权限。

二、配置步骤

1、在 AndroidManifest.xml 文件中添加网络权限声明

AndroidManifest.xml 文件中添加网络权限声明:

xml 复制代码
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.xxx" >
    
	<uses-permission android:name="android.permission.INTERNET" />

	...
</manifest>

2、在 AndroidManifest.xml 文件中的 application 节点下配置网络安全策略

AndroidManifest.xml 文件中的 application 节点下配置网络安全策略:

xml 复制代码
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.xxx" >
    
	<application 
		android:usesCleartextTraffic="true"
    	...>
    	...
	</application>

	...
</manifest>

usesCleartextTraffic 是清单文件(AndroidManifest.xml)中的配置项,用于指定应用程序是否允许明文流量(非加密流量)的网络请求,明文流量是指未经加密的网络流量,可能存在安全风险。

  • true:应用程序可以发送明文流量的网络请求;

  • false :应用程序将被限制只能发送加密流量的请求(即 HTTPS 请求)。

注意事项:

  • 开启明文流量可能会带来安全风险,因为未经加密的网络通信可能会被中间人攻击截取和窃听。
  • Google 在 Android 9(API 30)及之后的版本中默认禁止应用程序发送明文流量的网络请求,因此如果您的应用程序需要与不支持 HTTPS 的服务器通信,您可能需要显式地配置 android:usesCleartextTraffic="true"。

除了 usesCleartextTraffic 配置项外。还可以在网络安全配置文件(res/xml/network_security_config.xml)中配置网络安全策略,然后在清单文件中引用该配置文件:

xml 复制代码
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.xxx" >
    
	<application 
		android:networkSecurityConfig="@xml/network_security_config"
    	...>
    	...
	</application>

	...
</manifest>

network_security_config.xml

xml 复制代码
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">com.xxx</domain>
    </domain-config>
</network-security-config>

配置文件允许 com.xxx 及其 所有子域名 的明文流量(非加密流量),通过使用 android:networkSecurityConfig 配置项,您可以灵活地定义应用程序的网络安全策略,以确保应用程序与网络资源之间的安全通信。

相关推荐
砖厂小工4 分钟前
用 GLM + OpenClaw 打造你的 AI PR Review Agent — 让龙虾帮你审代码
android·github
张拭心42 分钟前
春节后,有些公司明确要求 AI 经验了
android·前端·人工智能
张拭心1 小时前
Android 17 来了!新特性介绍与适配建议
android·前端
Kapaseker3 小时前
Compose 进阶—巧用 GraphicsLayer
android·kotlin
黄林晴4 小时前
Android17 为什么重写 MessageQueue
android
阿巴斯甜1 天前
Android 报错:Zip file '/Users/lyy/develop/repoAndroidLapp/l-app-android-ble/app/bu
android
Kapaseker1 天前
实战 Compose 中的 IntrinsicSize
android·kotlin
xq95271 天前
Andorid Google 登录接入文档
android
黄林晴1 天前
告别 Modifier 地狱,Compose 样式系统要变天了
android·android jetpack
冬奇Lab2 天前
Android触摸事件分发、手势识别与输入优化实战
android·源码阅读