Socket.io在Android 9 (API level 28)上无法正常工作。

6

最近我想学习Android编程。在学习此教程时,发现在Android 9 (API level 28)上无法从Android模拟器连接到本地的nodejs服务器。如果将所有构建依赖项更改为使用较低的API级别(<=27),则可以成功连接。根据我所了解的Android 9的行为变化,我不知道可能会导致这种情况。以下是我认为关键的代码:

public class ChatBoxActivity extends AppCompatActivity {

    //declare socket object
    private Socket socket;

    public String Nickname;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat_box);

        // get the nickame of the user
        Nickname = (String) getIntent().getExtras().getString(MainActivity.NICKNAME);
        //connect you socket client to the server
        try {
            socket = IO.socket("http://192.168.2.106:3000");
            socket.connect();
            socket.emit("join", Nickname);
        } catch (URISyntaxException e) {
            e.printStackTrace();

        }
    }
}
3个回答

16

只需在您的清单文件中添加以下内容即可:

android:usesCleartextTraffic="true"


该代码将允许您的应用程序通过明文流量进行网络连接。

这就是了!谢谢! - Werner Schäffer
没有什么比这些情况更能阻碍开发了。 - Diego Alves
字面上拯救了我的生命 - Jahson kyalo

11
从Android 9.0(API级别28)开始,默认情况下禁用明文支持。您可能需要为域名url启用它。 更多信息请参见 https://developer.android.com/training/articles/security-config#CleartextTrafficPermitted 创建文件res/xml/network_security_config.xml -
 <?xml version="1.0" encoding="utf-8"?>
  <network-security-config>
    <domain-config cleartextTrafficPermitted="true">
    <domain includeSubdomains="true">Your URL</domain>
  </domain-config>
 </network-security-config>

你需要在Android清单文件中引用此文件。

     <?xml version="1.0" encoding="utf-8"?>
      <manifest ...>
        <uses-permission android:name="android.permission.INTERNET" />
       <application
         android:networkSecurityConfig="@xml/network_security_config"
          ...>
      </application>


1

前往AndroidManifest.xml,在应用程序标签中添加以下内容

android:usesCleartextTraffic="true"

像这样
<application
        android:usesCleartextTraffic="true"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme"
        tools:targetApi="m">

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接