我正在尝试将smack API用于我的聊天应用程序。 到目前为止做了什么:
我收听传入消息的服务:
chatmanager.addChatListener(
new ChatManagerListener() {
@Override
public void chatCreated(Chat chat, boolean createdLocally) {
if (!createdLocally)
chat.addMessageListener(myMessageListener);
}
});
class MyMessageListener implements ChatMessageListener {
@Override
public void processMessage(Chat chat, Message message) {
String body = message.getBody();
if (body != null && !body.isEmpty()) {
Intent intent = new Intent();
intent.setAction(MY_ACTION);
intent.putExtra("message", body);
sendBroadcast(intent);
}
}
}
我的接收器类:
public class MessageReceiver extends BroadcastReceiver
{
private ChatArrayAdapter chatArrayAdapter;
@Override
public void onReceive(Context context, Intent intent) {
String message = intent.getStringExtra("message");
Log.d("receiveddddd", message);
chatArrayAdapter.add(new ChatMessage(true,message));
chatArrayAdapter.notifyDataSetChanged();
}
}
我用于注册Receiver的活动:
protected void onResume() {
messageReceiver = new MessageReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(XMPPService.MY_ACTION);
registerReceiver(messageReceiver, intentFilter);
super.onResume();
}
这是我使用我的Android应用程序发送消息的方式:
//listener is the object of MyMessageListener class
Chat chat = chatmanager.createChat("username@" + SERVICE,listener);
try {
chat.sendMessage(messageBody);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
我使用Pidgin作为我的第二个客户。
问题:
1)当我从pidgin开始聊天时。我能够成功接收和发送但是当我开始从我的Android应用程序聊天到Pidgin时它无法接收消息。收到邮件时收到此错误:
Exception in packet listener
java.lang.NullPointerException
at android.content.ContextWrapper.sendBroadcast(ContextWrapper.java:312)
at fbcrush.fbcrush.XMPPClientSmack.XMPPService$MyMessageListener.processMessage(XMPPService.java:72)
at org.jivesoftware.smack.chat.Chat.deliver(Chat.java:180)
第72行是myMessageListener类中的sendBroadcast(intent)