openfire,smack,XMPP,android下的会议室,聊天室的实现

我直接贴测试代码了,我做的一个小Demo,只是测一下功能是什么样子的。

下面上代码:

<pre name="code" class="java">public class Myfragment2 extends Fragment {
	private View view;
	private ListView frag02_lv1;
	private XMPPConnection connection;
	private List<HostedRoom> roominfos = new ArrayList<HostedRoom>();
	private RoomAdapter roomAdapter;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.fragment_02, container, false);
	

		init();
		return view;
	}

	private void init() {
		frag02_lv1 = (ListView) view.findViewById(R.id.frag02_lv1);
		connection = XmppConnectionManager.getInstance().getConnection();
		roominfos.clear();
		roomAdapter = new RoomAdapter(MyApplication.getContext(), roominfos);
		frag02_lv1.setAdapter(roomAdapter);
		frag02_lv1.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View view, int position,
					long id) {
				// TODO Auto-generated method stub
				// 获取用户,跳到聊天室
				HostedRoom room = roominfos.get(position);
				Intent intent = new Intent(MyApplication.getContext(),
						ActivityMultiChat.class);
				intent.putExtra("jid", room.getJid());
				System.out.println(room.getJid());
				startActivity(intent);
			}
		});
//		createRoom("111111", "111111","111111");
//		joinMultiUserChat("111111", "111111","111111");
//		joinMultiUserChat("admin", "111","");
		updateHostRoom() ;
//		System.out.println(roominfos.toArray().toString());
	}
	
	/**
	 * 创建房间
	 * 
	 * @param roomName  房间名称
	 */
	public MultiUserChat createRoom(String user, String roomName,String password) {
		if (XmppConnectionManager.getInstance().getConnection() == null)
			return null;

		MultiUserChat muc = null;
		try {
			// 创建一个MultiUserChat
			muc = new MultiUserChat(XmppConnectionManager.getInstance().getConnection(), roomName + "@conference."
					+ XmppConnectionManager.getInstance().getConnection().getServiceName());
			// 创建聊天室
			muc.create(roomName);
			// 获得聊天室的配置表单
			Form form = muc.getConfigurationForm();
			// 根据原始表单创建一个要提交的新表单。
			Form submitForm = form.createAnswerForm();
			// 向要提交的表单添加默认答复
			for (Iterator<FormField> fields = form.getFields(); fields
					.hasNext();) {
				FormField field = (FormField) fields.next();
				if (!FormField.TYPE_HIDDEN.equals(field.getType())
						&& field.getVariable() != null) {
					// 设置默认值作为答复
					submitForm.setDefaultAnswer(field.getVariable());
				}
			}
			// 设置聊天室的新拥有者
			List<String> owners = new ArrayList<String>();
			owners.add(XmppConnectionManager.getInstance().getConnection().getUser());// 用户JID
			submitForm.setAnswer("muc#roomconfig_roomowners", owners);
			// 设置聊天室是持久聊天室,即将要被保存下来
			submitForm.setAnswer("muc#roomconfig_persistentroom", true);
			// 房间仅对成员开放
			submitForm.setAnswer("muc#roomconfig_membersonly", false);
			// 允许占有者邀请其他人
			submitForm.setAnswer("muc#roomconfig_allowinvites", true);
			if (!password.equals("")) {
				// 进入是否需要密码
				submitForm.setAnswer("muc#roomconfig_passwordprotectedroom",
						true);
				// 设置进入密码
				submitForm.setAnswer("muc#roomconfig_roomsecret", password);
			}
			// 能够发现占有者真实 JID 的角色
			// submitForm.setAnswer("muc#roomconfig_whois", "anyone");
			// 登录房间对话
			submitForm.setAnswer("muc#roomconfig_enablelogging", true);
			// 仅允许注册的昵称登录
			submitForm.setAnswer("x-muc#roomconfig_reservednick", true);
			// 允许使用者修改昵称
			submitForm.setAnswer("x-muc#roomconfig_canchangenick", false);
			// 允许用户注册房间
			submitForm.setAnswer("x-muc#roomconfig_registration", false);
			// 发送已完成的表单(有默认值)到服务器来配置聊天室
			muc.sendConfigurationForm(submitForm);
		} catch (XMPPException e) {
			e.printStackTrace();
			return null;
		}
		return muc;
	}
	
	/**
	 * 加入会议室
	 * 
	 * @param user
	 *            昵称
	 * @param password
	 *            会议室密码
	 * @param roomsName
	 *            会议室名
	 */
	public MultiUserChat joinMultiUserChat(String user, String roomsName,
			String password) {
		if (XmppConnectionManager.getInstance().getConnection() == null)
			return null;
		try {
			// 使用XMPPConnection创建一个MultiUserChat窗口
			MultiUserChat muc = new MultiUserChat(XmppConnectionManager.getInstance().getConnection(), roomsName
					+ "@conference." +XmppConnectionManager.getInstance().getConnection().getServiceName());
			// 聊天室服务将会决定要接受的历史记录数量
			DiscussionHistory history = new DiscussionHistory();
			history.setMaxChars(0);
			// history.setSince(new Date());
			// 用户加入聊天室
			muc.join(user, password, history,
					SmackConfiguration.getPacketReplyTimeout());
			Log.i("MultiUserChat", "会议室【"+roomsName+"】加入成功........");
			return muc;
		} catch (XMPPException e) {
			e.printStackTrace();
			Log.i("MultiUserChat", "会议室【"+roomsName+"】加入失败........");
			return null;
		}
	}
	
	private void updateHostRoom() {
		Collection<HostedRoom> hostrooms;
		try {
			//此处localhost为服务器名称
			hostrooms = MultiUserChat.getHostedRooms(XmppConnectionManager.getInstance().getConnection(),
					"conference.localhost");
			for (HostedRoom entry : hostrooms) {
				System.out.println(entry.getName() + " - " + entry.getJid());
				roominfos.add(entry);
			}
			roomAdapter.notifyDataSetChanged();
		} catch (XMPPException e) {
			e.printStackTrace();
		}
	}
}


 

xml配置文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <RelativeLayout
        android:id="@+id/frag2_relativelayout1"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:background="#3399ff" >

            
            
        <TextView
            android:id="@+id/frag2_tv1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:text="群列表"
            android:textSize="18sp"
            android:textColor="@color/white" />

   
    </RelativeLayout>
    <ListView 
        android:id="@+id/frag02_lv1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        
        ></ListView>


</LinearLayout>
点击进去后的界面,聊天界面:

public class ActivityMultiChat extends Activity implements PacketListener {

	private TextView sc_tv1;
	private Button send;
	private EditText message;
	private ListView lv1;

	private String jid;
	private MultiUserChat muc;
	private List<String> list;
	private GroupChatAdapter adapter;

	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			if (msg.what == 1) {

				list.add((String) msg.obj);
				adapter.notifyDataSetChanged();
				lv1.setSelection(lv1.getCount() - 1);
			}

		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_activity_multi_chat);

		init();

	}

	private void init() {
		sc_tv1 = (TextView) findViewById(R.id.sc_tv1);
		send = (Button) findViewById(R.id.send);
		message = (EditText) findViewById(R.id.message);
		lv1 = (ListView) findViewById(R.id.lv1);
		jid = getIntent().getStringExtra("jid");
		String name = Util.getLeftString(jid, "@");
		muc = joinMultiUserChat("我", Util.getLeftString(jid, "@"), "111111");
		sc_tv1.setText("聊天室" + Util.getLeftString(jid, "@"));
		list = new ArrayList<String>();
		adapter = new GroupChatAdapter(this, list);
		lv1.setAdapter(adapter);
		muc.addMessageListener(this);
		send.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View view) {
				String msg = message.getText().toString();
				if (!"".equals(msg)) {
					try {
						// System.out.println("我:" + msg);
						// receiveMsg("我", msg);
						muc.sendMessage(msg);
						message.setText("");
					} catch (Exception e) {
					}
				}

			}
		});

	}

	/**
	 * 加入会议室
	 * 
	 * @param user
	 *            昵称
	 * @param password
	 *            会议室密码
	 * @param roomsName
	 *            会议室名
	 */
	public MultiUserChat joinMultiUserChat(String user, String roomsName,
			String password) {
		if (XmppConnectionManager.getInstance().getConnection() == null)
			return null;
		try {
			// 使用XMPPConnection创建一个MultiUserChat窗口
			MultiUserChat muc = new MultiUserChat(XmppConnectionManager
					.getInstance().getConnection(), roomsName
					+ "@conference."
					+ XmppConnectionManager.getInstance().getConnection()
							.getServiceName());
			// 聊天室服务将会决定要接受的历史记录数量
			DiscussionHistory history = new DiscussionHistory();
			history.setMaxChars(0);
			// history.setSince(new Date());
			// 用户加入聊天室
			muc.join(user, password, history,
					SmackConfiguration.getPacketReplyTimeout());
			Log.i("MultiUserChat", "会议室【" + roomsName + "】加入成功........");
			return muc;
		} catch (XMPPException e) {
			e.printStackTrace();
			Log.i("MultiUserChat", "会议室【" + roomsName + "】加入失败........");
			return null;
		}
	}

	/**
	 * 此处监听只针对某一个讨论组,并不监听所有,所以要监听全部的话需要for循环来使所有的讨论组被监听 String multiUserRoom =
	 * jid; MultiUserChat muc = new MultiUserChat(connection, multiUserRoom);
	 * 拿到muc实例,然后监听
	 * 
	 */

	@Override
	public void processPacket(Packet packet) {
		// TODO Auto-generated method stub
		Message message = (Message) packet;
		String body = message.getBody();
		String from = message.getFrom();
		System.out.println(from + "发送了" + body);
		android.os.Message mess = android.os.Message.obtain();
		mess.what = 1;
		mess.obj = from + ":" + body;
		handler.sendMessage(mess);
		// 在这里面更新ui会出现迟缓及更新不出来状况
		// 发送一个boardcast或者使用handler来更新ui会很好

	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		muc.removeMessageListener(this);
	}
}
xml配置文件:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <!-- 标题栏 -->

    <RelativeLayout
        android:id="@+id/am_relativelayout1"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:background="#3399ff" >

        <TextView
            android:id="@+id/sc_tv1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:text="聊天室***"
            android:textColor="@color/white"
            android:textSize="18sp" />
    </RelativeLayout>

    <!-- 底部按钮以及 编辑框 -->

    <RelativeLayout
        android:id="@+id/rl_bottom"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:background="@drawable/chat_footer_bg" >

        <ImageView
            android:id="@+id/ivPopUp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:layout_marginLeft="10dip"
            android:src="@drawable/chatting_setmode_msg_btn" />
        

        <RelativeLayout
            android:id="@+id/btn_bottom"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            >

            <Button
			    android:id="@+id/send"
                android:layout_width="60dp"
                android:layout_height="40dp"
                android:layout_alignParentRight="true"
                android:layout_centerVertical="true"
                android:layout_marginRight="10dp"
                android:background="@drawable/chat_send_btn"
                android:text="发送" />

            <EditText
                android:id="@+id/message"
                android:layout_width="fill_parent"
                android:layout_height="40dp"
                android:layout_centerVertical="true"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="10dp"
                android:layout_toLeftOf="@id/send"
                android:background="@drawable/login_edit_normal"
                android:singleLine="true"
                android:textSize="18sp" />  
 </RelativeLayout>
 </RelativeLayout>
    <!-- 聊天内容 listview -->

    <ListView
        android:id="@+id/lv1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_above="@id/rl_bottom"
        android:layout_below="@id/am_relativelayout1"
        android:cacheColorHint="#0000"
        android:divider="@null"
        android:dividerHeight="5dp"
        android:scrollbarStyle="outsideOverlay"
         android:listSelector="#00000000"
        android:stackFromBottom="true" />
   
</RelativeLayout>
这样就差不多了,不早了,下次带来的是wifi相关的代码



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值