@Override public void connected(XMPPConnection connection) { LOG.info("Jabber connected"); if (mySubscribeListener == null) { mySubscribeListener = new MySubscribeListener(); connection.addPacketListener(mySubscribeListener, new PacketTypeFilter(Presence.class)); } if (myMessageListener == null) { myMessageListener = new MyMessageListener(); connection.addPacketListener(myMessageListener, new PacketTypeFilter(Message.class)); } }
@Override public boolean login() throws RemoteException { if (mAdaptee.isAuthenticated()) return true; if (!mAdaptee.isConnected()) return false; try { this.initFeatures(); // pour declarer les features xmpp qu'on // supporte PacketFilter filter = new PacketFilter() { @Override public boolean accept(Packet packet) { if (packet instanceof Presence) { Presence pres = (Presence) packet; if (pres.getType() == Presence.Type.subscribe) return true; } return false; } }; mAdaptee.addPacketListener(mSubscribePacketListener, filter); filter = new PacketTypeFilter(PingExtension.class); mAdaptee.addPacketListener(mPingListener, filter); mAdaptee.login(mLogin, mPassword, mResource); mUserInfo = new UserInfo(mAdaptee.getUser()); mChatManager = new BeemChatManager(mAdaptee.getChatManager(), mService, mAdaptee.getRoster()); // nikita: I commented this line because of the logs provided in // http://www.beem-project.com/issues/321 // Also, since the privacylistmanager isn't finished and used, it will be safer to not // initialize it // mPrivacyListManager = new // PrivacyListManagerAdapter(PrivacyListManager.getInstanceFor(mAdaptee)); mService.initJingle(mAdaptee); discoverServerFeatures(); mRoster = new RosterAdapter(mAdaptee.getRoster(), mService, mAvatarManager); mApplication.setConnected(true); int mode = mPref.getInt(BeemApplication.STATUS_KEY, 0); String status = mPref.getString(BeemApplication.STATUS_TEXT_KEY, ""); changeStatus(mode, status); return true; } catch (XMPPException e) { Log.e(TAG, "Error while connecting", e); mErrorMsg = mService.getString(R.string.error_login_authentication); return false; } }
/** * Creates a file transfer manager to initiate and receive file transfers. * * @param connection The XMPPConnection that the file transfers will use. */ private FileTransferManager(XMPPConnection connection) { super(connection); this.fileTransferNegotiator = FileTransferNegotiator.getInstanceFor(connection); connection.addPacketListener( new PacketListener() { public void processPacket(Packet packet) { StreamInitiation si = (StreamInitiation) packet; final FileTransferRequest request = new FileTransferRequest(FileTransferManager.this, si); for (final FileTransferListener listener : listeners) { // Those listeners need to be called asynchronously, in // order to not block further processing of incoming // stanzas. They also may send further requests, whose // responses are not processed if we do not call them // asynchronously. Async.go( new Runnable() { public void run() { listener.fileTransferRequest(request); } }); } } }, new AndFilter(new PacketTypeFilter(StreamInitiation.class), IQTypeFilter.SET)); }
@Override public void run() { if (connection != null && connection.isConnected()) { disconnect = true; Ping ping = new Ping(); ping.setFrom(ApplicationUtil.getXmppConnectionUserName(PreferencesUtil.getMyId())); try { connection.sendPacket(ping); } catch (Exception e) { clearTimer(); // Application.getNotificationManager().startNotificationService(); } connection.addPacketListener( new PacketListener() { public void processPacket(Packet packet) { disconnect = false; } }, new IQTypeFilter(Type.RESULT)); try { Thread.sleep(PERIOD); } catch (InterruptedException e) { } if (disconnect) { LaijiaoliuApp.getNotificationManager().startNotificationService(); clearTimer(); } } }
/** Creates a destination for a service that receives XMPP messages. */ public Destination getDestination(EndpointInfo endpointInfo) throws IOException { // The node name is the full name of the service. String nodeName = endpointInfo.getService().getName().toString(); pepProvider.registerPEPParserExtension(nodeName, soapProvider); PEPDestination dest = new PEPDestination(endpointInfo); try { XMPPConnection conn = destinationConnectionFactory.login(endpointInfo); // Advertise interest in receiving information. ServiceDiscoveryManager disco = ServiceDiscoveryManager.getInstanceFor(conn); disco.addFeature(nodeName + "+notify"); // Create destination. dest.setXmppConnection(conn); conn.addPacketListener( dest, new PacketExtensionFilter("event", "http://jabber.org/protocol/pubsub#event")); } catch (XMPPException e) { throw new IOException(e); } return dest; }
/** * Register a listener for item publication events. This listener will get called whenever an item * is published to this node. * * @param listener The handler for the event */ @SuppressWarnings("unchecked") public void addItemEventListener(@SuppressWarnings("rawtypes") ItemEventListener listener) { PacketListener conListener = new ItemEventTranslator(listener); itemEventToListenerMap.put(listener, conListener); con.addPacketListener( conListener, new EventContentFilter(EventElementType.items.toString(), "item")); }
/** * Creates a last activity manager to response last activity requests. * * @param connection The XMPPConnection that the last activity requests will use. */ private LastActivityManager(XMPPConnection connection) { this.connection = connection; // Listen to all the sent messages to reset the idle time on each one connection.addPacketWriterListener( new PacketListener() { public void processPacket(Packet packet) { resetIdleTime(); } }, null); // Register a listener for a last activity query connection.addPacketListener( new PacketListener() { public void processPacket(Packet packet) { LastActivity message = new LastActivity(); message.setType(IQ.Type.RESULT); message.setTo(packet.getFrom()); message.setFrom(packet.getTo()); message.setPacketID(packet.getPacketID()); message.setLastActivity(getIdleTime()); LastActivityManager.this.connection.sendPacket(message); } }, new AndFilter(new IQTypeFilter(IQ.Type.GET), new PacketTypeFilter(LastActivity.class))); }
@Override public void run() { if (xmppManager.isConnected() && !xmppManager.isAuthenticated() && !xmppManager.isRunning()) { XMPPConnection connection = xmppManager.getConnection(); try { xmppManager.setRunning(true); xmppManager .getConnection() .login(xmppManager.getUsername(), xmppManager.getPassword(), XMPP_RESOURCE_NAME); Log.d(LOG_TAG, "Loggedn in successfully"); PacketFilter packetFilter = new PacketTypeFilter(NotificationIQ.class); // packet listener PacketListener packetListener = xmppManager.getNotificationPacketListener(); connection.addPacketListener(packetListener, packetFilter); callback.onSuccess(); } catch (Exception e) { Log.e(LOG_TAG, "LoginTask.call()... other error"); Log.e(LOG_TAG, "Failed to login to xmpp server. Caused by: " + e.getMessage(), e); callback.onFailed("LoginTask.call()... other error"); } finally { xmppManager.setRunning(false); } } else { Log.w(LOG_TAG, "XMPP is not connected or is running or is authenticated"); callback.onFailed("XMPP is not connected or is running or is authenticated"); } }
/** * Called by Settings dialog when a connection is establised with the XMPP server * * @param connection */ public void setConnection(XMPPConnection connection) { this.connection = 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); } }
/** * Register an listener for item delete events. This listener gets called whenever an item is * deleted from the node. * * @param listener The handler for the event */ public void addItemDeleteListener(ItemDeleteListener listener) { PacketListener delListener = new ItemDeleteTranslator(listener); itemDeleteToListenerMap.put(listener, delListener); EventContentFilter deleteItem = new EventContentFilter(EventElementType.items.toString(), "retract"); EventContentFilter purge = new EventContentFilter(EventElementType.purge.toString()); con.addPacketListener(delListener, new OrFilter(deleteItem, purge)); }
/** * Registers this Manager's listener with <tt>connection</tt>. * * @param connection the connection that we'd like this manager to register with. */ public void addPacketListener(XMPPConnection connection) { PacketFilter filter = new AndFilter( new PacketTypeFilter(Presence.class), new PacketExtensionFilter( CapsPacketExtension.ELEMENT_NAME, CapsPacketExtension.NAMESPACE)); connection.addPacketListener(new CapsPacketListener(), filter); }
@Override public void run() { Log.i(LOGTAG, "RegisterTask.run()..."); final XmppManager xmppManager = getXmppManager(); if (!xmppManager.isRegistered()) { String uuid = Util.getDeviceUUID(xmppManager.getContext()); final String newUsername = uuid; final String newPassword = uuid; Registration registration = new Registration(); PacketFilter packetFilter = new AndFilter( new PacketIDFilter(registration.getPacketID()), new PacketTypeFilter(IQ.class)); PacketListener packetListener = new PacketListener() { public void processPacket(Packet packet) { Log.d("RegisterTask.PacketListener", "processPacket()....."); Log.d("RegisterTask.PacketListener", "packet=" + packet.toXML()); if (packet instanceof IQ) { IQ response = (IQ) packet; if (response.getType() == IQ.Type.ERROR) { if (!response.getError().toString().contains("409")) { Log.e( LOGTAG, "Unknown error while registering XMPP account! " + response.getError().getCondition()); } } else if (response.getType() == IQ.Type.RESULT) { xmppManager.setUsername(newUsername); xmppManager.setPassword(newPassword); Log.d(LOGTAG, "username="******"password="******"Account registered successfully"); xmppManager.runTask(); } } } }; XMPPConnection connection = xmppManager.getConnection(); connection.addPacketListener(packetListener, packetFilter); registration.setType(IQ.Type.SET); registration.addAttribute("username", newUsername); registration.addAttribute("password", newPassword); connection.sendPacket(registration); } else { Log.i(LOGTAG, "Account registered already"); xmppManager.runTask(); } }
private void onConnectionEstablished() { if (state != State.CONNECTED) { processOfflineMessages(); try { con.sendPacket(new Presence(Presence.Type.available)); } catch (NotConnectedException e) { } contactHelper = new SmackContactHelper(context, con); vCardHelper = new SmackVCardHelper(context, con); con.addPacketListener(messagePacketListener, new MessageTypeFilter(Message.Type.chat)); con.addPacketListener(presencePacketListener, new PacketTypeFilter(Presence.class)); con.addConnectionListener(createConnectionListener()); setState(State.CONNECTED); } }
/** * Register a listener for configuration events. This listener will get called whenever the node's * configuration changes. * * @param listener The handler for the event */ public void addConfigurationListener(NodeConfigListener listener) { PacketListener conListener = new NodeConfigTranslator(listener); configEventToListenerMap.put(listener, conListener); con.addPacketListener( conListener, new EventContentFilter(EventElementType.configuration.toString())); }
public void run() throws XMPPException, IOException, InterruptedException { logger.debug("Trying to connect to " + host + ":" + port); ConnectionConfiguration configuration = new ConnectionConfiguration(host, port, "gmail.com"); final XMPPConnection connection = new XMPPConnection(configuration); connection.connect(); logger.debug("...connected"); SASLAuthentication.supportSASLMechanism("PLAIN", 0); logger.debug("Trying to log in with credentials " + login + ":" + password); connection.login(login, password, "MyXmppBot"); logger.debug("...logged in"); final Process process = Runtime.getRuntime().exec("/bin/bash"); final InputStream inputStream = process.getInputStream(); final OutputStream outputStream = process.getOutputStream(); Thread inputThread = new Thread( new Runnable() { @Override public void run() { InputStreamReader inputStreamReader = new InputStreamReader(inputStream); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); try { while (true) { String line = bufferedReader.readLine(); Message message = new Message(to); message.setBody(line); connection.sendPacket(message); } } catch (IOException e) { e.printStackTrace(); } } }); inputThread.start(); final PrintWriter commandWriter = new PrintWriter(outputStream, true); PacketListener listener = new PacketListener() { @Override public void processPacket(Packet packet) { if (packet instanceof Message) { Message message = (Message) packet; to = message.getFrom(); String command = message.getBody(); if (command != null) { logger.debug("Command received:" + command); if (command.equalsIgnoreCase("exit")) { process.destroy(); System.exit(0); } else { commandWriter.println(command); } } } } }; PacketFilter filter = new FromContainsFilter("carlos.prados"); Thread.sleep(1000); connection.addPacketListener(listener, null); }
/** * Connects to GCM Cloud Connection Server using the supplied credentials. * * @throws XMPPException */ public void connect() throws XMPPException { config = new ConnectionConfiguration(Properties.GCM_SERVER, Properties.GCM_PORT); config.setSecurityMode(SecurityMode.enabled); config.setReconnectionAllowed(true); config.setRosterLoadedAtLogin(false); config.setSendPresence(false); config.setSocketFactory(SSLSocketFactory.getDefault()); // NOTE: Set to true to launch a window with information about packets sent and received config.setDebuggerEnabled(false); // -Dsmack.debugEnabled=true XMPPConnection.DEBUG_ENABLED = false; connection = new XMPPConnection(config); connection.connect(); connection.addConnectionListener( new ConnectionListener() { public void reconnectionSuccessful() { logger.info("Reconnecting.."); } public void reconnectionFailed(Exception e) { logger.log(Level.INFO, "Reconnection failed.. ", e); } public void reconnectingIn(int seconds) { logger.log(Level.INFO, "Reconnecting in %d secs", seconds); } public void connectionClosedOnError(Exception e) { logger.log(Level.INFO, "Connection closed on error."); } public void connectionClosed() { logger.info("Connection closed."); } }); // Handle incoming packets connection.addPacketListener( new PacketListener() { public void processPacket(Packet packet) { logger.log(Level.INFO, "Received: " + packet.toXML()); Message incomingMessage = (Message) packet; GcmPacketExtension gcmPacket = (GcmPacketExtension) incomingMessage.getExtension(Properties.GCM_NAMESPACE); String json = gcmPacket.getJson(); try { @SuppressWarnings("unchecked") Map<String, Object> jsonObject = (Map<String, Object>) JSONValue.parseWithException(json); // present for "ack"/"nack", null otherwise Object messageType = jsonObject.get("message_type"); if (messageType == null) { // Normal upstream data message handleIncomingDataMessage(jsonObject); // Send ACK to CCS String messageId = jsonObject.get("message_id").toString(); String from = jsonObject.get("from").toString(); String ack = createJsonAck(from, messageId); send(ack); } else if ("ack".equals(messageType.toString())) { // Process Ack handleAckReceipt(jsonObject); } else if ("nack".equals(messageType.toString())) { // Process Nack handleNackReceipt(jsonObject); } else { logger.log(Level.WARNING, "Unrecognized message type (%s)", messageType.toString()); } } catch (ParseException e) { logger.log(Level.SEVERE, "Error parsing JSON " + json, e); } catch (Exception e) { logger.log(Level.SEVERE, "Couldn't send echo.", e); } } }, new PacketTypeFilter(Message.class)); // Log all outgoing packets connection.addPacketInterceptor( new PacketInterceptor() { public void interceptPacket(Packet packet) { logger.log(Level.INFO, "Sent: {0}", packet.toXML()); } }, new PacketTypeFilter(Message.class)); connection.login(Properties.userName, Properties.password); }
/** * Creates a new ServiceDiscoveryManager for a given XMPPConnection. This means that the service * manager will respond to any service discovery request that the connection may receive. * * @param connection the connection to which a ServiceDiscoveryManager is going to be created. */ private ServiceDiscoveryManager(XMPPConnection connection) { super(connection); addFeature(DiscoverInfo.NAMESPACE); addFeature(DiscoverItems.NAMESPACE); // Listen for disco#items requests and answer with an empty result PacketListener packetListener = new PacketListener() { public void processPacket(Packet packet) throws NotConnectedException { DiscoverItems discoverItems = (DiscoverItems) packet; DiscoverItems response = new DiscoverItems(); response.setType(IQ.Type.result); response.setTo(discoverItems.getFrom()); response.setPacketID(discoverItems.getPacketID()); response.setNode(discoverItems.getNode()); // Add the defined items related to the requested node. Look for // the NodeInformationProvider associated with the requested node. NodeInformationProvider nodeInformationProvider = getNodeInformationProvider(discoverItems.getNode()); if (nodeInformationProvider != null) { // Specified node was found, add node items response.addItems(nodeInformationProvider.getNodeItems()); // Add packet extensions response.addExtensions(nodeInformationProvider.getNodePacketExtensions()); } else if (discoverItems.getNode() != null) { // Return <item-not-found/> error since client doesn't contain // the specified node response.setType(IQ.Type.error); response.setError(new XMPPError(XMPPError.Condition.item_not_found)); } connection().sendPacket(response); } }; connection.addPacketListener(packetListener, GET_DISCOVER_ITEMS); // Listen for disco#info requests and answer the client's supported features // To add a new feature as supported use the #addFeature message packetListener = new PacketListener() { public void processPacket(Packet packet) throws NotConnectedException { DiscoverInfo discoverInfo = (DiscoverInfo) packet; // Answer the client's supported features if the request is of the GET type DiscoverInfo response = new DiscoverInfo(); response.setType(IQ.Type.result); response.setTo(discoverInfo.getFrom()); response.setPacketID(discoverInfo.getPacketID()); response.setNode(discoverInfo.getNode()); // Add the client's identity and features only if "node" is null // and if the request was not send to a node. If Entity Caps are // enabled the client's identity and features are may also added // if the right node is chosen if (discoverInfo.getNode() == null) { addDiscoverInfoTo(response); } else { // Disco#info was sent to a node. Check if we have information of the // specified node NodeInformationProvider nodeInformationProvider = getNodeInformationProvider(discoverInfo.getNode()); if (nodeInformationProvider != null) { // Node was found. Add node features response.addFeatures(nodeInformationProvider.getNodeFeatures()); // Add node identities response.addIdentities(nodeInformationProvider.getNodeIdentities()); // Add packet extensions response.addExtensions(nodeInformationProvider.getNodePacketExtensions()); } else { // Return <item-not-found/> error since specified node was not found response.setType(IQ.Type.error); response.setError(new XMPPError(XMPPError.Condition.item_not_found)); } } connection().sendPacket(response); } }; connection.addPacketListener(packetListener, GET_DISCOVER_INFO); }
/** * Connects to GCM Cloud Connection Server using the supplied credentials. * * @param senderId Your GCM project number * @param apiKey API Key of your project */ public void connect(long senderId, String apiKey) throws XMPPException, IOException, SmackException { ConnectionConfiguration config = new ConnectionConfiguration(GCM_SERVER, GCM_PORT); config.setSecurityMode(SecurityMode.enabled); config.setReconnectionAllowed(true); config.setRosterLoadedAtLogin(false); config.setSendPresence(false); config.setSocketFactory(SSLSocketFactory.getDefault()); connection = new XMPPTCPConnection(config); connection.connect(); connection.addConnectionListener(new LoggingConnectionListener()); // Handle incoming packets connection.addPacketListener( new PacketListener() { @Override public void processPacket(Packet packet) { logger.log(Level.INFO, "Received: " + packet.toXML()); Message incomingMessage = (Message) packet; GcmPacketExtension gcmPacket = (GcmPacketExtension) incomingMessage.getExtension(GCM_NAMESPACE); String json = gcmPacket.getJson(); try { @SuppressWarnings("unchecked") Map<String, Object> jsonObject = (Map<String, Object>) JSONValue.parseWithException(json); // present for "ack"/"nack", null otherwise Object messageType = jsonObject.get("message_type"); if (messageType == null) { // Normal upstream data message handleUpstreamMessage(jsonObject); // Send ACK to CCS String messageId = (String) jsonObject.get("message_id"); String from = (String) jsonObject.get("from"); String ack = createJsonAck(from, messageId); send(ack); } else if ("ack".equals(messageType.toString())) { // Process Ack handleAckReceipt(jsonObject); } else if ("nack".equals(messageType.toString())) { // Process Nack handleNackReceipt(jsonObject); } else if ("control".equals(messageType.toString())) { // Process control message handleControlMessage(jsonObject); } else { logger.log(Level.WARNING, "Unrecognized message type (%s)", messageType.toString()); } } catch (ParseException e) { logger.log(Level.SEVERE, "Error parsing JSON " + json, e); } catch (Exception e) { logger.log(Level.SEVERE, "Failed to process packet", e); } } }, new PacketTypeFilter(Message.class)); // Log all outgoing packets connection.addPacketInterceptor( new PacketInterceptor() { @Override public void interceptPacket(Packet packet) { logger.log(Level.INFO, "Sent: {0}", packet.toXML()); } }, new PacketTypeFilter(Message.class)); connection.login(senderId + "@gcm.googleapis.com", apiKey); }
/** * Called by Settings dialog when a connection is establised with the XMPP server * * @param connection */ public void setConnection(XMPPConnection connection) { Util.connection = 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() { @Override public void processPacket(Packet packet) { Message message = (Message) packet; if (message.getBody() != null) { String fromName = StringUtils.parseBareAddress(message.getFrom()); DataBaseHandler datebasehandler = new DataBaseHandler(RegisterNormal.this); ConversationsModel checkConversations = new ConversationsModel(); checkConversations = datebasehandler.checkConversationID(fromName); if (checkConversations == null) { ConversationsModel conversions = new ConversationsModel(); conversions.setLast_message(message.getBody()); conversions.setEnd_time("endtime"); conversions.setLast_message_direction("in"); conversions.setLogin_user_display_name(fromName); conversions.setLogin_user_id(Integer.parseInt(Util.USER_ID)); conversions.setLogin_user_jid(Util.CHAT_LOGIN_JID); conversions.setLogin_user_resource("mobile"); conversions.setWith_user_display_name(fromName); conversions.setWith_user_id(0); conversions.setWith_user_jid(fromName); conversions.setWith_user_profilepicurl("message.getFrom()"); conversions.setWith_user_resource("mobile"); conversions.setStart_time("starttime"); conversions.setMessage_iseen("no"); conversions.setMessage_isseen_count("1"); datebasehandler.insertConversions(conversions); // // getting the latest conversation id checkConversations = datebasehandler.checkConversationID(fromName); if (checkConversations == null) { } else { ConversationsMessagesModel messageModel = new ConversationsMessagesModel(); messageModel.setConvmessage_type("Chat"); messageModel.setConvmessage_direction("in"); messageModel.setConvmessage_time("time"); messageModel.setConvmessage_message(message.getBody()); messageModel.setConversation_id(checkConversations.getConversation_id()); if (isApplicationSentToBackground(context)) { NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(RegisterNormal.this) .setSmallIcon(R.drawable.ic_launcher) .setContentTitle(checkConversations.getWith_user_display_name()) .setContentText(1 + " new messages"); // Creates an explicit intent for an Activity in your app Intent resultIntent = new Intent(RegisterNormal.this, ChatConversationsActivity.class); resultIntent.putExtra( "Conversation_Name", checkConversations.getWith_user_display_name()); resultIntent.putExtra( "Conversations_Name_Image", checkConversations.getWith_user_profilepicurl()); resultIntent.putExtra( "Connversation_ID", checkConversations.getConversation_id()); resultIntent.putExtra( "Connversation_JID", checkConversations.getWith_user_jid()); // The stack builder object will contain an artificial back stack for the // started Activity. // This ensures that navigating backward from the Activity leads out of // your application to the Home screen. TaskStackBuilder stackBuilder = TaskStackBuilder.create(RegisterNormal.this); // Adds the back stack for the Intent (but not the Intent itself) stackBuilder.addParentStack(SplashScreen.class); // Adds the Intent that starts the Activity to the top of the stack stackBuilder.addNextIntent(resultIntent); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); mBuilder.setContentIntent(resultPendingIntent); mBuilder.setAutoCancel(true); mBuilder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI); // Vibration mBuilder.setVibrate(new long[] {1000, 1000, 1000, 1000, 1000}); // LED mBuilder.setLights(Color.RED, 3000, 3000); NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); // mId allows you to update the notification later on. mNotificationManager.notify(101, mBuilder.build()); } try { datebasehandler.insertConversionsMessages(messageModel); } catch (Exception e) { } finally { datebasehandler.close(); } } } else { ConversationsMessagesModel messageModel = new ConversationsMessagesModel(); messageModel.setConvmessage_type("Chat"); messageModel.setConvmessage_direction("in"); messageModel.setConvmessage_time("time"); messageModel.setConvmessage_message(message.getBody()); messageModel.setConversation_id(checkConversations.getConversation_id()); try { datebasehandler.insertConversionsMessages(messageModel); int getCount = Integer.valueOf(checkConversations.getMessage_isseen_count()); getCount = getCount + 1; datebasehandler.updateLastMessageinConversations( String.valueOf(checkConversations.getConversation_id()), message.getBody(), "time", "in", "no", Integer.toString(getCount)); int countformessage = Integer.parseInt(checkConversations.getMessage_isseen_count()) + 1; if (isApplicationSentToBackground(context)) { NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(RegisterNormal.this) .setSmallIcon(R.drawable.ic_launcher) .setContentTitle(checkConversations.getWith_user_display_name()) .setContentText(countformessage + " new messages"); // Creates an explicit intent for an Activity in your app Intent resultIntent = new Intent(RegisterNormal.this, ChatConversationsActivity.class); resultIntent.putExtra( "Conversation_Name", checkConversations.getWith_user_display_name()); resultIntent.putExtra( "Conversations_Name_Image", checkConversations.getWith_user_profilepicurl()); resultIntent.putExtra( "Connversation_ID", checkConversations.getConversation_id()); resultIntent.putExtra( "Connversation_JID", checkConversations.getWith_user_jid()); // The stack builder object will contain an artificial back stack for the // started Activity. // This ensures that navigating backward from the Activity leads out of // your application to the Home screen. TaskStackBuilder stackBuilder = TaskStackBuilder.create(RegisterNormal.this); // Adds the back stack for the Intent (but not the Intent itself) stackBuilder.addParentStack(SplashScreen.class); // Adds the Intent that starts the Activity to the top of the stack stackBuilder.addNextIntent(resultIntent); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); mBuilder.setContentIntent(resultPendingIntent); mBuilder.setAutoCancel(true); mBuilder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI); // Vibration mBuilder.setVibrate(new long[] {1000, 1000, 1000, 1000, 1000}); // LED mBuilder.setLights(Color.RED, 3000, 3000); NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); // mId allows you to update the notification later on. mNotificationManager.notify(101, mBuilder.build()); } } catch (Exception e) { } finally { datebasehandler.close(); } } Util.IncomingChatMessage = true; } } }, filter); } }
/** 登陆XMPP服务器 */ public boolean login() throws RemoteException { // 未建立XMPP连接 if (!connection.isConnected()) { return false; } // 应经登陆过 if (connection.isAuthenticated()) { return true; } else { // 开始登陆 try { connection.login(account, password, imService.getString(R.string.app_name)); if (messageListener == null) { messageListener = new MessageListener(); } // 添加消息监听器 connection.addPacketListener(messageListener, new PacketTypeFilter(Message.class)); Roster roster = connection.getRoster(); if (rosterListener == null) { rosterListener = new IMClientRosterListener(); } // 添加花名册监听器 roster.addRosterListener(rosterListener); // 获取花名册 if (roster != null && roster.getEntries().size() > 0) { Uri uri = null; for (RosterEntry entry : roster.getEntries()) { // 获取联系人名片信息 VCard vCard = new VCard(); vCard.load(connection, entry.getUser()); // 用户名称 String userName = StringUtils.parseName(entry.getUser()); // 用户备注 String remarks = entry.getName(); // 通讯录的名称 String name = ""; // 名称与备注判断 if (userName.equals(remarks) && vCard != null) { // 使用联系人的昵称 name = vCard.getNickName(); } else { // 使用备注 name = remarks; } if (vCard != null) { IM.saveAvatar(vCard.getAvatar(), StringUtils.parseName(entry.getUser())); } ContentValues values = new ContentValues(); values.put(ContactsProvider.ContactColumns.ACCOUNT, entry.getUser()); values.put(ContactsProvider.ContactColumns.NAME, name); String sortStr = PinYin.getPinYin(name); values.put(ContactsProvider.ContactColumns.SORT, sortStr); values.put( ContactsProvider.ContactColumns.SECTION, sortStr.substring(0, 1).toUpperCase(Locale.ENGLISH)); // 储存联系人 if (imService .getContentResolver() .update( ContactsProvider.CONTACT_URI, values, ContactsProvider.ContactColumns.ACCOUNT + " = ?", new String[] {entry.getUser()}) == 0) { uri = imService.getContentResolver().insert(ContactsProvider.CONTACT_URI, values); } } // 发生改变,通知刷新 if (uri != null) { imService.getContentResolver().notifyChange(uri, null); } } } catch (XMPPException e) { e.printStackTrace(); } catch (SmackException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return true; } }
/** * Initializes the packet listeners of the connection that will answer to any service discovery * request. */ private void init() { // Register the new instance and associate it with the connection instances.put(connection, this); // Add a listener to the connection that removes the registered instance when // the connection is closed connection.addConnectionListener( new ConnectionListener() { public void connectionClosed() { // Unregister this instance since the connection has been closed instances.remove(connection); } public void connectionClosedOnError(Exception e) { // ignore } public void reconnectionFailed(Exception e) { // ignore } public void reconnectingIn(int seconds) { // ignore } public void reconnectionSuccessful() { // ignore } }); // Listen for disco#items requests and answer with an empty result PacketFilter packetFilter = new PacketTypeFilter(DiscoverItems.class); PacketListener packetListener = new PacketListener() { public void processPacket(Packet packet) { DiscoverItems discoverItems = (DiscoverItems) packet; // Send back the items defined in the client if the request is of type GET if (discoverItems != null && discoverItems.getType() == IQ.Type.GET) { DiscoverItems response = new DiscoverItems(); response.setType(IQ.Type.RESULT); response.setTo(discoverItems.getFrom()); response.setPacketID(discoverItems.getPacketID()); response.setNode(discoverItems.getNode()); // Add the defined items related to the requested node. Look for // the NodeInformationProvider associated with the requested node. NodeInformationProvider nodeInformationProvider = getNodeInformationProvider(discoverItems.getNode()); if (nodeInformationProvider != null) { // Specified node was found List<DiscoverItems.Item> items = nodeInformationProvider.getNodeItems(); if (items != null) { for (DiscoverItems.Item item : items) { response.addItem(item); } } } else if (discoverItems.getNode() != null) { // Return <item-not-found/> error since client doesn't contain // the specified node response.setType(IQ.Type.ERROR); response.setError(new XMPPError(XMPPError.Condition.item_not_found)); } connection.sendPacket(response); } } }; connection.addPacketListener(packetListener, packetFilter); // Listen for disco#info requests and answer the client's supported features // To add a new feature as supported use the #addFeature message packetFilter = new PacketTypeFilter(DiscoverInfo.class); packetListener = new PacketListener() { public void processPacket(Packet packet) { DiscoverInfo discoverInfo = (DiscoverInfo) packet; // Answer the client's supported features if the request is of the GET type if (discoverInfo != null && discoverInfo.getType() == IQ.Type.GET) { DiscoverInfo response = new DiscoverInfo(); response.setType(IQ.Type.RESULT); response.setTo(discoverInfo.getFrom()); response.setPacketID(discoverInfo.getPacketID()); response.setNode(discoverInfo.getNode()); // Add the client's identity and features only if "node" is null if (discoverInfo.getNode() == null) { // Set this client identity DiscoverInfo.Identity identity = new DiscoverInfo.Identity("client", getIdentityName()); identity.setType(getIdentityType()); response.addIdentity(identity); // Add the registered features to the response synchronized (features) { for (Iterator<String> it = getFeatures(); it.hasNext(); ) { response.addFeature(it.next()); } } } else { // Disco#info was sent to a node. Check if we have information of the // specified node NodeInformationProvider nodeInformationProvider = getNodeInformationProvider(discoverInfo.getNode()); if (nodeInformationProvider != null) { // Node was found. Add node features List<String> features = nodeInformationProvider.getNodeFeatures(); if (features != null) { for (String feature : features) { response.addFeature(feature); } } // Add node identities List<DiscoverInfo.Identity> identities = nodeInformationProvider.getNodeIdentities(); if (identities != null) { for (DiscoverInfo.Identity identity : identities) { response.addIdentity(identity); } } } else { // Return <item-not-found/> error since specified node was not found response.setType(IQ.Type.ERROR); response.setError(new XMPPError(XMPPError.Condition.item_not_found)); } } connection.sendPacket(response); } } }; connection.addPacketListener(packetListener, packetFilter); }
private void addListeners() { connection.addConnectionListener( new org.jivesoftware.smack.ConnectionListener() { public void authenticated(XMPPConnection connection) { // do nothing } public void connected(XMPPConnection connection) { // do nothing } public void connectionClosed() { for (final ConnectionListener l : connectionListeners) { l.connectionClosed(); } } public void connectionClosedOnError(Exception e) { for (final ConnectionListener l : connectionListeners) { l.connectionClosedOnError(e); } } public void reconnectingIn(int seconds) { for (final ConnectionListener l : connectionListeners) { l.reconnectingIn(seconds); } } public void reconnectionFailed(Exception e) { for (final ConnectionListener l : connectionListeners) { l.reconnectionFailed(e); } } public void reconnectionSuccessful() { updateStatus(); for (final ConnectionListener l : connectionListeners) { l.reconnectionSuccessful(); } } }); connection .getRoster() .addRosterListener(leagueRosterListener = new LeagueRosterListener(this, connection)); connection.addPacketListener( leaguePacketListener = new LeaguePacketListener(this, connection), new PacketFilter() { public boolean accept(Packet packet) { if (packet instanceof Presence) { final Presence presence = (Presence) packet; if (presence.getType().equals(Presence.Type.subscribed) || presence.getType().equals(Presence.Type.subscribe) || presence.getType().equals(Presence.Type.unsubscribed) || presence.getType().equals(Presence.Type.unsubscribe)) { return true; } } return false; } }); ChatManager.getInstanceFor(connection) .addChatListener( new ChatManagerListener() { @Override public void chatCreated(Chat c, boolean locally) { final Friend friend = getFriendById(c.getParticipant()); if (friend != null) { c.addMessageListener( new MessageListener() { @Override public void processMessage(Chat chat, Message msg) { for (final ChatListener c : chatListeners) { if (msg.getType() == Message.Type.chat) { c.onMessage(friend, msg.getBody()); } } } }); } } }); }
@Override public void connectionCreated(XMPPConnection connection) { if (XMPPFriendConnectionImpl.this.connection != connection) { return; } if (LOG.isDebugEnabled()) { LOG.debug("connection created for " + connection.toString()); } connection.addConnectionListener(this); synchronized (ProviderManager.getInstance()) { if (ProviderManager.getInstance().getIQProvider("address", "jabber:iq:lw-address") == null) { ProviderManager.getInstance() .addIQProvider( "address", "jabber:iq:lw-address", new AddressIQProvider(addressFactory)); } if (ProviderManager.getInstance() .getIQProvider("file-transfer", "jabber:iq:lw-file-transfer") == null) { ProviderManager.getInstance() .addIQProvider( "file-transfer", "jabber:iq:lw-file-transfer", FileTransferIQ.getIQProvider()); } if (ProviderManager.getInstance().getIQProvider("auth-token", "jabber:iq:lw-auth-token") == null) { ProviderManager.getInstance() .addIQProvider("auth-token", "jabber:iq:lw-auth-token", new AuthTokenIQProvider()); } if (ProviderManager.getInstance() .getIQProvider("library-changed", "jabber:iq:lw-lib-change") == null) { ProviderManager.getInstance() .addIQProvider( "library-changed", "jabber:iq:lw-lib-change", LibraryChangedIQ.getIQProvider()); } if (ProviderManager.getInstance() .getIQProvider(ConnectBackRequestIQ.ELEMENT_NAME, ConnectBackRequestIQ.NAME_SPACE) == null) { ProviderManager.getInstance() .addIQProvider( ConnectBackRequestIQ.ELEMENT_NAME, ConnectBackRequestIQ.NAME_SPACE, new ConnectBackRequestIQProvider()); } if (ProviderManager.getInstance().getIQProvider(NoSaveIQ.ELEMENT_NAME, NoSaveIQ.NAME_SPACE) == null) { ProviderManager.getInstance() .addIQProvider(NoSaveIQ.ELEMENT_NAME, NoSaveIQ.NAME_SPACE, NoSaveIQ.getIQProvider()); } } ChatStateManager.getInstance(connection); discoInfoListener = new DiscoInfoListener(XMPPFriendConnectionImpl.this, connection, featureRegistry); discoInfoListener.addListeners(connectionMulticaster, friendPresenceSupport); addressIQListener = addressIQListenerFactory.create(XMPPFriendConnectionImpl.this, addressFactory); connection.addPacketListener(addressIQListener, addressIQListener.getPacketFilter()); fileTransferIQListener = fileTransferIQListenerFactory.create(XMPPFriendConnectionImpl.this); connection.addPacketListener( fileTransferIQListener, fileTransferIQListener.getPacketFilter()); authTokenIQListener = authTokenIQListenerFactory.create(XMPPFriendConnectionImpl.this); connection.addPacketListener(authTokenIQListener, authTokenIQListener.getPacketFilter()); libraryChangedIQListener = libraryChangedIQListenerFactory.create(XMPPFriendConnectionImpl.this); connection.addPacketListener( libraryChangedIQListener, libraryChangedIQListener.getPacketFilter()); connectRequestIQListener = connectBackRequestIQListenerFactory.create(XMPPFriendConnectionImpl.this); connection.addPacketListener( connectRequestIQListener, connectRequestIQListener.getPacketFilter()); new LimewireFeatureInitializer().register(featureRegistry); noSaveFeatureInitializer = new NoSaveFeatureInitializer( connection, XMPPFriendConnectionImpl.this, rosterListeners, friendPresenceSupport); noSaveFeatureInitializer.register(featureRegistry); SubscriptionListener sub = new SubscriptionListener(connection, friendRequestBroadcaster); connection.addPacketListener(sub, sub); for (URI feature : featureRegistry.getPublicFeatureUris()) { ServiceDiscoveryManager.getInstanceFor(connection).addFeature(feature.toASCIIString()); } if (xmppActivityListener == null) { xmppActivityListener = new XmppActivityEventListener(); } xmppActivitySupport.addListener(xmppActivityListener); if (idleStatusMonitor == null) { idleStatusMonitor = idleStatusMonitorFactory.create(); } idleStatusMonitor.start(); }