ConnectionListener方法不显示Toast(Smack Library)

时间:2016-02-26 11:23:06

标签: android xmpp smack

我是Xmpp的新手并且现在很困惑。当我向ConnectionListener接口方法添加新的Toast时,Toast不会显示在应用程序中。

我的代码:

  conn2.addConnectionListener(new ConnectionListener()
    {
        @Override
        public void connected(XMPPConnection xmppConnection)
        {
            Toast.makeText(getApplicationContext(), "connected", Toast.LENGTH_LONG).show();
        }

        @Override
        public void authenticated(XMPPConnection xmppConnection, boolean b)
        {
            Toast.makeText(getApplicationContext(), "authenticated", Toast.LENGTH_LONG).show();
        }

        @Override
        public void connectionClosed()
        {
            Toast.makeText(getApplicationContext(), "conclose", Toast.LENGTH_LONG).show();
        }

        @Override
        public void connectionClosedOnError(Exception e)
        {
            Toast.makeText(getApplicationContext(), "conclose", Toast.LENGTH_LONG).show();
        }

        @Override
        public void reconnectionSuccessful()
        {
            Toast.makeText(getApplicationContext(), "reconnect", Toast.LENGTH_LONG).show();
        }

        @Override
        public void reconnectingIn(int i)
        {
            Toast.makeText(getApplicationContext(), "reconnect", Toast.LENGTH_LONG).show();
        }

        @Override
        public void reconnectionFailed(Exception e)
        {

        }
    });

这就是我期望代码做的事情:无论何时建立连接,屏幕上都会出现一个新的Toast,表示"已连接"。我做错了什么。这是错误的方式这样做?

2 个答案:

答案 0 :(得分:2)

你必须使用处理程序,但应该这样:

new Handler(Looper.getMainLooper())

答案 1 :(得分:0)

您需要创建一个处理程序才能显示Toast消息。

例如:

    private Handler mHandler = new Handler();

这会创建处理程序对象。在此任何连接侦听器代码之后,添加以下内容:

例如,我在reconnectionSuccessful()方法中显示toast:

    @Override
    public void reconnectionSuccessful() {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(this, "Yay, Reconnect Success!",Toast.LENGTH_LONG).show();
            }
        });
    }