2015年1月25日 星期日

Android 基於xmpp協議,smack包,openfire服務端的高仿QQ的即時通訊實現【3】添加分組...

http://www.apkbus.com/blog-125132-52802.html

我利用xmpp协议写的Spark作为另一个客户端,与我自己建的QQ客户端进行测试。
首先下载Spark,安装,配置,可以用我们openfire服务端建立的帐号进行登录。
首先 先添加好友,添加组,然后读取好友列表,我这个地方写的简单,可以借鉴,自己优化。
登录成功后,点击menu按钮,可以出现底部菜单,添加好友。
点击 添加好友进入,添加好友页面:
输入好友名称,可以搜索服务端有的帐号,搜索与添加好友代码:
[html] view plaincopy
  1. public void searchFriend() {      
  2.         String search_text = ((EditText) findViewById(R.id.search_text)).getText().toString();  
  3.         if (search_text.equals("")) {  
  4.             Toast.makeText(FriendAddActivity.this, "输入信息不能为空!", Toast.LENGTH_SHORT).show();  
  5.         } else {  
  6.             try{  
  7.                 XMPPConnection connection = XmppConnection.getConnection();  
  8.                 UserSearchManager search = new UserSearchManager(connection);  
  9.                 //此处一定要加上 search.  
  10.                 Form searchForm = search.getSearchForm("search."+connection.getServiceName());  
  11.                 Form answerForm = searchForm.createAnswerForm();  
  12.                 answerForm.setAnswer("Username", true);  
  13.                 answerForm.setAnswer("search", search_text.toString().trim());  
  14.                 ReportedData data = search.getSearchResults(answerForm,"search."+connection.getServiceName());                    
  15.                 Iterator<Row> it = data.getRows();  
  16.                 Row row=null;  
  17.                 while(it.hasNext()){  
  18.                     row=it.next();  
  19.                     queryResult=row.getValues("Username").next().toString();  
  20.                 }  
  21.             }catch(Exception e){  
  22.                 Toast.makeText(FriendAddActivity.this,e.getMessage()+" "+e.getClass().toString(), Toast.LENGTH_SHORT).show();  
  23.             }  
  24.             if(!queryResult.equals("")){  
  25.                 // 生成动态数组,加入数据  
  26.                 ArrayList<HashMap<String, Object>> listItem = new ArrayList<HashMap<String, Object>>();  
  27.                     HashMap<String, Object> map = new HashMap<String, Object>();           
  28.                     map.put("name", queryResult); //会员昵称  
  29.                     listItem.add(map);  
  30.                 // 生成适配器的Item和动态数组对应的元素  
  31.                 SimpleAdapter listItemAdapter = new SimpleAdapter(this, listItem,// 数据源  
  32.                         R.layout.friend_search_view,// ListItem的XML实现  
  33.                         // 动态数组与ImageItem对应的子项  
  34.                         new String[] { "name", },  
  35.                         // ImageItem的XML文件里面的一个ImageView,两个TextView ID  
  36.                         new int[] { R.id.itemtext });  
  37.                 // 添加并且显示  
  38.                 list.setAdapter(listItemAdapter);  
  39.                 // 添加短点击事件  
  40.                 list.setOnItemClickListener(new OnItemClickListener() {  
  41.                     public void onItemClick(AdapterView<?> parent, View view,  
  42.                             int position, long id) {  
  43.                         HashMap<String, String> map = (HashMap<String, String>) list.getItemAtPosition(position);  
  44.                         final String name = map.get("name");  
  45.                         AlertDialog.Builder dialog=new AlertDialog.Builder(FriendAddActivity.this);  
  46.                         dialog.setTitle("添加好友")  
  47.                               .setIcon(R.drawable.default_head)  
  48.                               .setMessage("您确定要添加【"+name+"】为好友吗?")  
  49.                               .setPositiveButton("确定", new DialogInterface.OnClickListener() {  
  50.                                          @Override  
  51.                                          public void onClick(DialogInterface dialog, int which) {          
  52.                                              // TODO Auto-generated method stub   
  53.                                              Roster roster = XmppConnection.getConnection().getRoster();  
  54.                                              String userName = name+"@"+XmppConnection.getConnection().getServiceName();  
  55.                                              //默认添加到【我的好友】分组  
  56.                                              String groupName = "我的好友";  
  57.                                              XmppService.addUsers(roster, userName, name, groupName);  
  58.                                              Presence subscription = new Presence(Presence.Type.subscribe);  
  59.                                              subscription.setTo(userName);  
  60.                                              dialog.cancel();//取消弹出框  
  61.                                              finish();  
  62.                                              Intent intent = new Intent();  
  63.                                              intent.putExtra("USERID", pUSERID);  
  64.                                              intent.putExtra("GROUPNAME", groupName);  
  65.                                              intent.setClass(FriendAddActivity.this, FriendListActivity.class);  
  66.                                              startActivity(intent);  
  67.                                          }  
  68.                                        })  
  69.                                .setNegativeButton("取消", new DialogInterface.OnClickListener() {  
  70.                                          public void onClick(DialogInterface dialog, int which) {              
  71.                                              // TODO Auto-generated method stub  
  72.                                              dialog.cancel();//取消弹出框  
  73.                                          }  
  74.                                        }).create().show();  
  75.                            }  
  76.                      });      
  77.               }else{  
  78.                   Toast.makeText(FriendAddActivity.this, "此用户不存在,请确保输入的信息正确!", Toast.LENGTH_SHORT).show();  
  79.               }  
  80.         }  
  81.     }  

搜索到好友后,直接点击添加,会添加到默认分组【我的好友】,也可以在搜索到好友后,将其添加到新建分组中,也可以即时聊天,这是我的设计。

添加组代码:
[html] view plaincopy
  1. String groupName = addFriend.getText().toString().trim();  
  2.                     if (groupName.equals("") || groupName.equals("")) {  
  3.                         Toast.makeText(FriendAddActivity.this, "群组名称不能为空!", Toast.LENGTH_SHORT).show();  
  4.                     } else {  
  5.                         boolean result = false;  
  6.                         result = XmppService.addGroup(roster, groupName);  
  7.                         if (result) {  
  8.                              Roster roster = XmppConnection.getConnection().getRoster();  
  9.                              String userName = queryResult+"@"+XmppConnection.getConnection().getServiceName();  
  10.                              XmppService.addUsers(roster, userName, queryResult, groupName);  
  11.                              Intent intent = new Intent();  
  12.                              intent.putExtra("USERID", pUSERID);  
  13.                              intent.setClass(FriendAddActivity.this, FriendListActivity.class);  
  14.                              startActivity(intent);  
  15.                         } else {  
  16.                             Toast.makeText(FriendAddActivity.this, "群组添加失败!", Toast.LENGTH_SHORT).show();  
  17.                         }  
  18.                     }  


当你确定添加后,Spark端,后收到添加好友请求。
接受后,两面都可以看见彼此了,要是自建客户端好友未出现,刷新列表,就能看见了。
以下是自建客户端,读取好友列表的代码:
[html] view plaincopy
  1. public void loadFriend() {  
  2.         try {  
  3.             XMPPConnection conn = XmppConnection.getConnection();  
  4.             Roster roster = conn.getRoster();  
  5.             Collection<RosterGroup> groups = roster.getGroups();  
  6.             groupList = new ArrayList<GroupInfo>();  
  7.             for (RosterGroup group : groups) {  
  8.                 groupInfo = new GroupInfo();  
  9.                 friendList = new ArrayList<FriendInfo>();  
  10.                 groupInfo.setGroupName(group.getName());  
  11.                 Collection<RosterEntry> entries = group.getEntries();  
  12.                 for (RosterEntry entry : entries) {  
  13.                     if("both".equals(entry.getType().name())){//只添加双边好友   
  14.                         friendInfo = new FriendInfo();  
  15.                         friendInfo.setUsername(Utils.getJidToUsername(entry.getUser()));  
  16.                         System.out.println("我的好友心情是:"+entry.getStatus().fromString(entry.getUser()));  
  17.                         if(friendMood == null){  
  18.                             friendMood ="Q我吧,静待你的来信!";  
  19.                         }  
  20.                         friendInfo.setMood(friendMood);  
  21.                         friendList.add(friendInfo);  
  22.                         friendInfo = null;            
  23.                     }  
  24.                 }  
  25.                 groupInfo.setFriendInfoList(friendList);  
  26.                 groupList.add(groupInfo);  
  27.                 groupInfo = null;  
  28.             }  
  29.         if(groupList.isEmpty()){  
  30.             groupInfo = new GroupInfo();  
  31.             groupInfo.setGroupName("我的好友");  
  32.             groupInfo.setFriendInfoList(new ArrayList<FriendInfo>());  
  33.             groupList.add(groupInfo);  
  34.             groupInfo = null;  
  35.         }  
  36.         } catch (Exception e) {  
  37.             e.printStackTrace();  
  38.         }  
  39.     }