android - 创建 Android 后台服务并在关闭应用程序时保持 XMPP 连接和数据包监听器设置

标签 android xmpp

我正在创建一个聊天应用程序。为此,我正在测试 XMPP 服务器。登录时,我连接并登录到测试 XMPP 服务器。它正在发送和接收消息。

我想要的是,当应用程序关闭时(在调用 destroy 方法时),此服务应保持连接处于 Activity 状态并监听消息并将它们存储在应用程序正在使用的同一数据库中。

我已经创建了一个服务并向其添加了连接监听器和数据包监听器,但是当我关闭应用程序时,我看到服务正在运行但连接丢失了。

登录 Activity :

private class ProcessLogin extends AsyncTask<String, Void, String> {
    private ProgressDialog pDialog;
    String uname,password;
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        uname = txtUsername.getText().toString();
        password = txtPassword.getText().toString();

        pDialog = new ProgressDialog(LoginActivity.this);
        pDialog.setTitle("Contacting Servers");
        pDialog.setMessage("Logging in ...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }
    @Override
    protected String doInBackground(String... args) {

        // Create a connection
        ConnectionConfiguration connConfig = new ConnectionConfiguration(HOST,PORT);
        XMPPConnection connection = new XMPPTCPConnection(connConfig);
        String user = null;

        HostAddress address = new HostAddress(HOST);

        try {
            try {
                connection.connect();

            } catch (SmackException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            Log.i("XMPPChatDemoActivity", "[SettingsDialog] Connected to " + connection.getHost());
            Log.i("XMPPChatDemoActivity",  "[SettingsDialog] Connected to "+ address.getErrorMessage());

        } catch (XMPPException ex) {
            Log.e("XMPPChatDemoActivity",  "[SettingsDialog] Failed to connect to "+ connection.getHost());
            Log.i("XMPPChatDemoActivity",  "[SettingsDialog] Connected to "+ address.getErrorMessage());
            Log.e("XMPPChatDemoActivity", ex.toString());
            //setConnect(null);
        }
        try {
            try {
                connection.login(uname, password);
                XMPPSuper.getInstance().setConnection(connection);
            } catch (SaslException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SmackException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            Log.i("XMPPChatDemoActivity",  "Logged in as" + connection.getUser());




            // Set the status to available
            Presence presence = new Presence(Presence.Type.available);

            connection.sendPacket(presence);
            //setConnect(connection);

            Roster roster = connection.getRoster();
            Collection<RosterEntry> entries = roster.getEntries();
            for (RosterEntry entry : entries) {

                Log.d("XMPPChatDemoActivity",  "--------------------------------------");
                Log.d("XMPPChatDemoActivity", "RosterEntry " + entry);
                Log.d("XMPPChatDemoActivity", "User: " + entry.getUser());
                Log.d("XMPPChatDemoActivity", "Name: " + entry.getName());
                Log.d("XMPPChatDemoActivity", "Status: " + entry.getStatus());
                Log.d("XMPPChatDemoActivity", "Type: " + entry.getType());
                Presence entryPresence = roster.getPresence(entry.getUser());

                Log.d("XMPPChatDemoActivity", "Presence Status: "+ entryPresence.getStatus());
                Log.d("XMPPChatDemoActivity", "Presence Type: " + entryPresence.getType());

                Presence.Type type = entryPresence.getType();
                if (type == Presence.Type.available)
                    Log.d("XMPPChatDemoActivity", "Presence AVIALABLE");
                Log.d("XMPPChatDemoActivity", "Presence : " + entryPresence);
                user = XMPPSuper.getInstance().getConnection().getUser();
            }
        } catch (XMPPException ex) {
            Log.e("XMPPChatDemoActivity", "Failed to log in as "+  USERNAME);
            Log.e("XMPPChatDemoActivity", ex.toString());
            user=null;
            //setConnect(null);
        }
        //                 dialog.dismiss();
        catch (SmackException.NotConnectedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return user;
    }
    @Override
    protected void onPostExecute(String user) {
        try {

            if(user != null){

                // Creating user login session
                // For testing i am storing name, email as follow
                // Use user real data

                session.createLoginSession(user,"email id", "2000");

                Intent i = new Intent("com.example.tabmainactivity");
                pDialog.dismiss();
                startService(new Intent(getApplicationContext(), iFlyChatMessage.class));
                startActivity(i);
                finish();

            }else{
                // username / password doesn't match
                pDialog.dismiss();
                Toast.makeText(getApplicationContext(),
                        "Incorrect username/password", Toast.LENGTH_SHORT).show();

            }


        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

我的服务:

@Override
public void onCreate() {

    connection = XMPPSuper.getInstance().getConnection();
    //PingManager keep_alive = PingManager.getInstanceFor(connection);
    configureConnection(connection);
    //keep_alive.setPingInterval(100);

    if (connection != null) {

        final DatabaseHandler db = new DatabaseHandler(this);
        // Add a packet listener to get messages sent to us
        PacketFilter filter = new MessageTypeFilter(org.jivesoftware.smack.packet.Message.Type.chat);
        connection.addPacketListener(new PacketListener() {
            @Override
            public void processPacket(Packet packet) {
                org.jivesoftware.smack.packet.Message message = (org.jivesoftware.smack.packet.Message) packet;
                if (message.getBody() != null) {
                    String fromName = StringUtils.parseBareAddress(message.getFrom());
                    Log.i("XMPPChatDemoActivity ", " Text Recieved " + message.getBody() + " from " + fromName);


                    java.util.Date date = new java.util.Date();
                    Timestamp time = new Timestamp(date.getTime());
                    db.addMessage(message.getBody().toString(), fromName, "testkerry@suchat.org", "1", "2000", time.toString());
                    /*org.jivesoftware.smack.packet.Message msg = new org.jivesoftware.smack.packet.Message(fromName);
                    msg.setBody("Test Successful");
                    try {
                        connection.sendPacket(msg);

                    } catch (SmackException.NotConnectedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }*/
                    // Add the incoming message to the list view
                    /*mHandler.post(new Runnable() {
                        public void run() {
                            //    setListAdapter();
                        }
                    });*/
                    //messagelist.add(new MessageClass("kerry@suchat.org","testkerry@suchat.org",recipient_uid, sender_uid,message.getBody().toString(), time.toString()));


                }
            }
        }, filter);
    }

}

/** The service is starting, due to a call to startService() */
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    // We want this service to continue running until it is explicitly stopped, so return sticky.
    return START_STICKY;
}



private void configureConnection(final XMPPConnection connection){
    connection.addConnectionListener(new AbstractConnectionListener()
                                     {

                                         public void connectionClosed(){

                                             connect();




                                         }
                                         public void connectionClosedOnError(Exception e)
                                         {

                                             connect();
                                         }

                                         public void reconnectionFailed(Exception e)
                                         {
                                         }
                                         public void reconnectionSuccessful(){
                                         }
                                         public void reconnectingIn(int seconds)
                                         {
                                         }
                                     }
    );
}

private void connect()
{
    ConnectionConfiguration connConfig = new ConnectionConfiguration(HOST,PORT);
    XMPPConnection connection = new XMPPTCPConnection(connConfig);

    HostAddress address = new HostAddress(HOST);

    try {
        try {
            connection.connect();

        } catch (SmackException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Log.i("XMPPChatDemoActivity", "[SettingsDialog] Connected to " + connection.getHost());
        Log.i("XMPPChatDemoActivity",  "[SettingsDialog] Connected to "+ address.getErrorMessage());

    } catch (XMPPException ex) {
        Log.e("XMPPChatDemoActivity",  "[SettingsDialog] Failed to connect to "+ connection.getHost());
        Log.i("XMPPChatDemoActivity",  "[SettingsDialog] Connected to "+ address.getErrorMessage());
        Log.e("XMPPChatDemoActivity", ex.toString());
        //setConnect(null);
    }
    try {
        try {
            connection.login(USERNAME,PASSWORD);
            XMPPSuper.getInstance().setConnection(connection);
        } catch (SaslException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SmackException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Log.i("XMPPChatDemoActivity",  "Logged in as" + connection.getUser());




        // Set the status to available
        Presence presence = new Presence(Presence.Type.available);

        connection.sendPacket(presence);
        //setConnect(connection);

        Roster roster = connection.getRoster();
        Collection<RosterEntry> entries = roster.getEntries();
        for (RosterEntry entry : entries) {

            Log.d("XMPPChatDemoActivity",  "--------------------------------------");
            Log.d("XMPPChatDemoActivity", "RosterEntry " + entry);
            Log.d("XMPPChatDemoActivity", "User: " + entry.getUser());
            Log.d("XMPPChatDemoActivity", "Name: " + entry.getName());
            Log.d("XMPPChatDemoActivity", "Status: " + entry.getStatus());
            Log.d("XMPPChatDemoActivity", "Type: " + entry.getType());
            Presence entryPresence = roster.getPresence(entry.getUser());

            Log.d("XMPPChatDemoActivity", "Presence Status: "+ entryPresence.getStatus());
            Log.d("XMPPChatDemoActivity", "Presence Type: " + entryPresence.getType());

            Presence.Type type = entryPresence.getType();
            if (type == Presence.Type.available)
                Log.d("XMPPChatDemoActivity", "Presence AVIALABLE");
            Log.d("XMPPChatDemoActivity", "Presence : " + entryPresence);
        }
    } catch (XMPPException ex) {
        Log.e("XMPPChatDemoActivity", "Failed to log in as "+  USERNAME);
        Log.e("XMPPChatDemoActivity", ex.toString());
        //setConnect(null);
    }
    //                 dialog.dismiss();
    catch (SmackException.NotConnectedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

知道怎么做吗?

最佳答案

启动应用程序时启动服务

在 AsyncTask 的 onPostExecute() 方法中添加连接监听器和数据包监听器。

并在服务onCreate()方法中执行AsyncTask

在服务内部执行 AsyncTask 它使任务持续工作直到服务处于 Activity 状态以及 xmpp 连接。

希望对你有帮助

对我有用...

关于android - 创建 Android 后台服务并在关闭应用程序时保持 XMPP 连接和数据包监听器设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29790845/

相关文章:

iphone - 用于 iPhone 开发的 Objective C 中带有 Jingle 的 XMPP 库

android - 我们如何在 XMPP 中结束特定用户的 session 并从聊天中注销

xmpp - 如何创建 XMPP 帐户?

android - startActivity 和 startActivityForResult 具有相同的 Activity?

java - 发生评估根项目> com.android.application找不到插件

java - android: 找不到符号 TaskDescription

java - Smack XMPP Java : How to access the original XML reprsentation of a ByteStreamRequest (OPEN)?

sockets - 调整大量 XMPP 用户的 TCP 设置

android - 文字大小和不同的 Android 屏幕尺寸

android - 在 Android 中强制执行 GCMNetworkManager OneoffTask