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

最近我想掌握 Android 编程。当我完成本教程时:https ://dev.to/medaymentn/creating-a-realtime-chat-app-with-android--nodejs-and-socketio-4o55原来对于 Android 9(API 级别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();


        }

    }

}


Qyouu
浏览 259回答 3
3回答

米琪卡哇伊

只需在清单中添加以下内容即可完成:android:usesCleartextTraffic="true"

人到中年有点甜

从 Android 9.0(API 级别 28)开始,明文支持默认禁用。您可能需要为您的域 url 启用。更多信息请参阅此 https://developer.android.com/training/articles/security-config#CleartextTrafficPermitted创建文件 res/xml/network_security_config.xml -&nbsp;<?xml version="1.0" encoding="utf-8"?>&nbsp; <network-security-config>&nbsp; &nbsp; <domain-config cleartextTrafficPermitted="true">&nbsp; &nbsp; <domain includeSubdomains="true">Your URL</domain>&nbsp; </domain-config>&nbsp;</network-security-config>您需要在 android Manifest 中提供此文件的参考&nbsp; &nbsp; &nbsp;<?xml version="1.0" encoding="utf-8"?>&nbsp; &nbsp; &nbsp; <manifest ...>&nbsp; &nbsp; &nbsp; &nbsp; <uses-permission android:name="android.permission.INTERNET" />&nbsp; &nbsp; &nbsp; &nbsp;<application&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;android:networkSecurityConfig="@xml/network_security_config"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ...>&nbsp; &nbsp; &nbsp; </application>

慕桂英4014372

转到应用程序标记中的 AndroidManifest.xml 添加此android:usesCleartextTraffic="true"像这样<application&nbsp; &nbsp; &nbsp; &nbsp; android:usesCleartextTraffic="true"&nbsp; &nbsp; &nbsp; &nbsp; android:allowBackup="true"&nbsp; &nbsp; &nbsp; &nbsp; android:icon="@drawable/ic_launcher"&nbsp; &nbsp; &nbsp; &nbsp; android:label="@string/app_name"&nbsp; &nbsp; &nbsp; &nbsp; android:theme="@style/AppTheme"&nbsp; &nbsp; &nbsp; &nbsp; tools:targetApi="m">
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java