Android基于XMPP Smack Openfire开发IM【三】客户端接收服务器发送的消息

Demo需求:android客户端接收服务器发送来的消息。

第一,客户端代码如下:
MainActivity未做改动,与之前两篇一样
package com.example.openfiretest;

import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ChatManager;
import org.jivesoftware.smack.ChatManagerListener;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.packet.Message;

import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
	
	
	
	private EditText accountEditText;
	private EditText passwordEditText;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_main);
		accountEditText = (EditText) findViewById(R.id.username);
		passwordEditText = (EditText) findViewById(R.id.password);

		findViewById(R.id.login).setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				String account = accountEditText.getText().toString();
				String password = passwordEditText.getText().toString();
				if (account.equals("") || password.equals("")) {
					Toast.makeText(MainActivity.this, "账号或密码不能为空!",
							Toast.LENGTH_SHORT).show();
				} else {
					ClientConServer ccs = new ClientConServer(MainActivity.this);
					boolean b = ccs.login(account, password);
					// 如果登录成功
					if (b) {
						Toast.makeText(MainActivity.this, "登陆成功!",
								Toast.LENGTH_SHORT).show();
						
						
					} else {
						Toast.makeText(MainActivity.this, "登陆失败!",
								Toast.LENGTH_SHORT).show();
					}
				}
			}
		});
	}
	
}


下面的这个类在第二篇的基础上,在登陆以后添加一个监听消息的监听器,用来监听收到的消息(代码89、90行):
package com.example.openfiretest;

import java.util.Collection;

import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ChatManager;
import org.jivesoftware.smack.ChatManagerListener;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.RosterGroup;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;


import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;

public class ClientConServer {
	private static int PORT=5222;
	private Context context;
	public ClientConServer(Context context){
		this.context=context;

	}
	//这里收到消息后,通过广播将消息发送到需要的地方.哈哈,既然收到了服务器发送来的信息,如何处理自己决定。
	private Handler handler = new Handler(){  
        public void handleMessage(android.os.Message m) {  
            Message msg=new Message();  
            msg=(Message) m.obj; 
            //把从服务器获得的消息通过广播发送  
            Intent intent = new Intent("org.yhn.mes");  
            String[] message=new String[]{  
                    msg.getFrom(),  
                    msg.getBody()}; 
            System.out.println("==========收到服务器消息  From==========="+message[0].toString());
            System.out.println("==========收到服务器消息  Body==========="+message[1].toString());
            intent.putExtra("message", message);  
            context.sendBroadcast(intent);  
        };  
    };
	
	public boolean login(String a,String p){
		ConnectionConfiguration config = new ConnectionConfiguration("192.168.0.124", PORT);
		/** 是否启用安全验证 */
		config.setSASLAuthenticationEnabled(false);
		/** 是否启用调试 */
        //config.setDebuggerEnabled(true);
        /** 创建connection链接 */
		XMPPConnection connection = new XMPPConnection(config);
		try {
			/** 建立连接 */
			connection.connect();
			
			
			/** 登录*/
			connection.login(a, p);
			/** 开启读写线程,并加入到管理类中*/
			//ClientSendThread cst=new ClientSendThread(connection);
			//cst.start();
			//ManageClientThread.addClientSendThread(a, cst);
			
			//获取用户组、成员信息。
			System.out.println("======开始获取组及用户==========");
			Roster roster = connection.getRoster();
			Collection<RosterGroup> entriesGroup = roster.getGroups();
			System.out.println("组的个数:"+entriesGroup.size());
			for(RosterGroup group: entriesGroup){
				Collection<RosterEntry> entries = group.getEntries();
				System.out.println("=========groupName==="+group.getName());
				for (RosterEntry entry : entries) {
					//Presence presence = roster.getPresence(entry.getUser());
					//Log.i("---", "user: "+entry.getUser());
					System.out.println("组成员名字:"+entry.getName());
					//Log.i("---", "tyep: "+entry.getType());
					//Log.i("---", "status: "+entry.getStatus());
					//Log.i("---", "groups: "+entry.getGroups());
				}
			}
			System.out.println("======结束获取组及用户==========");
			
			
			//在登陆以后应该建立一个监听消息的监听器,用来监听收到的消息:
			ChatManager chatManager = connection.getChatManager();
			chatManager.addChatListener(new MyChatManagerListener());
			
			
			return true;
		} catch (XMPPException e) {
			e.printStackTrace();
		}
		return false;
	 }
	/** message listener*/  
    class MyChatManagerListener implements ChatManagerListener {  
    	
    	
        public void chatCreated(Chat chat, boolean arg1) {  
            chat.addMessageListener(new MessageListener(){  
                public void processMessage(Chat arg0, Message msg) {  
                    /**通过handler转发消息*/  
                    android.os.Message m=handler.obtainMessage();  
                    m.obj=msg;  
                    m.sendToTarget(); 
                	
                	
                }  
            });  
        } 
    }
}



第二,启动android客户端,进行登录。
[img]
Android基于XMPP Smack Openfire开发IM【三】客户端接收服务器发送的消息_第1张图片
[/img]



第三、在openfire的管理控制台,会话-工具中发送消息给所有在线用户,如下图
[img]
Android基于XMPP Smack Openfire开发IM【三】客户端接收服务器发送的消息_第2张图片
[/img]



第四、打印信息如下:
[img]
Android基于XMPP Smack Openfire开发IM【三】客户端接收服务器发送的消息_第3张图片
[/img]

你可能感兴趣的:(android)