Ureca终于把主要的功能给解决了,不管怎样,明天去见Prof. ,不管他同不同意,我都不会再做下去了。真心比较忙最近,而且哈,忙的话,真的很多事情都没法尽善尽美地完成,这不是我的风格,另外剩下主要准备实习了,加油加油。

这个project主要是想实现一个一边看视频,一边在线聊天的App,真的好老土,不过对于我这种新手能做出来已经很不错了。下边讲的就是如何利用XMPP登录gtalk以实现聊天的功能,真心投入很多。标题的后半部分是想表达如果利用App Engine来实现转发的功能,并且通过这个特性,实现聊天室的组建,当然这是个比较虚的“聊天室”。没服务器呀,只要免费用google的了。下边是用两个模拟器展示出来的效果图:

XMPP的功能主要就是通过一下两个文件实现的,当然都有refer别人的东西。SettingDialog就是得先连接好gtalk的服务器,然后在XMPP里边发送和接受消息,需要用到smack,自行google哈。

SettingDialog.java

package app.tabsample;

import org.jivesoftware.smack.ConnectionConfiguration;import org.jivesoftware.smack.XMPPConnection;import org.jivesoftware.smack.XMPPException;import org.jivesoftware.smack.packet.Message;import org.jivesoftware.smack.packet.Presence;

import android.app.Dialog;import android.util.Log;import android.view.View;import android.widget.Button;import android.widget.EditText;

/** * Gather the xmpp settings and create an XMPPConnection*/public class SettingsDialog extends Dialog implements android.view.View.OnClickListener {private XMPPClient xmppClient;

public SettingsDialog(XMPPClient xmppClient) {super(xmppClient);this.xmppClient = xmppClient;    }

protected void onStart() {super.onStart();        setContentView(R.layout.settings);        getWindow().setFlags(4, 4);        setTitle("XMPP Settings");        Button ok = (Button) findViewById(R.id.ok);        ok.setOnClickListener(this);    }

public void onClick(View v) {        String host = "talk.google.com";        String port = "5222";        String service = "google.com";        String username = getText(R.id.userid);        String password = getText(R.id.password);

// Create a connection        ConnectionConfiguration connConfig =new ConnectionConfiguration(host, Integer.parseInt(port), service);        XMPPConnection connection = new XMPPConnection(connConfig);

try {            connection.connect();            Log.i("XMPPClient", "[SettingsDialog] Connected to " + connection.getHost());        } catch (XMPPException ex) {            Log.e("XMPPClient", "[SettingsDialog] Failed to connect to " + connection.getHost());            Log.e("XMPPClient", ex.toString());            xmppClient.setConnection(null);        }try {            connection.login(username, password);            Log.i("XMPPClient", "Logged in as " + connection.getUser());

// Set the status to available            Presence presence = new Presence(Presence.Type.available);            connection.sendPacket(presence);            xmppClient.setConnection(connection);

//Send initial messages to the server            String t = Temp.getID();            String to = "wihoho@appspot.com";            Log.i("XMPPClient", "Sending text [" + t + "] to [" + to + "]");            Message msg = new Message(to, Message.Type.chat);             msg.setSubject("VideoID");            msg.setBody("i"+t); // i is used to indicate this message as sending video ID            connection.sendPacket(msg);

        } catch (XMPPException ex) {            Log.e("XMPPClient", "[SettingsDialog] Failed to log in as " + username);            Log.e("XMPPClient", ex.toString());                xmppClient.setConnection(null);        }        dismiss();    }

private String getText(int id) {        EditText widget = (EditText) this.findViewById(id);return widget.getText().toString();    }}

XMPPClient.java

package app.tabsample;

import android.app.Activity;import android.os.Bundle;import android.os.Handler;import android.util.Log;import android.view.View;import android.widget.ArrayAdapter;import android.widget.Button;import android.widget.EditText;import android.widget.ListView;import org.jivesoftware.smack.PacketListener;import org.jivesoftware.smack.XMPPConnection;import org.jivesoftware.smack.filter.MessageTypeFilter;import org.jivesoftware.smack.filter.PacketFilter;import org.jivesoftware.smack.packet.Message;import org.jivesoftware.smack.packet.Packet;import org.jivesoftware.smack.util.StringUtils;

import java.util.ArrayList;

public class XMPPClient extends Activity {

private ArrayList<String> messages = new ArrayList<String>();private Handler mHandler = new Handler();private SettingsDialog mDialog;//private EditText mRecipient;    private EditText mSendText;private ListView mList;private XMPPConnection connection;

/**     * Called with the activity is first created.*/    @Overridepublic void onCreate(Bundle icicle) {super.onCreate(icicle);        Log.i("XMPPClient", "onCreate called");        setContentView(R.layout.chatting);

//mRecipient = (EditText) this.findViewById(R.id.recipient);//Log.i("XMPPClient", "mRecipient = " + mRecipient);        mSendText = (EditText) this.findViewById(R.id.sendText);        Log.i("XMPPClient", "mSendText = " + mSendText);        mList = (ListView) this.findViewById(R.id.listMessages);        Log.i("XMPPClient", "mList = " + mList);        setListAdapter();

// Dialog for getting the xmpp settings        mDialog = new SettingsDialog(this);

//Sending the Video ID to the app engine//        Temp app = (Temp)getApplicationContext();//        String t = app.getID();//        String to = "gongli.huge@gmail.com";//        Log.i("XMPPClient", "Sending text [" + t + "] to [" + to + "]");//        Message msg = new Message(to, Message.Type.chat);//        msg.setBody(t);//        connection.sendPacket(msg);//End of updating the chatting room

// Set a listener to show the settings dialog        Button setup = (Button) this.findViewById(R.id.setup);        setup.setOnClickListener(new View.OnClickListener() {public void onClick(View view) {                mHandler.post(new Runnable() {public void run() {                        mDialog.show();//........................Send the current video Id to the app engine//                        String t = Temp.getID();//                        String to = "gongli.huge@gmail.com";//                        Log.i("XMPPClient", "Sending text [" + t + "] to [" + to + "]");//                        Message msg = new Message(to, Message.Type.chat);//                        msg.setBody(t);//                        connection.sendPacket(msg);//........................End                    }                });            }        });

// Set a listener to send a chat text message        Button send = (Button) this.findViewById(R.id.send);        send.setOnClickListener(new View.OnClickListener() {public void onClick(View view) {//String to = mRecipient.getText().toString();                String to = "wihoho@appspot.com";                String text = mSendText.getText().toString();

                Log.i("XMPPClient", "Sending text [" + text + "] to [" + to + "]");                Message msg = new Message(to, Message.Type.chat);                msg.setSubject("chat");                msg.setBody("c"+text); //c is used to indicate this message is chatting txt                connection.sendPacket(msg);//messages.add(connection.getUser() + ":"); //messages.add(text);                setListAdapter();            }        });    }

/**     * Called by Settings dialog when a connection is establised with the XMPP server     *     * @param connection*/public void setConnection            (XMPPConnection                    connection) {this.connection = connection;if (connection != null) {// Add a packet listener to get messages sent to us            PacketFilter filter = new MessageTypeFilter(Message.Type.chat);            connection.addPacketListener(new PacketListener() {public void processPacket(Packet packet) {                    Message message = (Message) packet;if (message.getBody() != null) {                        String fromName = StringUtils.parseBareAddress(message.getFrom());                        Log.i("XMPPClient", "Got text [" + message.getBody() + "] from [" + fromName + "]");//messages.add(fromName + ":");                        messages.add(message.getBody());// Add the incoming message to the list view                        mHandler.post(new Runnable() {public void run() {                                setListAdapter();                            }                        });                    }                }            }, filter);        }    }

private void setListAdapter() {        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,                R.layout.multi_line_list_item,                messages);        mList.setAdapter(adapter);    }}

接下来的是App Engine这端的代码:

chattingServiceServlet.java

package com.chat;

import java.io.IOException;import java.util.LinkedList;import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.xmpp.JID;import com.google.appengine.api.xmpp.Message;import com.google.appengine.api.xmpp.MessageBuilder;import com.google.appengine.api.xmpp.XMPPService;import com.google.appengine.api.xmpp.XMPPServiceFactory;

@SuppressWarnings("serial")public class ChattingServiceServlet extends HttpServlet {private static final Logger LOG = Logger.getLogger(ChattingServiceServlet.class.getName());private LinkedList<User> users = new LinkedList<User>();

              @Overridepublic void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {

// Parse incoming message                XMPPService xmpp = XMPPServiceFactory.getXMPPService();                Message msg = xmpp.parseMessage(req);                JID jid = msg.getFromJid();                String body = msg.getBody();

// Analyze the received message

//Send the video ID                if(body.charAt(0) == 'i'){                    LOG.info(jid.getId() + ": " + body);int m;for(m = 0; m < users.size(); m ++){if(users.get(m).user.toString().equals(getRealID(jid).toString()))break;                    }

//if found                    if(m < users.size())                        users.get(m).videoID = body.substring(1);//if not found                    else{                        users.add(new User(getRealID(jid) ,body.substring(1)));                    }

//indicate that the user has entered the chat room                    String response = "You have entered chatting room: "+body.substring(1)+"\nThe below users are in the same chatting room with you ";                    msg = new MessageBuilder().withRecipientJids(jid).withBody(response).build();                    xmpp.sendMessage(msg);

//Used to print out the current users

for(int n = 0 ; n < users.size(); n++){    if(users.get(n).videoID.equals(body.substring(1))){                            String userinfo = users.get(n).user.toString();                            msg = new MessageBuilder().withRecipientJids(jid).withBody(userinfo).build();                            xmpp.sendMessage(msg);                        }                    }                }

//Send text                else if(body.charAt(0) == 'c'){                    LOG.info(jid.getId() + ": " + body);//Find the video ID of the current user                    int index;for(index = 0; index < users.size(); index ++){if(users.get(index).user.toString().equals(getRealID(jid).toString()))break;                    }//Find the users with the same vdieo ID                    if(index < users.size()){                        LinkedList<JID> jids = getJIDsID(users.get(index).videoID);                        String response = jid.toString()+": "+body.substring(1);

for(int n = 0 ; n < jids.size(); n++){                                                    msg = new MessageBuilder().withRecipientJids(jids.get(n)).withBody(response).build();                            xmpp.sendMessage(msg);                        }                    }                }              }

public JID getRealID(JID receiveID){                  StringBuffer sb = new StringBuffer();int i = 5;

while(receiveID.toString().charAt(i) != '/'){                      sb.append(receiveID.toString().charAt(i));                      i++;assert i < receiveID.toString().length();                  }

return new JID(sb.toString().trim());              }

public LinkedList<JID> getJIDsID(String video){                  LinkedList<JID> jids = new LinkedList<JID>();for(int i= 0; i < users.size();i++){if(users.get(i).videoID.equals(video))                          jids.add(users.get(i).user);                  }return jids;              }

public LinkedList<String> getVideoIDs(){                  LinkedList<String> ids = new LinkedList<String>();for(int i = 0; i < users.size(); i ++){if(!ids.contains(users.get(i).videoID))                          ids.add(users.get(i).videoID);                  }return ids;              }    }

下载链接:https://github.com/wihoho/AndroidXMPP

原文:http://www.cnblogs.com/wihoho/archive/2012/03/27/2420157.html

转载于:https://www.cnblogs.com/mypzx/archive/2013/02/28/2936468.html

Android 通过 XMPP 实现聊天功能,App Engine Assisted Group Chat (开源)相关推荐

  1. Android Studio开发——蓝牙聊天功能

    Android Studio开发--蓝牙聊天功能 蓝牙工作流程 功能要求 实现要点 声明蓝牙权限 添加程序运行的状态描述文本及配色代码 布局文件 蓝牙会话的服务组件ChatService Activi ...

  2. Android仿QQ实现聊天功能

    前段时间下载了Android仿QQ界面和聊天的Demo,发现很有意思,于是研究了一下并自己在此基础上集成环信实现了在线聊天功能,可以实现注册.加人.审核通知.推送.创建群组.群组聊天,并加入了炫酷的背 ...

  3. android加入聊天功能,app实现聊天功能 - houwanmin的个人空间 - OSCHINA - 中文开源技术交流社区...

    .  OpenIM(Android)主体功能集成 1.1  前置准备 如果您单纯是想体验OpenIM的功能,建议直接跳过这一步.直接查看快速集成. 在这个集成教程中,我们使用已创建的Demo应用,向您 ...

  4. Android模仿微信语音聊天功能

    项目效果如下: 项目目录结构如下: 代码如下: AudioManager.java package com.xuliugen.weichat;import java.io.File; import j ...

  5. android 通过xmpp即时聊天客户端往服务器发消息,利用XMPP协议推送服务器告警信息到安卓平台及桌面...

    XMPP的前身是Jabber,一个开源形式组织产生的网络即时通信协议. XMPP目前被IETF国际标准组织完成了标准化工作.标准化的核心结果分为两部分: 核心的XML流传输协议 基于XML流传输的即时 ...

  6. android仿微信语音聊天功能,Android仿微信发送语音消息的功能及示例代码

    微信的发送语音是有一个向上取消的,我们使用ontouchlistener来监听手势,然后做出相应的操作就行了. 直接上代码: //语音操作对象 private mediaplayer mplayer ...

  7. Android初学者仿QQ聊天软件APP (一) 登录界面

    今天新学的知识来这里总结一下,在做登录界面时做了两个单选框按钮,用来记住密码和自动登录. //存储数据也就是用户的账号和密码SharedPreferences sharedPreferences = ...

  8. java实现仿微信app聊天功能_Android仿微信语音聊天功能

    本文实例讲述了Android仿微信语音聊天功能代码.分享给大家供大家参考.具体如下: 项目效果如下: 具体代码如下: AudioManager.java package com.xuliugen.we ...

  9. android 仿微信聊天界面 以及语音录制功能,Android仿微信录制语音功能

    本文实例为大家分享了Android仿微信录制语音的具体代码,供大家参考,具体内容如下 前言 我把录音分成了两部分 1.UI界面,弹窗读秒 2.一个类(包含开始.停止.创建文件名功能) 第一部分 由于6 ...

最新文章

  1. 在 Linux“.NET研究” 操作系统中运行 ASP.NET 4 (下)
  2. 关于 MySQL LEFT JOIN 你可能需要了解的三点
  3. fileoutputstream路径 android,Android编程中FileOutputStream与openFileOutput()的区别分析
  4. yum -y --downloadonly --downloaddir=/ruiy upggrde;
  5. 论文学习18-Relation extraction and the influence of automatic named-entity recognition(联合实体关系抽取模型,2007)
  6. dipole antenna simulation by HFSS
  7. 静态嵌套类和非静态嵌套类
  8. python变量循环写入txt文件_Python中将变量按行写入txt文本中
  9. CSDN:如何获得C币
  10. 微软拼音中设置小鹤双拼
  11. Vue中Class和Style几种v-bind绑定的用法-详解案例
  12. pdf 添加水印、页眉页脚、签名
  13. 怎么用一个显示器来显示和控制两台主机
  14. Java毕设项目会议室预约管理系统(java+VUE+Mybatis+Maven+Mysql)
  15. 微服务和分布式的区别什么?有什么特点?
  16. MyEclipse小结
  17. 巧妙地用继电器实现直流电机正反转
  18. 强烈建议使用Windows Live Writer发布日志
  19. 【数值溢出】从二进制的角度看数值溢出
  20. java bat转vbs_EXE2BAT(EXE转BAT)的vbs脚本

热门文章

  1. 在线IDE之关键字另色显示
  2. 使用brew安装Logstash(Mac)
  3. java接口的映射文件,详解mybatis通过mapper接口加载映射文件
  4. autojs怎么post协议_超9成人都理解错了HTTP中GET与POST的区别
  5. 算法杂货铺——分类算法之贝叶斯网络(Bayesian networks)
  6. 【数据平台】关于Hadoop集群namenode format安全事故
  7. uni-app接口封装
  8. 智能车声标定位相关算法优化
  9. 【BLE】TLSR8258开发记录之15--模拟FATFS
  10. 万向锁的简单数学解释