我发现了这个问题:Android上的XMPP事件,答案解释了我遇到的问题的解决方案。但是我似乎无法弄清楚如何让packetListener工作。我尝试过packetCollectors和packetListeners,但没有什么作用。
我不确定应该将packet listeners放在哪里。它应该放在服务的onCreate()方法中还是放在onStartCommand()中,还是应该放在每几秒钟运行一次的单独方法中?
我的困惑大部分是关于listeners的概念。监听器是否始终在运行,并且会在接收到数据包时立即触发?我如何确保监听器可以“看到”传入的数据包事件?
这是我目前尝试让它工作的方式:
我不确定应该将packet listeners放在哪里。它应该放在服务的onCreate()方法中还是放在onStartCommand()中,还是应该放在每几秒钟运行一次的单独方法中?
我的困惑大部分是关于listeners的概念。监听器是否始终在运行,并且会在接收到数据包时立即触发?我如何确保监听器可以“看到”传入的数据包事件?
这是我目前尝试让它工作的方式:
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, "room@conference.jabber.org");
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);
}
}
}