Package listener in Android service

I am trying to create a service for a chat widget using XMPP that collects chat messages when they are sent to the user.

I created a service, and in onStart I use AsyncTask to connect to the chat server, and then configures the batch.

Here is the code for the packer listener:

public void setConnection(XMPPConnection 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.v(TAG, "Got:" + message.getBody()); // messages.add(fromName + ":"); // messages.add(message.getBody()); } } }, filter); } } 

The problem is that she stops listening when you are idle for a while. If I immediately send chat messages, they will get an output.

Does the service somehow stop? Is this a suitable place to place a packer?

thanks

+1
source share
1 answer

I created a service, and in onStart I use AsyncTask to connect to the chat server, and then configures the batch.

I do not recommend this. Create your own thread, not AsyncTask . AsyncTask is for things that end in milliseconds or seconds, rather than minutes or hours.

Does the service stop somehow?

Quite possible. Use adb logcat , DDMS or the DDMS perspective in Eclipse to learn LogCat and see what it tells you about your code.

You should use startForeground() in your service, especially if you plan to keep the service running when your chat client activity is not necessarily in the foreground.

+1
source

Source: https://habr.com/ru/post/922964/


All Articles