XMPP events on Android

2020-07-18 03:50发布

I'm trying to develop a background process that intercepts a XMPP message and performs an action, I'm using asmack as the main XMPP library. I presume I need a broadcastReciever that responds to a specific intent. The question is how to raise the intent? It must be possible as this functionality is present in the google talk client. many thanks in advance.

2条回答
可以哭但决不认输i
2楼-- · 2020-07-18 04:20

If you really want to achieve this behavior, you might think about a persistent background service running the asmack XMPP client. The listener method (i.e. processPacket) of your XMPP client could raise an intent. You could then catch this intent from another application or within this application by using a BroadcastReceiver.

final Context context = getContext(); // or getApplicationContext(). context must be final.
PacketFilter packetFilter = new MessageTypeFilter(Message.Type.chat);
connection.addPacketListener(new PacketListener() {
    @Override
    public void processPacket(Packet packet) {
        Message message = (Message) packet;
        if (message.getBody() != null) {
            String from = StringUtils.parseBareAddress(message.getFrom());
            Intent intent = new Intent();
            intent.setAction("your.package.XMPP_PACKET_RECEIVED");
            intent.putExtra("from", from);
            intent.putExtra("body", message.getBody());
            context.sendBroadcast(i);
        }
    }
}, packetFilter);

You could also try to implement the other communication direction by creating a BroadcastReceiver (or IntentService) that receives an intent and sends it via XMPP. A BackgroundReceiver would have to create a new connection for each message which would be slow but energy saving (there is no need to keep the XMPP session alive).

查看更多
虎瘦雄心在
3楼-- · 2020-07-18 04:24

I presume I need a broadcastReciever that responds to a specific intent.

Probably not. aSmack appears to be mostly Smack, which has nothing to do with Android, and therefore has no notion of Intents.

It must be possible as this functionality is present in the google talk client.

The "google talk client" does not use Smack, AFAIK.

查看更多
登录 后发表回答