openfire+smack收发消息

一、在openfire+smack下,制作简单的AndroidApp可以收发消息

1、openfire和smack配置这里就不赘述了,网上配置教程一堆;

2、直接开始写代码,聊天主界面布局文件chat.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:background="@drawable/chat_bg"
    android:orientation="vertical" >
    
    <TextView 
        android:id="@+id/chat_text"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        ></TextView>
    
    <LinearLayout 
      android:layout_width="fill_parent"
      android:layout_height="50dp"
      
      android:orientation="horizontal"
      android:background="@drawable/linearlayout_boder"
      >
        <ImageView 
            android:layout_width="45dp"
            android:layout_height="45dp"
            android:background="@drawable/id"/>
        <EditText
            android:id="@+id/edit_chat" 
            android:layout_width="220dp"
            android:layout_height="40dp"
            android:inputType="text"
            />
        <ImageView 
            android:layout_width="45dp"
            android:layout_height="45dp"
            android:background="@drawable/action_add"/>
        <ImageView 
            android:id="@+id/img_x"
            android:layout_width="45dp"
            android:layout_height="45dp"
            android:background="@drawable/x"/>
        
    </LinearLayout>
</LinearLayout>

3、创建连接服务器类ConnectServer.java。

package com.example.eric_jqm_chat;

import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;

/*
 *@author  Eric
 *@create date 2015-8-21上午9:22:14
 */
public class ConnectServer {
	public XMPPConnection ConnectServer() {
		ConnectionConfiguration connectionConfig = new ConnectionConfiguration(
			    "192.168.226.41", 5222);//服务器IP和默认端口号5222
		connectionConfig.setReconnectionAllowed(true);
		connectionConfig.setSendPresence(true);

		XMPPConnection con = new XMPPConnection(connectionConfig);
		try {
			con.connect();
			System.out.println("连接成功!!");
			// Toast.makeText(getApplicationContext(), "连接成功", 0).show();
		} catch (XMPPException e) {
			System.out.println("连接发生错误!!");
		}
		return con;
	}
}


4、收发用户消息的ChatActivity.java,可以在pc端使用Spark与app进行聊天。

package com.example.eric_jqm_chat;

import java.text.SimpleDateFormat;
import java.util.Date;

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



import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

/*
 *@author  Eric
 *@create date 2015-8-25下午8:51:17
 */

public class ChatActivity extends Activity {
	private TextView text_chat;
	private EditText edit_chat;
	private ImageView img_x;
	private XMPPConnection con = new ConnectServer().ConnectServer();//实例化连接对象
	private String str_text,name,password,friend,sendMsg;
	private ChatHandler handler;
	private SimpleDateFormat sf = new SimpleDateFormat("HH:mm");//获取系统时间自定义格式
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.chat);//加载布局文件
		
		text_chat = (TextView) findViewById(R.id.chat_text);
		img_x = (ImageView) findViewById(R.id.img_x);
		edit_chat = (EditText) findViewById(R.id.edit_chat);
		
		//点击图片,发送编辑框里的内容给friend用户
		img_x.setOnClickListener(new OnClickListener() {
					
			@Override
			public void onClick(View arg0) {
				sendMsg = edit_chat.getText().toString();//获取EditText中的文本		
				
				Chat chat = con.getChatManager().createChat(friend+"@"+"eric-pc", null);//建立聊天
				try {
					chat.sendMessage(sendMsg);//发送消息
				} catch (XMPPException e) {
					e.printStackTrace();
				}
				
				edit_chat.setText(null);
				
				if(str_text==null){
				  str_text = "("+sf.format(new Date())+")"+"你对他说:"+sendMsg;
				}else{
				  str_text = str_text + "\n" +"("+sf.format(new Date())+")"+"你对他说:"+sendMsg;
				}
				text_chat.setText(str_text);//将聊天内容加入到主界面TextView中
			}
		});
		
		
		
		name = getIntent().getStringExtra("name");
		password = getIntent().getStringExtra("password");//获取前一个Activity传来的用户名和密码
		try {
			con.login(name, password);//登录用户
		} catch (XMPPException e) {
			e.printStackTrace();
		}
<p>		</p><p>
</p><p><span style="white-space:pre">		</span>//登录后的用户接收消息的副线程</p>
		Thread thread = new Thread(new Runnable(){

		  @Override
		  public void run() {
		      //接收用户发来的消息
		     con.getChatManager().addChatListener(new ChatManagerListener() {
					
			@Override
			public void chatCreated(Chat chat, boolean arg1) {
			    chat.addMessageListener(new MessageListener() {
							
				@Override
				public void processMessage(Chat chat, Message msg) {
				  //截取发来信息的用户的用户名
				   friend = msg.getFrom();
				   friend = friend.substring(0, friend.indexOf("@"));
								 
				 //处理消息内容,实际上msg.getBody就是消息内容,为了显示美观,做了简单处理
				  if(msg.getBody()!= null){
				     if(str_text==null){
			               str_text ="("+sf.format(new Date())+")"+friend+"对你说:"+msg.getBody()+"\n";
					android.os.Message m = new android.os.Message();
					Bundle b= new Bundle();
					b.putString("msg", str_text);
					m.setData(b);
					handler.sendMessage(m);//将获取的消息内容发送给handler
										
				  }else{
		                       str_text =str_text+"("+sf.format(new Date())+")"+friend+"对你说:"+msg.getBody()+"\n";
					android.os.Message m = new android.os.Message();
					Bundle b= new Bundle();
					b.putString("msg", str_text);
					m.setData(b);
					handler.sendMessage(m);
				  }
			        }
								 
		              }
	                   });
                         }
                     });
				
				
				
		  }
			
		});
		
		thread.start();//启动接收消息的副线程
		handler = new ChatHandler();//实例化Handler
		
		
	}
	
	
	public class ChatHandler extends Handler{
		@Override
		public void handleMessage(android.os.Message msg) {
			super.handleMessage(msg);
			
			Bundle b = msg.getData();
			String ChatHandler = b.getString("msg");
			
			text_chat.setText(ChatHandler);//将接收到的消息设置到主界面
		}
	}
}


效果图:




你可能感兴趣的:(android,handler,smack,openfire)