Socket.io无法在Android 9(API级别28)上运行

Zmi*_*acz 5 java android socket.io

最近,我想掌握Android编程的知识。当我阅读本教程时:https : //dev.to/medaymentn/creating-a-realtime-chat-app-with-android--nodejs-and-socketio-4o55,事实证明,对于Android 9(API级别28)我无法从android设备模拟器连接到本地Node.js服务器。如果我仅更改所有构建依赖项以使用较低的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();

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 10

从Android 9.0(API级别28)开始,默认情况下会禁用明文支持。您可能需要启用域网址。更多信息请参考 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>
Run Code Online (Sandbox Code Playgroud)

您需要在android Manifest中提供此文件的参考

     <?xml version="1.0" encoding="utf-8"?>
      <manifest ...>
        <uses-permission android:name="android.permission.INTERNET" />
       <application
         android:networkSecurityConfig="@xml/network_security_config"
          ...>
      </application>
Run Code Online (Sandbox Code Playgroud)


Bil*_*med 9

只需在清单中添加以下内容即可:

android:usesCleartextTraffic="true"