安卓实现gtalk的xmpp简单通信
这里尝试用安卓尝试对电脑上的一个gtalk客户端进行推送消息。
项目源代码可去我的Q群共享下载(250395324)
1.首先要有两个google账号,这里我们假设账号一和账号二
2.需要一个xmpp协议(smack)的jar包,下载地址有很多
lz用的是http://beem-project.com/projects/beem/repository/changes/libs/asmack-android-7-beem.jar
3.配置java代码(其中gmail邮箱代表了你的gtalk的账号)
- String host = "talk.google.com";
- String port = "5222";
- String service = "google.com";
- String username = "你的google邮箱";
- String password = "邮箱密码";
- // Create a connection
- ConnectionConfiguration connConfig =
- new ConnectionConfiguration(host, Integer.parseInt(port), service);
- XMPPConnection connection = new XMPPConnection(connConfig);
- try {
- Log.v("aaaaaaaaaaaaaaaaaaaa", "start");
- 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);
- String to = "推送目的地邮箱";
- Message msg = new Message(to, Message.Type.chat);
- msg.setSubject("VideoID");
- msg.setBody("刘新云是sb"); // 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);
- }
ps.记得配置权限: <uses-permission android:name="android.permission.INTERNET" />
不然请求会被拒绝
如果希望接收消息,记得新建一个方法然后再方法里面监听connection对象
- public void setConnection
- (XMPPConnection
- 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);
- }
- }
4.5 然后在 connection.sendPacket(msg);
这句代码下面调用该方法,此时app将监听服务器那边的异动了
this.setConnection(connection);
4.打开你的gtalk看看是不是有一条新的消息(其中你推送的邮箱最好是你加过的好友)
如果希望自己配置服务器的可以使用fireopen这样的开源服务器框架就可自己制作简单即时通信软件了