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

10 篇文章 0 订阅
7 篇文章 0 订阅

从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
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     xmlns:tools="http://schemas.android.com/tools"  
  4.     android:layout_width="match_parent"  
  5.     android:layout_height="match_parent"  
  6.     android:orientation="vertical"  
  7.     android:paddingBottom="@dimen/activity_vertical_margin"  
  8.     android:paddingLeft="@dimen/activity_horizontal_margin"  
  9.     android:paddingRight="@dimen/activity_horizontal_margin"  
  10.     android:paddingTop="@dimen/activity_vertical_margin"  
  11.     android:weightSum="1"  
  12.     tools:context="com.piyell.openfiretest.MainActivity">  
  13.   
  14.   
  15.     <EditText  
  16.         android:hint="输入用户名:"  
  17.         android:id="@+id/et_jid"  
  18.         android:layout_width="match_parent"  
  19.         android:layout_height="wrap_content" />  
  20.     <LinearLayout  
  21.         android:orientation="horizontal"  
  22.         android:layout_width="match_parent"  
  23.         android:layout_height="wrap_content">  
  24.         <Button  
  25.             android:onClick="con"  
  26.             android:layout_width="wrap_content"  
  27.             android:layout_height="wrap_content"  
  28.             android:text="connect" />  
  29.         <Button  
  30.             android:onClick="login"  
  31.             android:layout_width="wrap_content"  
  32.             android:layout_height="wrap_content"  
  33.             android:text="login" />  
  34.         <Button  
  35.             android:onClick="sendMsg"  
  36.             android:layout_width="wrap_content"  
  37.             android:layout_height="wrap_content"  
  38.             android:text="sendMsg" />  
  39.     </LinearLayout>  
  40.   
  41.     <ExpandableListView  
  42.         android:padding="5dip"  
  43.         android:id="@+id/listview"  
  44.         android:layout_weight="1"  
  45.         android:layout_width="match_parent"  
  46.         android:layout_height="wrap_content">  
  47.   
  48.     </ExpandableListView>  
  49.   
  50. </LinearLayout>  


新建item_child.xml和item_parent.xml

item_child.xml

[java]  view plain  copy
  1. <pre name="code" class="html"><?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical" android:layout_width="match_parent"  
  4.     android:layout_height="match_parent">  
  5.     <TextView  
  6.         android:gravity="right"  
  7.         android:id="@+id/tv_child"  
  8.         android:text="sdfdgdf"  
  9.         android:textSize="30sp"  
  10.         android:layout_width="match_parent"  
  11.         android:layout_height="match_parent">  
  12.     </TextView>  
  13.   
  14. </LinearLayout>  


 
 item_parent.xml 
 

[java]  view plain  copy
  1. <pre name="code" class="html"><?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical" android:layout_width="match_parent"  
  4.     android:layout_height="match_parent">  
  5.     <TextView  
  6.         android:id="@+id/tv_parent"  
  7.         android:gravity="right"  
  8.         android:textSize="20sp"  
  9.         android:layout_width="match_parent"  
  10.         android:layout_height="match_parent">  
  11.     </TextView>  
  12.   
  13. </LinearLayout>  

 
 连接服务器: 
 

[java]  view plain  copy
  1. protected boolean conServer() {  
  2.        XMPPTCPConnectionConfiguration.Builder config = XMPPTCPConnectionConfiguration.builder();  
  3.        config.setHost("10.0.2.2");              //设置openfire主机IP  
  4.        config.setServiceName("pc-piyell");         //设置openfire服务器名称  
  5.        config.setPort(5222);                   //设置端口号:默认5222  
  6.        config.setUsernameAndPassword(et_jid.getText(), "123456");    //设置用户名与密码  
  7.        config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);      //禁用SSL连接  
  8.        config.setSendPresence(true);  //状态设为离线,目的为了取离线消息  
  9.        config.setDebuggerEnabled(true);//设为调试模式以在控制台查看相关log报文,方便调试
  10.        con = new XMPPTCPConnection(config.build());  
  11.        try {  
  12.            con.connect();  
  13.            //Log.e("TAG", connect.getUser());  
  14.        } catch (Exception e) {  
  15.            Log.e("TAG""connect failed!" + e.toString());  
  16.            e.printStackTrace();  
  17.            return false;  
  18.        }  
  19.        return true;  
  20.   
  21.   
  22.    }  
登录部分:

[java]  view plain  copy
  1.  public void login(View view) {  
  2.   
  3.         Roster roster = Roster.getInstanceFor(con);  
  4.   
  5.   
  6.         try {  
  7.             con.login();  
  8.         } catch (Exception e) {  
  9.             e.printStackTrace();  
  10.         }  
  11.         Log.e("TAG""login sucess!!");  
  12.         setPresence(1);  
  13.   
  14. //         设置聊天监听器,监听聊天消息  
  15.         ChatManager chatm = ChatManager.getInstanceFor(con);  
  16.         chatm.addChatListener(new ChatManagerListener() {  
  17.             @Override  
  18.             public void chatCreated(Chat chat, boolean b) {  
  19.                 if (!b) {           //不是本地创建的会话  
  20.                     chat.addMessageListener(new mChatMsgListener());  
  21.                 }  
  22.             }  
  23.         });  
  24.   
  25.         /** 
  26.          *  添加一个分组—— friends 
  27.          */  
  28.         Set<RosterEntry> entries = roster.getEntries();  
  29.         RosterGroup friends = roster.createGroup("friends");  
  30.         try {  
  31.             for (RosterEntry entry : entries) {  
  32.                 friends.addEntry(entry);   /**添加所有好友到friends分组*/  
  33.   
  34.             }  
  35.         } catch (Exception e) {  
  36.             e.printStackTrace();  
  37.         }  
  38.   
  39.         Log.e("tag""------群组数=======" + roster.getGroupCount());  
  40.         Collection<RosterGroup> groups = roster.getGroups();  
  41.         parentList = new ArrayList<>();  
  42.   
  43.         map = new HashMap<>();  
  44.         for (RosterGroup group : groups) {  
  45.             parentList.add(group.getName());  
  46.             List<String> childList = new ArrayList<>();  
  47.             for (RosterEntry rosterEntry : entries) {  
  48.                 childList.add(rosterEntry.getUser().toString().split("@")[0]);  
  49.                 Log.e("tag""------Entry=======" + rosterEntry.getUser().toString());  
  50.             }  
  51.             map.put(group.getName(), childList);  
  52.             Log.e("tag""childlist--------" + map.get(parentList.get(0)).toString());  
  53. //            childList.clear();  
  54.         }  
  55.         listview.setAdapter(new MyAdapter());  
  56.   
  57.   
  58.         roster.addRosterListener(new RosterListener() {  
  59.             @Override  
  60.             public void entriesAdded(Collection<String> collection) {}  
  61.   
  62.             @Override  
  63.             public void entriesUpdated(Collection<String> collection) { }  
  64.   
  65.             @Override  
  66.             public void entriesDeleted(Collection<String> collection) {}  
  67.   
  68.             @Override  
  69.             public void presenceChanged(Presence presence) {  
  70.                 Log.e("TAG", presence.getFrom() + presence);  
  71.             }  
  72.         });  
  73.   
  74.     }  

发送消息:

[java]  view plain  copy
  1. public void sendMsg(View view) {  
  2.         ChatManager chatm = ChatManager.getInstanceFor(con);  
  3.         Chat chat = chatm.createChat("piyell@pc-piyell"new ChatMessageListener() {        //创建与piyell的会话  
  4.             public void processMessage(Chat chat, Message message) {  
  5.                 System.out.println("Received message: " + message);  
  6.             }  
  7.         });  
  8.         try {  
  9.             /** 
  10.              * 发送一条消息给piyell 
  11.              */  
  12.             Message message = new Message("piyell@pc-piyell");  
  13.             message.addBody(null"hello");  
  14.             message.addSubject("favorite color""red");  
  15. //            chat.sendMessage("Hello World!");  
  16.             chat.sendMessage(message);  
  17.   
  18.         } catch (SmackException.NotConnectedException e) {  
  19.             e.printStackTrace();  
  20.         }  
  21.     }  


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

转自:http://blog.csdn.net/piyell/article/details/49641167

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值