代码改变世界

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

2012-03-27 21:03  wihoho  阅读(10447)  评论(42编辑  收藏  举报

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.
*/
@Override
public 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>();

@Override
public 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

如果有github账户,希望可以star一下,哈