I spent more 1 day to try to connect from Android App to SocketIO but can not. Although I can access to link local by browser in laptop and my physic device (used <uses-permission android:name="android.permission.INTERNET"/>
), I can not connect to Socket by Android App after each times I start application.
This is dependencies I added in gradle
:
dependencies{
implementation 'androidx.appcompat:appcompat:1.3.1'
implementation 'com.google.android.material:material:1.4.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.2'
testImplementation 'junit:junit:4. '
implementation ('io.socket:socket.io-client:2.0.0') {
exclude group: 'org.json', module: 'json'
}
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
This is my code in MainActivity.java
:
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import io.socket.client.IO;
import io.socket.client.Socket;
import java.net.URISyntaxException;
public class MainActivity extends AppCompatActivity {
private Socket mSocket;
{
try {
mSocket = IO.socket("http://192.168.1.2:3000/");
} catch (URISyntaxException e) {
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSocket.connect();
}
}
What should I do?
CodePudding user response:
You are using a http url for connection On newer android versions http traffic is blocked by default by system
To allow http, edit your AndroidManifest.xml and add android:usesCleartextTraffic="true" to application tag like this
<application android:usesCleartextTraffic="true">
</application>
▲ this answer if it helps!