在SMACK中重新连接互联网时无法继续聊天

时间:2016-09-23 14:18:23

标签: xmpp smack xmppframework

这是我的代码: 有两种情况正在发生: 1.当我从另一方收到待处理的消息时,没有继续聊天: 2.当我断开XMPP连接的互联网时,待处理的消息没有到来,但聊天将继续

  public void init(String userId, String pwd) {
    Log.i("XMPP", "Initializing!");

    mPassword = DatabaseManager.Session.getClientPassword(this);
    HOST = "xm3.conversity.net";
    xMppUserName = DatabaseManager.Session.getXmppUserName(this);
    xMppOnlyUserName = xMppUserName.split("@")[0];
    agentId = DatabaseManager.Session.getAgentNameId(this);
    PORT = DatabaseManager.Session.getPortNumber(this);
    Log.e("xmpp", "mPassword:" + mPassword);
    Log.e("xmpp", "HOST:" + HOST);
    Log.e("xmpp", "xMppOnlyUserName:" + xMppOnlyUserName);
    Log.e("xmpp", "xMppUserName:" + xMppUserName);
    Log.e("xmpp", "agentId:" + agentId);
    Log.e("xmpp", "PORT:" + String.valueOf(PORT));

    XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder();
    configBuilder.setUsernameAndPassword(xMppUserName, passWord);
    configBuilder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
    configBuilder.setResource("Android");
    configBuilder.setServiceName(DOMAIN);
    configBuilder.setHost(HOST);
    configBuilder.setPort(PORT);
    configBuilder.setSendPresence(true);
    configBuilder.setDebuggerEnabled(true);
    configBuilder.setCompressionEnabled(true);
    connection = new XMPPTCPConnection(configBuilder.build());
    connection.addConnectionListener(connectionListener);


            //        ReconnectionManager.getInstanceFor(connection).enableAutomaticReconnection();

        //        connection.setPacketReplyTimeout(10000);
        //        PingManager.setDefaultPingInterval(600);
        //        PingManager.getInstanceFor(connection).registerPingFailedListener((PingFailedListener) this);
    chatmanager = ChatManager.getInstanceFor(connection);
    chatmanager.addChatListener(new ChatManagerListener() {
        @Override
        public void chatCreated(Chat chat, boolean createdLocally) {
            chat.addMessageListener(new ChatMessageListener() {
                @Override
                public void processMessage(Chat chat, final Message message) {
                    Log.e("Xmpp", String.valueOf(chat) + " === " + message.toString() + "MESSAGE: " + message.getBody());
                    Handler refresh = new Handler(Looper.getMainLooper());
                    refresh.post(new Runnable() {
                        public void run() {
                            Log.e("Xmpp", "RECIVE MESSAGE: " + message.getBody() + message.getFrom() + "StanzaID: " + message.getBodies());
                            String[] strings = {message.getBody(), "2", Utility.getCurrentTime(), message.getThread(), "A", "6", "7", DatabaseManager.Message.START_CHAT, ""};
                            DatabaseManager.Message.insertValues(getApplicationContext(), strings);
                            Intent i = new Intent(ChatActivity.CHAT_BROADCAST);
                            i.putExtra(ChatActivity.KEY_ACTION, ChatActivity.NEW_MESSAGE);
                            getApplicationContext().sendBroadcast(i);

                            final Handler handler = new Handler();
                            handler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    // Do something after 5s = 5000ms
                //                                disconnectConnection();
                                }
                            }, 3000);
                        }
                    });
                }
            });
        }
    });

}

// Disconnect Function
public void disconnectConnection() {

    new Thread(new Runnable() {
        @Override
        public void run() {
            connection.disconnect();
            Log.e("xmpp", "connection.disconnect();");
        }
    }).start();
}

public void connectConnection() {
    AsyncTask<Void, Void, Boolean> connectionThread = new AsyncTask<Void, Void, Boolean>() {

        @Override
        protected Boolean doInBackground(Void... arg0) {

            // Create a connection
            try {
                connection.connect();
                login();
                connected = true;
                final ScheduledExecutorService scheduleTaskExecutor = Executors.newSingleThreadScheduledExecutor();
                scheduleTaskExecutor.scheduleWithFixedDelay(new Runnable() {
                    @Override
                    public void run() {
                        Log.d("xmpp", "inside run()");
                        Log.d("xmpp", "isconnect: " + connection.isConnected() + " Auth: " + connection.isAuthenticated());

                     /*   if(!Utility.isNetworkAvailable(getApplicationContext())){
       //                                disconnectConnection();
                        }
                        else */
                        if (connection.isConnected()) {
                            sendMessagesToServer();

                        } else {
                            try {
                                connection.connect();
                                login();
                            } catch (SmackException e) {
                                e.printStackTrace();
                            } catch (IOException e) {
                                e.printStackTrace();
                            } catch (XMPPException e) {
                                e.printStackTrace();
                            }

                        }
                    }
                }, 0, 2, TimeUnit.SECONDS);


            } catch (IOException e) {
            } catch (SmackException e) {

            } catch (XMPPException e) {
            }

            return null;
        }
    };
    connectionThread.execute();
}

private void sendMessagesToServer() {

    try {
        connection.sendPacket(new Presence(Presence.Type.available));
    } catch (SmackException.NotConnectedException e) {
        e.printStackTrace();
    }
    //        Log.e(TAG,"in side sendMessagesToServer()");
    DatabaseManager dbManager = new DatabaseManager(this);
    dbManager.open();
    Cursor c = dbManager.getMessages();
    while (c.moveToNext()) {
        //Read the message details
        String status = c.getString(DatabaseManager.Message.INDEX_STATUS);
        //            Log.e("PREM", status + String.valueOf(status.equalsIgnoreCase("P")));
        if (status.equalsIgnoreCase("P")) {


            String message = c.getString(DatabaseManager.Message.INDEX_MESSAGE);
            String id = c.getString(0);
            sendMsg(message);
            dbManager.updateMessageStatus(id, jid);
        }
    }
    c.close();
    dbManager.close();
}


public void sendMsg(String message) {
    if (connection.isConnected() == true) {
        // Assume we've created an XMPPConnection name "connection"._
        chatmanager = ChatManager.getInstanceFor(connection);
        newChat = chatmanager.createChat(agentId);

        try {
            newChat.sendMessage(message);
            jid = newChat.getThreadID();
            Log.i("Xmpp", "message send to server");
            Log.i("Xmpp", "thread: " + newChat.getThreadID() + " Listner: " + newChat.getListeners() + " participant" + newChat.getParticipant());
        } catch (SmackException.NotConnectedException e) {
            e.printStackTrace();
        }
    }
}

public void login() {

    try {
        connection.login(xMppOnlyUserName, DatabaseManager.Session.getClientPassword(this));
        Log.i("Xmpp", "Yey! We're connected to the Xmpp server!");

    } catch (XMPPException | SmackException | IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
    }

}

1 个答案:

答案 0 :(得分:0)

你的问题不明确,但从我的理解,你必须在android上的sqlite数据库中保存消息,然后每次打开聊天页面时从数据库加载