Zmirlacz
Zmirlacz

Reputation: 65

Socket.io not working on Android 9 (API level 28)

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();

        }
    }
}

Upvotes: 6

Views: 8370

Answers (3)

javad asghari
javad asghari

Reputation: 129

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">

Upvotes: 1

Bilal Ahmed
Bilal Ahmed

Reputation: 358

Simply can be done by adding following in your manifest:

android:usesCleartextTraffic="true"

Upvotes: 16

Ramesh Yankati
Ramesh Yankati

Reputation: 1217

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>

Upvotes: 11

Related Questions