XMPP 通信之Asmack(二) 登陆

 /**
     * 登陆方法
     * 这部分相对简单,登陆之前判断XMPP是否连接,登陆成功将用户状态改为在线
     * @param account
     * @param password
     * @return
     */
    public static boolean login(Context context, GeneralChatRoomHandler mhandler, CharRoomCore successful, String account, String password) {
        ChatRoomInfo.account = account;
        try {
            LogUtil.w("login is error");
            if (XmppTool.getInstance().getConnection(context, mhandler, successful) == null) {// 如果网络没有连接上
                LogUtil.i("没有网络i");
                return false;
            }
            /** 登录
             *  SASL的认证方式 在客户端要声明,客户端必须支持PLAIN模式--用户名和密码通过网络传输,不安全
             *  关于SASL认证,有兴趣的可以查询下其他资料
             * */
            SASLAuthentication.supportSASLMechanism("PLAIN", 0);
            XmppTool.getInstance().getConnection(context, mhandler, successful).login(account, password);
            // 设置登录状态:在线
            Presence presence = new Presence(Presence.Type.available);
            XmppTool.getInstance().getConnection(context, mhandler, successful).sendPacket(presence);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            LogUtil.w("login close");
            //登录失败记得将连接关闭
            XmppTool.getInstance().closeConnection();
        }
        return false;
    }

  登陆部分上面的注释已经写的很清楚,但我也提一点,登陆操作是异步的,实际使用还需要将其放到线程里;

 关于如何建立连接请参考:http://www.cnblogs.com/ZhangXiangQian/p/5254840.html

原文地址:https://www.cnblogs.com/ZhangXiangQian/p/5260692.html