无法连接到 Android 上的 React Native 开发服务器

问题描述:

当我运行 react-native run-android 时,它给了我以下错误:

When I run react-native run-android, it gives me the following error:

无法连接到开发服务器

  • 包服务器正在运行,我可以直接从浏览器访问它在我的移动设备上.
  • 我的 Android 设备已连接到计算机并已启用调试(我使用 adb devices 命令检查).
  • 我的 Android 版本是 4.4.4,所以我不能使用 adb reverse 命令.
  • 我已经在开发设置中设置了 ID 地址和端口.
  • USB 调试已开启.
  • 我使用的是 Windows 7.
  • Package server is running and I can access it directly from browser on my mobile device.
  • My Android device is connected to computer and has debugging enabled (I checked using adb devices command).
  • My Android version is 4.4.4 so I cannot use adb reverse command.
  • I have set the ID address and port in Dev setting.
  • USB debug is on.
  • I use Windows 7.

如何修复这个错误?

从 Android 9.0(API 级别 28)开始,明文支持是默认禁用.我们可以使用 android:usesCleartextTraffic="true" 这会起作用,但这不是推荐的解决方案.对于永久和推荐的解决方案如下:

第一步:在android文件夹中创建一个文件app/src/debug/res/xml/network_security_config.xml

Step 1 : create a file in android folder app/src/debug/res/xml/network_security_config.xml

第 2 步:将其添加到 network_security_config.xml

Step 2 : add this to network_security_config.xml

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
  <!-- deny cleartext traffic for React Native packager ips in release -->
  <domain-config cleartextTrafficPermitted="true">
   <domain includeSubdomains="true">localhost</domain>
   <domain includeSubdomains="true">10.0.2.2</domain>
   <domain includeSubdomains="true">10.0.3.2</domain>
  </domain-config>
</network-security-config>

第 3 步:将配置应用到您的 AndroidManifest.xml

Step 3 : Apply the config to your AndroidManifest.xml

<application
 android:networkSecurityConfig="@xml/network_security_config">
</application>