使用Android+smack4.1.4+openfire进行IM开发

从smack4.1开始,smack就已经原生支持Android了(再也不需要用asmack了!),然而发现目前国内对最新的smack尤其是4.1之后的介绍比较少。在自己一番折腾后终于测试成功,在这里分享出自己的一些经验,希望初学者能少走弯路,有不足之处还请指正。

程序运行界面:


1.首先是对于openfire环境的搭建,这方面网上示例很多,就不赘述了。

2.相关jar包的下载:

1)smack4.1.4.zip

下载地址:http://download.igniterealtime.org/smack/smack_4_1_4.zip

2)jndi.rar

包含两个jar包:fscontext.jar      providerutil.jar

3)minidns-0.1.3.jar

jxmpp-util-cache-0.4.0-alpha1.jar

jxmpp-core-0.4.1.jar

2和3的jar包在我的示例代码中可以找到,网上也是很容易找到的,就不贴地址了。

3.客户端开发:

新建一个module命名为openfiretest,分别在libs下导入这几个jar包(记得要添加到build path):


activity_main.xml:





    
    
        


新建item_child.xml和item_parent.xml

item_child.xml



    
    



 
  item_parent.xml 
  



    
    



 
  连接服务器: 
  

 protected boolean conServer() {
        XMPPTCPConnectionConfiguration.Builder config = XMPPTCPConnectionConfiguration.builder();
        config.setHost("10.0.2.2");              //设置openfire主机IP
        config.setServiceName("pc-piyell");         //设置openfire服务器名称
        config.setPort(5222);                   //设置端口号:默认5222
        config.setUsernameAndPassword(et_jid.getText(), "123456");    //设置用户名与密码
        config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);      //禁用SSL连接
        config.setSendPresence(true);
        config.setDebuggerEnabled(true);
        con = new XMPPTCPConnection(config.build());
        try {
            con.connect();
            //Log.e("TAG", connect.getUser());
        } catch (Exception e) {
            Log.e("TAG", "connect failed!" + e.toString());
            e.printStackTrace();
            return false;
        }
        return true;


    }
登录部分:

 public void login(View view) {

        Roster roster = Roster.getInstanceFor(con);


        try {
            con.login();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.e("TAG", "login sucess!!");
        setPresence(1);

//         设置聊天监听器,监听聊天消息
        ChatManager chatm = ChatManager.getInstanceFor(con);
        chatm.addChatListener(new ChatManagerListener() {
            @Override
            public void chatCreated(Chat chat, boolean b) {
                if (!b) {           //不是本地创建的会话
                    chat.addMessageListener(new mChatMsgListener());
                }
            }
        });

        /**
         *  添加一个分组—— friends
         */
        Set entries = roster.getEntries();
        RosterGroup friends = roster.createGroup("friends");
        try {
            for (RosterEntry entry : entries) {
                friends.addEntry(entry);   /**添加所有好友到friends分组*/

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        Log.e("tag", "------群组数=======" + roster.getGroupCount());
        Collection groups = roster.getGroups();
        parentList = new ArrayList<>();

        map = new HashMap<>();
        for (RosterGroup group : groups) {
            parentList.add(group.getName());
            List childList = new ArrayList<>();
            for (RosterEntry rosterEntry : entries) {
                childList.add(rosterEntry.getUser().toString().split("@")[0]);
                Log.e("tag", "------Entry=======" + rosterEntry.getUser().toString());
            }
            map.put(group.getName(), childList);
            Log.e("tag", "childlist--------" + map.get(parentList.get(0)).toString());
//            childList.clear();
        }
        listview.setAdapter(new MyAdapter());


        roster.addRosterListener(new RosterListener() {
            @Override
            public void entriesAdded(Collection collection) {}

            @Override
            public void entriesUpdated(Collection collection) { }

            @Override
            public void entriesDeleted(Collection collection) {}

            @Override
            public void presenceChanged(Presence presence) {
                Log.e("TAG", presence.getFrom() + presence);
            }
        });

    }

发送消息:

public void sendMsg(View view) {
        ChatManager chatm = ChatManager.getInstanceFor(con);
        Chat chat = chatm.createChat("piyell@pc-piyell", new ChatMessageListener() {        //创建与piyell的会话
            public void processMessage(Chat chat, Message message) {
                System.out.println("Received message: " + message);
            }
        });
        try {
            /**
             * 发送一条消息给piyell
             */
            Message message = new Message("piyell@pc-piyell");
            message.addBody(null, "hello");
            message.addSubject("favorite color", "red");
//            chat.sendMessage("Hello World!");
            chat.sendMessage(message);

        } catch (SmackException.NotConnectedException e) {
            e.printStackTrace();
        }
    }


下面贴上示例代码下载地址: http://download.csdn.net/detail/piyell/9241179

你可能感兴趣的:(使用Android+smack4.1.4+openfire进行IM开发)