聊天应用程序 - Smack 4.1 Android IntentService - 发送消息

时间:2015-07-15 09:17:47

标签: android xmpp chat smack

我正在使用Smack 4.1在Android中创建聊天应用程序。我已经实现了一个IntentService,它创建连接并在用户登录应用程序后在xmpp中记录用户。我使用以下代码从片段启动intentservice,工作正常:

chatIntent = new Intent(mContext, ChatService.class);
chatIntent.setAction(XMPP_ACTION_CONNECT);
mContext.startService(chatIntent);

然后我试图从片段发送消息。我尝试使用与上面相同的代码

Intent sendmsgIntent = new Intent(mContext, ChatService.class);
sendmsgIntent.putExtra("msg",messageText);
sendmsgIntent.putExtra("to",companionLabel.getText().toString());
sendmsgIntent.setAction(ACTION_SEND_MESSAGE);
mContext.startService(sendmsgIntent);

但是当在IntentService中收到intent时,XMPPTCPConnection连接为null,我不能使用:

connection.sendStanza(message);

为什么这是空的?服务从一开始就重新开始吗? 这是我用来发送第二个意图错误的方式吗? 或者我如何获得第一个意图发送时创建的XMPPTCPConnection连接?

1 个答案:

答案 0 :(得分:2)

是的,IntentService只是在后台线程中执行onHandleIntent,然后被销毁。

而是使用可以从片段和活动绑定的普通服务,以使其在生命周期中可用;实际上有一些不错的文档: http://developer.android.com/guide/components/bound-services.html#Binding 该服务将在UI线程上运行,因此您需要在新线程或AsyncTasks中执行Smack网络调用。