【问题标题】:Socket.io not working on Android 9 (API level 28)Socket.io 无法在 Android 9(API 级别 28)上运行
【发布时间】:2019-04-16 12:23:33
【问题描述】:

最近我想掌握 Android 编程。当我完成本教程时:https://dev.to/medaymentn/creating-a-realtime-chat-app-with-android--nodejs-and-socketio-4o55 事实证明,对于 Android 9(API 级别 28),我无法从 android 设备模拟器连接到我的本地 nodejs 服务器。如果我只是更改所有构建依赖项以使用较低的 API 级别(

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

        }
    }
}

【问题讨论】:

    标签: java android socket.io


    【解决方案1】:

    只需在清单中添加以下内容即可:

    android:usesCleartextTraffic="true"

    【讨论】:

    • 就是这样!谢谢!
    • 没有什么比这些情况更能阻止开发了。
    • 真的救了我的命
    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 2020-04-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-16
        • 1970-01-01
        • 2014-12-01
        相关资源
        最近更新 更多