XMPP events on Android

…衆ロ難τιáo~ 提交于 2020-01-13 03:19:26

问题


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.


回答1:


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).




回答2:


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.



来源:https://stackoverflow.com/questions/4668477/xmpp-events-on-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!