1.长连接服务建立
/**
* xmpp service
* @author tanping
*
*/
public class XmppService extends Service {
public static final String TAG = "xmpp";
public static final String RESOURCE = "mobile";
//生产服务器
public static final String SERVICE_NAME ="xmpp.iuapp.cn";
public static final String SERVICE_IP ="xmpp.iuapp.cn";
public static final int SERVICE_PORT =5022;
//测试服务器
// public static final String SERVICE_NAME ="ay140514152219z";
// public static final String SERVICE_IP ="115.29.244.85";
// public static final int SERVICE_PORT =5222;
public static final String ADMIN_SERVICE ="admin";
XMPPConnection mConnection;
ChatManager mChatManager; //消息管理
OfflineMessageManager mOfflineMessageManager;//
MessageEventManager mEventManager;
ExecutorService mExecutorService;
boolean isLogin = false ;
boolean isQuit = false;
LastActivityManager mLastActivityManager ;
public long send_long_time =1;//单位s
public static final int REPORT_STATUS_INTERVAL = 15*60*1000 ;//上报状态时间间隔
@Override
public IBinder onBind(Intent arg0) {
IBinder result = null;
if (null == result)
result = new XmppServiceBinder();
return result;
}
public class XmppServiceBinder extends Binder {
public XmppService getService() {
return XmppService.this;
}
}
@Override
public void onCreate() {
super.onCreate();
//createConnect();
}
/**
* 创建连接
*/
public void createConnect(){
if (mConnection == null) { //建立连接
ConnectionConfiguration connConfig = new ConnectionConfiguration(
SERVICE_IP, SERVICE_PORT,SERVICE_NAME);
connConfig.setReconnectionAllowed(true);
connConfig.setSecurityMode(SecurityMode.disabled);
/*try {
connConfig.setCustomSSLContext(SSLContext.getDefault());
connConfig.setKeystoreType("ssl");
} catch (Exception e) {
e.printStackTrace();
}*/
mConnection = new XMPPTCPConnection(connConfig);
mConnection.addConnectionListener(connectionListener);
}
}
@Override
public void onDestroy() {
super.onDestroy();
mhHandler.removeMessages(SEND_LOGIN_REQUEST);
VPLog.d(TAG, "onDestroy()");
isLogin = false;
isQuit = true;
logout();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (mExecutorService==null) {
mExecutorService = Executors.newSingleThreadExecutor();//单例的线程池
}
createConnect();
login();
return super.onStartCommand(intent, flags, startId);
}
/**
* 登出
*/
private synchronized void logout(){
VPLog.d(TAG, "==logout===");
if (mConnection!=null) {
new Thread(){
public void run() {
try {
isLogin = false;
//注销
mConnection.disconnect();
mExecutorService.shutdownNow();//立即停止
} catch (Exception e) {
e.printStackTrace();
}finally{
mConnection = null;
}
};
}.start();
}
}
/**
* 登录
*/
private synchronized void login(){
if (mExecutorService==null) {
mExecutorService = Executors.newSingleThreadExecutor();//单例的线程池
}
if (isQuit) { //登出
try {
mhHandler.removeMessages(SEND_LOGIN_REQUEST);//清理掉
mhHandler.removeMessages(GET_ONLINE_REMIND);
} catch (Exception e) {
// TODO: handle exception
}
return ;
}
//去登陆
mExecutorService.submit(new Runnable() {
@Override
public void run() {
getConnect();
}
});
}
private synchronized void getConnect() {
try {
VPLog.d(TAG, "login");
if (isLogin && mConnection!=null && mConnection.isAuthenticated()) {
VPLog.d(TAG, "已经登录成功过");
return;
}
if (isQuit) {//登出
return ;
}
if (mConnection==null) {//已经建立
createConnect();
}
LoginUserInfoBean loginInfo = LoginStatus.getLoginInfo();
if (loginInfo == null) {
stopSelf();
return;
}
VPLog.d(TAG, "source:"+RESOURCE);
mConnection.connect();
String service = mConnection.getServiceName();
VPLog.d(TAG, "xmpp:" +loginInfo.getXmpp_user() +" pwd:" +loginInfo.getXmpp_pwd() + " - " + service);
mConnection.login(loginInfo.getXmpp_user().trim(), loginInfo.getXmpp_pwd().trim(), RESOURCE);
//mConnection.login("test", "123456", RESOURCE);
//mConnection.login("test2", "123456");
mChatManager = ChatManager.getInstanceFor(mConnection);
mChatManager.addChatListener(mPushListener);
PingManager pingManager = PingManager.getInstanceFor(mConnection);
pingManager.registerPingFailedListener(new PingFailedListener() {
@Override
public void pingFailed() {
VPLog.d(TAG, "ping fail");
isLogin = false;
login(); //重新去登陆
}
});
//pingManager.setDefaultPingInterval(60);//60s一次ping
//pingManager.setPingInterval(60);
// ChatStateManager chatStateManager = ChatStateManager.getInstance(mConnection);
Roster roster = mConnection.getRoster();
roster.addRosterListener(new RosterListener() {
@Override
public void presenceChanged(Presence arg0) {
//用户在线提醒
VPLog.d(TAG+"roster", "presenceChanged" +arg0);
VPLog.d(TAG+"roster", "presenceChanged" +arg0.toXML());
}
@Override
public void entriesUpdated(Collection arg0) {
for (String c :arg0){
VPLog.d(TAG+"roster","entriesUpdated : "+c);
}
}
@Override
public void entriesDeleted(Collection arg0) {
for (String c :arg0){
VPLog.d(TAG+"roster","entriesDeleted : "+c);
}
}
@Override
public void entriesAdded(Collection arg0) {
for (String c :arg0){
VPLog.d(TAG+"roster","entriesAdded : "+c);
}
}
});
offlineManager();
//登录
Presence presence = new Presence(Presence.Type.available);
mConnection.sendPacket(presence);
isLogin = true;
send_long_time = 1;
mhHandler.removeMessages(SEND_LOGIN_REQUEST);
//上报状态
mhHandler.sendEmptyMessage(REPORT_USER_STATUS);
}catch(SASLErrorException e){//用户名或密码错误
//需要重新登录。
VPLog.e(TAG, "用户名 或者密码错误");
e.printStackTrace();
stopSelf();
}catch (Exception e) {
e.printStackTrace();
mhHandler.sendEmptyMessage(SEND_LOGIN_REQUEST);
}
}
/**
* 欢迎回来
*/
public void welcome(){
VPLog.d(TAG, "welcome ...");
try {
MsgSharePreferenceUtil sharePreferenceUtil = new MsgSharePreferenceUtil(this, "xmpp_service");
String wel = sharePreferenceUtil.getValueForKey("welcome");
if (TextUtils.isEmpty(wel)) {
sharePreferenceUtil.addKey("welcome", "welcome");
}else {
//return
return ;
}
} catch (Exception e) {
e.printStackTrace();
}
ChatMessage message = new ChatMessage();
message.msgType = MsgType.welcome_service.getValue();
LoginUserInfoBean loginInfo = LoginStatus.getLoginInfo();
if (loginInfo == null) {
VPLog.d(TAG, "welcome ... no login ");
return;
}
UserInfo userInfo = new UserInfo();
userInfo.userId = loginInfo.getUid()+"";
message.fromUserInfo = userInfo;
VPLog.d(TAG, "welcome:"+message.toJsonObject().toString());
try {
sendPacket(ADMIN_SERVICE, message.toJsonObject().toString(),null, 201+"", null);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 上线提醒,只有成功后不再发送, 除非进入mainactivity ,
*/
public void getOnlineRemind(){
VPLog.d(TAG, "getOnlineRemind ...");
try {
MsgSharePreferenceUtil sharePreferenceUtil = new MsgSharePreferenceUtil(this, "xmpp_service");
String wel = sharePreferenceUtil.getValueForKey("get_online_remind");
if (TextUtils.isEmpty(wel)) {//第一次进来
//sharePreferenceUtil.addKey("get_online_remind", System.currentTimeMillis()+"");
}else {
//判断是否满足一小时
try {
long time = Long.parseLong(wel);
if (System.currentTimeMillis() - time >= 60*60*1000) {//大于一小时
//sharePreferenceUtil.addKey("get_online_remind", System.currentTimeMillis()+"");
}else {
VPLog.d(TAG, "online 小于一小时 remove");
mhHandler.removeMessages(GET_ONLINE_REMIND);//删除消息
VPLog.d(TAG, System.currentTimeMillis()+"");
return ;
}
} catch (Exception e) {
sharePreferenceUtil.removeKey("get_online_remind");
}
}
} catch (Exception e) {
e.printStackTrace();
return ;
}
ChatMessage message = new ChatMessage();
message.msgType = MsgType.get_online_remind.getValue();
LoginUserInfoBean loginInfo = LoginStatus.getLoginInfo();
if (loginInfo == null) {
VPLog.d(TAG, "reportStatus ... no login ");
return;
}
UserInfo userInfo = new UserInfo();
userInfo.userId = loginInfo.getUid()+"";
userInfo.userName = loginInfo.getNickname();
message.fromUserInfo = userInfo;
VPLog.d(TAG, "getOnlineRemind :"+message.toJsonObject().toString());
try {
sendPacket(ADMIN_SERVICE, message.toJsonObject().toString(),null, 202+"", new SendPacketListener() {
@Override
public void onFinish(String command, int result, String packet) {
if (result>0) {//发送成功
mhHandler.removeMessages(GET_ONLINE_REMIND);//删除消息
try {
MsgSharePreferenceUtil sharePreferenceUtil = new MsgSharePreferenceUtil(XmppService.this, "xmpp_service");
sharePreferenceUtil.addKey("get_online_remind", System.currentTimeMillis()+"");//更新时间
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 上报状态
*/
public void reportStatus(){
ChatMessage message = new ChatMessage();
message.msgType = MsgType.report_status.getValue();
message.txt = Presence.Mode.available.name();
LoginUserInfoBean loginInfo = LoginStatus.getLoginInfo();
if (loginInfo == null) {
VPLog.d(TAG, "reportStatus ... no login ");
return;
}
UserInfo userInfo = new UserInfo();
userInfo.userId = loginInfo.getUid()+"";
message.fromUserInfo = userInfo;
VPLog.d(TAG, "reportStatus:"+message.toJsonObject().toString());
try {
sendPacket(ADMIN_SERVICE, message.toJsonObject().toString(),null, 200+"", null);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
*
*/
public void lastActivityManger(){
LastActivityManager lastActivityManager = LastActivityManager.getInstanceFor(mConnection);
try {
LastActivity result = lastActivityManager.getLastActivity("test1@tp/"+RESOURCE);
VPLog.d(TAG, "last:"+result);
} catch (NoResponseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XMPPErrorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NotConnectedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 离线管理
*/
public void offlineManager(){
mOfflineMessageManager = new OfflineMessageManager(mConnection);
try {
VPLog.d(TAG+"off", "offline"+ mOfflineMessageManager.getMessageCount() ) ;
List offMsg = mOfflineMessageManager.getMessages();
for (int i = 0; i < offMsg.size(); i++) {
VPLog.d(TAG, offMsg.get(i).toXML()+"");
}
Iterator it = mOfflineMessageManager.getMessages().iterator();
// System.out.println(offlineManager.supportsFlexibleRetrieval());
System.out.println("离线消息数量: " + mOfflineMessageManager.getMessageCount());
Map> offlineMsgs = new HashMap>();
while (it.hasNext()) {
org.jivesoftware.smack.packet.Message message = it.next();
System.out
.println("收到离线消息, Received from 【" + message.getFrom()
+ "】 message: " + message.getBody());
String fromUser = message.getFrom().split("/")[0];
if (offlineMsgs.containsKey(fromUser)) {
offlineMsgs.get(fromUser).add(message);
} else {
ArrayList temp = new ArrayList();
temp.add(message);
offlineMsgs.put(fromUser, temp);
}
}
// 在这里进行处理离线消息集合......
Set keys = offlineMsgs.keySet();
Iterator offIt = keys.iterator();
while (offIt.hasNext()) {
String key = offIt.next();
ArrayList ms = offlineMsgs.get(key);
}
mOfflineMessageManager.deleteMessages();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 连接监听
*/
ConnectionListener connectionListener = new ConnectionListener() {
@Override
public void authenticated(XMPPConnection arg0) {
VPLog.i(TAG, "authenticated");
isLogin = true;
welcome();
}
@Override
public void connected(XMPPConnection arg0) {
VPLog.i(TAG, "connected");
}
@Override
public void connectionClosed() {
VPLog.i(TAG, "connectionClosed");
isLogin = false;
}
@Override
public void connectionClosedOnError(Exception arg0) {
VPLog.i(TAG, "connectionClosedOnError");
//这里就是网络不正常或者被挤掉断线激发的事件
if(arg0.getMessage()!=null && arg0.getMessage().contains("conflict")){ //被挤掉线
VPLog.e(TAG,"非正常关闭异常:"+arg0.getMessage());
//VPLog.e(TAG,"非正常关闭异常:"+arg0);
arg0.printStackTrace();
isQuit = true;
mhHandler.removeMessages(SEND_LOGIN_REQUEST);
//logout();
if (mConnection!=null) {
try {
mConnection.disconnect();
mExecutorService.shutdownNow();//立即停止
} catch (Exception e) {
e.printStackTrace();
}
}
Intent intent = new Intent(VpApplication.getInstance(),ConfictLoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
stopSelf();
}
//isLogin = false;
}
@Override
public void reconnectingIn(int arg0) {
VPLog.i(TAG, "reconnectingIn");
if (!isLogin &&!isQuit) {//没有登录
login();//去登陆
}
}
@Override
public void reconnectionFailed(Exception arg0) {
VPLog.i(TAG, "reconnectionFailed :" +arg0);
}
@Override
public void reconnectionSuccessful() {
VPLog.i(TAG, "reconnectionSuccessful");
isLogin = true;
mExecutorService.execute(new Runnable() {
@Override
public void run() {
offlineManager();
}
});
}
};
/**
* 发送 包体
* @param to
* @param packet
* @param state 可以为null 不需要状态 如果为编辑 composing 状态 packet==null
* @param command
* @param listener
*/
public synchronized void sendPacket(String to,String packet,ChatState state,String command,SendPacketListener listener){
VPLog.d(TAG, "to:"+to +" packet:"+packet);
to = to+"";
VpSendPacket vpPacket = new VpSendPacket(to,packet,state,command,listener);
SendPacketRun sendRun = new SendPacketRun(vpPacket) {
@Override
public void run() {
if (mConnection!=null && mConnection.isConnected() && mConnection.isAuthenticated()) {
VPLog.d(TAG, ""+mVpPacket);
if (mVpPacket.to.indexOf("@")<0) {
mVpPacket.to += "@"+SERVICE_NAME;
}
Chat chat = mChatManager.createChat(mVpPacket.to, null);
android.os.Message osmsg = new android.os.Message();
osmsg.obj = mVpPacket;
osmsg.what = SEND_PACKET;
try {
Message chatMessage = new Message();
chatMessage.setBody(mVpPacket.packet);
if (mVpPacket.mChatState!=null) {
chatMessage.addExtension(new ChatStateExtension(mVpPacket.mChatState));
}
chat.sendMessage(chatMessage);//发送消息
mVpPacket.result = 1;
} catch (Exception e) {
e.printStackTrace();
mVpPacket.result = -1;
}finally{
if (chat!=null) {
chat.close();
}
}
mhHandler.sendMessageDelayed(osmsg, 10);//成功
VPLog.d(TAG, ""+mVpPacket);
}else { //没有登录,去登陆
login();
android.os.Message osmsg = new android.os.Message();
osmsg.obj = mVpPacket;
osmsg.what = SEND_PACKET;
mVpPacket.result = -1;
mhHandler.sendMessage(osmsg);
}
}
};
if (mExecutorService==null) {
mExecutorService = Executors.newSingleThreadExecutor();//单例的线程池
}
mExecutorService.submit(sendRun);
}
/**
* handler处理
*/
public static final int SEND_PACKET =12345;//发送包裹
public static final int SEND_LOGIN_REQUEST=2345;//发送
public static final int REPORT_USER_STATUS=2346;//上报状态
public static final int GET_ONLINE_REMIND=2347;//获取在线提醒
public Handler mhHandler = new Handler(){
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case SEND_PACKET: //发送包裹
if (msg.obj!=null && msg.obj instanceof VpSendPacket) {
VpSendPacket vpSendPacket = (VpSendPacket) msg.obj;
if (vpSendPacket.mSendPacketListener!=null) {
vpSendPacket.mSendPacketListener.onFinish(vpSendPacket.command, vpSendPacket.result, vpSendPacket.packet);
}
};
break;
case SEND_LOGIN_REQUEST: //去登陆
VPLog.d(TAG, "try login:"+ send_long_time);
mhHandler.removeMessages(SEND_LOGIN_REQUEST);
if (send_long_time <5*60) {//单位s 5分钟
send_long_time++;
}
mhHandler.postDelayed(new Runnable() {
@Override
public void run() {
login();
}
}, send_long_time*1000);
break;
case REPORT_USER_STATUS:
mhHandler.removeMessages(REPORT_USER_STATUS);
mhHandler.sendEmptyMessageDelayed(REPORT_USER_STATUS, REPORT_STATUS_INTERVAL);
reportStatus();
break ;
case GET_ONLINE_REMIND:
mhHandler.removeMessages(GET_ONLINE_REMIND);
mhHandler.sendEmptyMessageDelayed(GET_ONLINE_REMIND, REPORT_STATUS_INTERVAL);
getOnlineRemind();//上线提醒
break ;
default:
break;
}
};
};
/**
* push 监听器
*/
ChatManagerListener mPushListener = new ChatManagerListener() {
@Override
public void chatCreated(Chat arg0, boolean arg1) {
arg0.addMessageListener(new ChatStateListener() {
@Override
public void processMessage(Chat arg0, Message arg1) {
//接收消息
mExecutorService.submit(new AcceptChatRun(arg1,XmppService.this));
//回收 chat
arg0.close();
}
@Override
public void stateChanged(Chat chat, ChatState state) {
VPLog.d(TAG, "stateChanged:"+state.name());
}
});
}
};
}
2.发送消息方法和回调处理:
发送消息包裹的封装,用来发送消息并提供监听实现状态回调
/**
*
* @author tanping
* 2015-10-30
*/
public abstract class SendPacketRun implements Runnable{
public SendPacketRun.VpSendPacket mVpPacket;
public SendPacketRun(VpSendPacket vpPacket) {
this.mVpPacket = vpPacket;
}
/**
* 发送包裹 封装
* @author tanping
* 2015-10-30
*/
public static class VpSendPacket{
public String packet; //包体
public String command;// 命令 标识
public SendPacketListener mSendPacketListener;//结果回调
public String to;
public ChatState mChatState;//聊天状态
public int result ;//结果
public VpSendPacket(String to,String packet ,String command , SendPacketListener listener){
this.packet = packet;
this.command = command;
this.mSendPacketListener = listener;
this.to = to;
}
public VpSendPacket(String to,String packet,ChatState state ,String command , SendPacketListener listener){
this.packet = packet;
this.command = command;
this.mSendPacketListener = listener;
this.to = to;
this.mChatState = state;
}
@Override
public String toString() {
return "VpSendPacket [packet=" + packet + ", command=" + command
+ ", mSendPacketListener=" + mSendPacketListener + ", to="
+ to + ", mChatState=" + mChatState + ", result=" + result
+ "]";
}
}
/**
* sendback 发送消息包体 操作
* @author tanping
*
*/
public interface SendPacketListener {
/**
* result >=0 成功 <=0失败
* @param command
* @param result
* @param packet
*/
public void onFinish(String command,int result,String packet);//完成
}
}
Bind消息服务中发送消息
/**
* 发送 包体
* @param to
* @param packet
* @param state 可以为null 不需要状态 如果为编辑 composing 状态 packet==null
* @param command
* @param listener
*/
public synchronized void sendPacket(String to,String packet,ChatState state,String command,SendPacketListener listener){
VPLog.d(TAG, "to:"+to +" packet:"+packet);
to = to+"";
VpSendPacket vpPacket = new VpSendPacket(to,packet,state,command,listener);
SendPacketRun sendRun = new SendPacketRun(vpPacket) {
@Override
public void run() {
if (mConnection!=null && mConnection.isConnected() && mConnection.isAuthenticated()) {
VPLog.d(TAG, ""+mVpPacket);
if (mVpPacket.to.indexOf("@")<0) {
mVpPacket.to += "@"+SERVICE_NAME;
}
Chat chat = mChatManager.createChat(mVpPacket.to, null);
android.os.Message osmsg = new android.os.Message();
osmsg.obj = mVpPacket;
osmsg.what = SEND_PACKET;
try {
Message chatMessage = new Message();
chatMessage.setBody(mVpPacket.packet);
if (mVpPacket.mChatState!=null) {
chatMessage.addExtension(new ChatStateExtension(mVpPacket.mChatState));
}
chat.sendMessage(chatMessage);//发送消息
mVpPacket.result = 1;
} catch (Exception e) {
e.printStackTrace();
mVpPacket.result = -1;
}finally{
if (chat!=null) {
chat.close();
}
}
mhHandler.sendMessageDelayed(osmsg, 10);//成功
VPLog.d(TAG, ""+mVpPacket);
}else { //没有登录,去登陆
login();
android.os.Message osmsg = new android.os.Message();
osmsg.obj = mVpPacket;
osmsg.what = SEND_PACKET;
mVpPacket.result = -1;
mhHandler.sendMessage(osmsg);
}
}
};
if (mExecutorService==null) {
mExecutorService = Executors.newSingleThreadExecutor();//单例的线程池
}
mExecutorService.submit(sendRun);
}
4.接收消息处理
将接收消息处理中心注册进入接收消息服务即可实现消息push推送
/**
* 消息接收中心,处理 message中心。 不阻碍读线程的性能
* @author tanping
* 2015-11-2
*/
public class AcceptChatRun implements Runnable {
public static final String TAG ="AcceptChatRun";
public Message mMessage;// 消息
public Context mContext;
public AcceptChatRun(Message message,Context context){
this.mMessage = message;
this.mContext = context;
}
@Override
public void run() {
//处理message
String from = mMessage.getFrom();
String body = mMessage.getBody();
//Log.d("chat", "msg:" +arg1);
//VPLog.d(TAG,"from=" + from + " body=" + body +" type:" +arg1.getType());
VPLog.i(TAG, mMessage.toXML()+"");
if (body!=null) {
try {
JSONObject data = new JSONObject(body);
int type = data.optInt("msg_type");
long timestamp = data.getLong("timestamp");
if (type>0) {//聊天消息
ChatMessage chatMessage = ChatMessage.parseJson(body);
chatMessage.to = mMessage.getTo();
chatMessage.loginUser = XmppUtils.getJidToUsername(chatMessage.to).toLowerCase();
chatMessage.showType = MsgShowType.in.ordinal();
chatMessage.timestamp = timestamp;
chatMessage.readStatus = MsgReadStatus.unread.ordinal();//未读
if (chatMessage.msgType == MsgType.img.getValue() || chatMessage.msgType == MsgType.maps.getValue()) {//图片
chatMessage.showType = MsgShowType.in_img.ordinal();
}
chatMessage.otherUser = chatMessage.fromUserInfo.xmppUser;
VPLog.d(TAG, ""+chatMessage);
UserInfo uInfo = UserInfoDao.getInstance(mContext).findByXmppUser(chatMessage.otherUser);
//黑名单验证,黑名单丢弃
if (uInfo !=null && uInfo.black >0) {//拉黑了
VPLog.d(TAG, "拉黑了。。。");
return;
}
//存数据库
UserInfoDao.getInstance(mContext).saveOrUpdate(chatMessage.fromUserInfo);
long chatId = ChatMessageDao.getInstance(mContext).saveOrUpdate(chatMessage);
chatMessage.id = chatId;
VPLog.i(TAG, "chat_id:"+chatId +" re:" +BroadcastType.PRIVATE_CHAT_RECEVIE +"" +XmppUtils.getJidToUsername(chatMessage.otherUser));
//在线聊天窗口
Intent intent = new Intent(BroadcastType.PRIVATE_CHAT_RECEVIE +"" + XmppUtils.getJidToUsername(chatMessage.otherUser));
intent.putExtra("chat_message", chatMessage);
mContext.sendBroadcast(intent);
//更新聊天会话
mContext.getContentResolver().update(MessageSessionProvider.CONTENT_MSG_SESSION_URI,
null, null, null);
}else {//推送消息
VPLog.d(TAG, data.toString());
long expire_time = data.getLong("expire_time");
if (expire_time >0 && System.currentTimeMillis()/1000 > expire_time ) {//过期了,扔掉
VPLog.d(TAG, "expire");
return ;
}
if (from.toLowerCase().startsWith("yh")) {//非管理员
return;
}
LoginUserInfoBean mine = LoginStatus.getLoginInfo();
if (mine == null) {
mine = new LoginUserInfoBean(mContext);
}
PushNoticeBean pushNoticeBean = PushNoticeBean.parsePushJson(data.getString("body"));
pushNoticeBean.timestamp = timestamp;
pushNoticeBean.loginId = mine.getUid()+"";
pushNoticeBean.readStatus = 0;//未读
//推送
if (pushNoticeBean.pushType == PushType.notice.getValue()) {//把通知存起来
PushNoticeBeanDao.getInstance(mContext).saveOrUpdate(pushNoticeBean);//保存 ,,发送红点广播
}else {
if (pushNoticeBean.bubbleType == BubbleType.close_app.getValue()) {//强制杀死自己
try {
LoginStatus.loginOut();
Intent intent = new Intent(mContext.getApplicationContext(),MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("command", "logout");
mContext.startActivity(intent);
//关掉服务
Intent intents = new Intent(VpApplication.getContext(), XmppService.class);
VpApplication.getInstance().stopService(intents);
} catch (Exception e) {
e.printStackTrace();
}
return;
}
//气泡存储
MsgSharePreferenceUtil msgSharePreferenceUtil = new MsgSharePreferenceUtil(mContext, "push_bubble");//气泡
if (pushNoticeBean.bubbleType == BubbleType.praise.getValue()) {
pushNoticeBean.bubbleType = BubbleType.comment.getValue();//赞和评论 都属于评论
}
String key = PushNoticeBean.BUBBLE_TYPE_KEY +pushNoticeBean.bubbleType;
int value =-1;
try {//取int值,可能不为int,比如活动的签到推送。
value = msgSharePreferenceUtil.getIntValueForKey(key);
} catch (Exception e) {
}
try {
if (value <=0) {
msgSharePreferenceUtil.addKey(key, 1);
}else {
msgSharePreferenceUtil.addKey(key, value+1);//加1
}
//{"id":1100,"status":90}
if (pushNoticeBean.bubbleType == BubbleType.join_activity.getValue()) {//参加活动
msgSharePreferenceUtil.addKey(key, pushNoticeBean.txt);//参加活动
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}finally{
PushNoticeBean.sendUpdateBroadcast(mContext);//发送红点通知
}
}
/*VPLog.d(TAG, ""+ arg1.getExtensions());
VPLog.d(TAG, arg1.getBodies()+"");*/
for ( PacketExtension ext :mMessage.getExtensions()){
//VPLog.i(TAG+"-extens:", ext.getElementName() +" -" +ext.getNamespace() +" ==");
/*try {
Chat chat = mChatManager.createChat("test2@"+SERVICE_NAME, null);
Message msg = new Message("test21");
ChatStateExtension chatStateExtension = new ChatStateExtension(ChatState.gone);
msg.addExtension(chatStateExtension);
msg.setBody("收到"+ext.getElementName());
msg.setThread(UUID.randomUUID().toString());
chat.getThreadID();
//chat.sendMessage(msg);
chat.close();
} catch (Exception e) {
e.printStackTrace();
}
*/
}
}
}