Recently I wanted to get a grip on programming for Android. While I was getting through this tutorial: https://dev.to/medaymentn/creating-a-realtime-chat-app-with-android--nodejs-and-socketio-4o55 it turned out that for Android 9 (API level 28) I couldn't connect to my local nodejs server from android device emulator. If I just change all build dependencies to use lower API levels (<=27) it connects correctly. From what i've read on the behavior changes for Android 9 I don't really know what could cause such a thing. Here is the code that is critical i think.
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();
}
}
}
Installing the DependenciesNow we can use Socket.IO on Android!
Socket.io, and WebSockets in general, require an http server for the initial upgrade handshake. So even if you don't supply Socket.io with an http server it will create one for you.
You can check the socket.io version in node_modules->socket.io->package. json and there will be "version": "your version of socket.io".
Simply can be done by adding following in your manifest:
android:usesCleartextTraffic="true"
Starting with Android 9.0 (API level 28), cleartext support is disabled by default.You might need to enable for your domain url. More info refer this https://developer.android.com/training/articles/security-config#CleartextTrafficPermitted
Create file 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>
You need give reference of this file in 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>
Go to the AndroidManifest.xml in the application tag add this
android:usesCleartextTraffic="true"
like this
<application
android:usesCleartextTraffic="true"
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme"
tools:targetApi="m">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With