Can't establish a new connection with aSmack 4.0.2

前端 未结 2 421
梦毁少年i
梦毁少年i 2021-01-23 02:08

I\'m learning Android programming and I\'ve been trying to figure this out for a couple days now. I\'m writing and Android app that is supposed to connect to XMPP server. I\'m g

相关标签:
2条回答
  • 2021-01-23 02:16

    I had the same problem, but found solution here: SImple Asmack program not working

    The solution is to put connection code into separate thread.

    public static final String HOST = "208.68.163.218"; //write your host name
    public static final int PORT = 5222;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        connect();
    }
    
    public void connect() {
        Thread t = new Thread(new Runnable() {
    
            @Override
            public void run() {
                Context context = getApplicationContext();
                SmackAndroid.init(context);
                ConnectionConfiguration ConnectionConfiguration = new ConnectionConfiguration(HOST, PORT);
                ConnectionConfiguration.setDebuggerEnabled(true);
                XMPPConnection connection = new XMPPTCPConnection(ConnectionConfiguration);     
    
                try {
                    connection.connect();
                } catch (ConnectionException e) {
                    e.printStackTrace();
                } catch (SmackException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (XMPPException e) {
                    e.printStackTrace();
                }
            }
        });
        t.start();
    }
    
    0 讨论(0)
  • 2021-01-23 02:20

    I got this exception even when connection part of code was in a new thread. It was caused by not turning on my internet connection (via wifi or mobile data network) on my physical android device (i use it connected via usb cable to my laptop) (dont know if works on emulator without connection, didnt test). I found this exception thrown by method deep in api structure:

    connect failed: ENETUNREACH (Network is unreachable)
    

    This exception was not shown in LogCat, but finally after reading Flow's comment on this question i found it in HostAddress list.

    Maybe this saves someone from desperately looking for what's wrong in his code like me.

    0 讨论(0)
提交回复
热议问题