我發現了這個問題:XMPP events on Android,答案解釋了我遇到的問題的解決方案。但我似乎無法弄清楚如何讓packetListener工作。我已經嘗試過packetCollectors和packetListeners,但注意到似乎工作。在android中收聽XMPP數據包
我不確定應該在哪裏放置數據包監聽器。是否應該進入服務的onCreate()方法或onStartCommand()中,還是應該放入每隔幾秒運行一次的單獨方法?
我的困惑主要是聽者的概念。監聽程序是否始終運行,並會在收到數據包後立即觸發?我如何確保聽衆能夠「看到」進來的數據包事件?
這是我得到這個工作當前的嘗試:
public class XMPPService extends Service{
private static String TAG = "XMPPService";
XMPPConnection connection;
MultiUserChat muc;
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate(){
super.onCreate();
}
public int onStartCommand(Intent intent, int flags, int startId){
ConnectionConfiguration config = new ConnectionConfiguration("jabber.org", 5222);
connection = new XMPPConnection(config);
try
{
connection.connect();
Log.i(TAG,"connected");
}
catch (XMPPException e)
{
Log.e(TAG, "Connection Issue: ", e);
}
try
{
connection.login("user", "password");
muc = new MultiUserChat(connection, "[email protected]");
muc.join("nick","password");
Presence presence = new Presence(Presence.Type.available);
connection.sendPacket(presence);
setConnection(connection);
}
catch (XMPPException e)
{
Log.e(TAG, "Connection Issue: ", e);
}
makeNotification("started");
return 1;
}
private void makeNotification(String msg){
Notification notification = new Notification(R.drawable.icon, msg, System.currentTimeMillis());
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MUCTestActivity.class), 2);
notification.setLatestEventInfo(this, "Title", msg, contentIntent);
NotificationManager nmgr = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
nmgr.notify(123443, notification);
}
public void setConnection(XMPPConnection connection) {
this.connection = 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.i(TAG, "Got text [" + message.getBody() + "] from [" + fromName + "]");
}
else
{
Log.i(TAG,"null");
}
}
}, filter);
}
}
}
嘿,我也面臨同樣的問題。如果你解決了這個問題,你可以讓我知道。我也想知道整個應用程序中的事件通知(消息,好友請求,連接事件等),而不管活動。 @Atomix – Roster