![](/img/trans.png)
[英]Android-ProviderTestCase2 with API Level 28 not working
[英]Socket.io not working on Android 9 (API level 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();
}
}
}
只需在清单中添加以下内容即可完成:
android:usesCleartextTraffic="true"
从 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 Manifest 中引用此文件
<?xml version="1.0" encoding="utf-8"?>
<manifest ...>
<uses-permission android:name="android.permission.INTERNET" />
<application
android:networkSecurityConfig="@xml/network_security_config"
...>
</application>
转到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">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.