您的位置:首页 > 移动开发 > Android开发

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

2017-01-04 14:10 337 查看
从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:

[java] view
plain copy

<?xml version="1.0" encoding="utf-8"?>  

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  

    xmlns:tools="http://schemas.android.com/tools"  

    android:layout_width="match_parent"  

    android:layout_height="match_parent"  

    android:orientation="vertical"  

    android:paddingBottom="@dimen/activity_vertical_margin"  

    android:paddingLeft="@dimen/activity_horizontal_margin"  

    android:paddingRight="@dimen/activity_horizontal_margin"  

    android:paddingTop="@dimen/activity_vertical_margin"  

    android:weightSum="1"  

    tools:context="com.piyell.openfiretest.MainActivity">  

  

  

    <EditText  

        android:hint="输入用户名:"  

        android:id="@+id/et_jid"  

        android:layout_width="match_parent"  

        android:layout_height="wrap_content" />  

    <LinearLayout  

        android:orientation="horizontal"  

        android:layout_width="match_parent"  

        android:layout_height="wrap_content">  

        <Button  

            android:onClick="con"  

            android:layout_width="wrap_content"  

            android:layout_height="wrap_content"  

            android:text="connect" />  

        <Button  

            android:onClick="login"  

            android:layout_width="wrap_content"  

            android:layout_height="wrap_content"  

            android:text="login" />  

        <Button  

            android:onClick="sendMsg"  

            android:layout_width="wrap_content"  

            android:layout_height="wrap_content"  

            android:text="sendMsg" />  

    </LinearLayout>  

  

    <ExpandableListView  

        android:padding="5dip"  

        android:id="@+id/listview"  

        android:layout_weight="1"  

        android:layout_width="match_parent"  

        android:layout_height="wrap_content">  

  

    </ExpandableListView>  

  

</LinearLayout>  

新建item_child.xml和item_parent.xml

item_child.xml

[java] view
plain copy

<pre name="code" class="html"><?xml version="1.0" encoding="utf-8"?>  

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  

    android:orientation="vertical" android:layout_width="match_parent"  

    android:layout_height="match_parent">  

    <TextView  

        android:gravity="right"  

        android:id="@+id/tv_child"  

        android:text="sdfdgdf"  

        android:textSize="30sp"  

        android:layout_width="match_parent"  

        android:layout_height="match_parent">  

    </TextView>  

  

</LinearLayout>  


item_parent.xml

[java] view
plain copy

<pre name="code" class="html"><?xml version="1.0" encoding="utf-8"?>  

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  

    android:orientation="vertical" android:layout_width="match_parent"  

    android:layout_height="match_parent">  

    <TextView  

        android:id="@+id/tv_parent"  

        android:gravity="right"  

        android:textSize="20sp"  

        android:layout_width="match_parent"  

        android:layout_height="match_parent">  

    </TextView>  

  

</LinearLayout>  


连接服务器:

[java] view
plain copy

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);//设为调试模式以在控制台查看相关log报文,方便调试

       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;  

  

  

   }  

登录部分:

[java] view
plain copy

 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<RosterEntry> 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<RosterGroup> groups = roster.getGroups();  

        parentList = new ArrayList<>();  

  

        map = new HashMap<>();  

        for (RosterGroup group : groups) {  

            parentList.add(group.getName());  

            List<String> 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<String> collection) {}  

  

            @Override  

            public void entriesUpdated(Collection<String> collection) { }  

  

            @Override  

            public void entriesDeleted(Collection<String> collection) {}  

  

            @Override  

            public void presenceChanged(Presence presence) {  

                Log.e("TAG", presence.getFrom() + presence);  

            }  

        });  

  

    }  

发送消息:

[java] view
plain copy

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

转自:http://blog.csdn.net/piyell/article/details/49641167
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: