Friday, February 26, 2010

Android XMPP

Update: working code for send/receive over XMPP from gtalk / non-gtalk accounts

So, apparently XMPP support was briefly part of the official android SDK, but they took it out again.

There's a respected library called "smack", but it doesn't work with android out of the box.

There's a hack of smack for android called asmack, and that seems to work for me, at least for sending messages.

I haven't figured out how to make it work with, but I created an account at and was successful in sending an IM from my android.

package com.example.HelloFormStuff;

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ChatManager;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;

public class HelloFormStuffActivity extends Activity {
public int state = 0;

/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {

XMPPConnection xmpp = new XMPPConnection("");
try {
xmpp.login("username","password"); // just username, no @ sign
} catch (XMPPException e) {
// TODO Auto-generated catch block
System.out.println("Failed to connect to " + xmpp.getHost());
ChatManager chatmanager = xmpp.getChatManager();
Chat newChat = chatmanager.createChat("", new MessageListener() {
public void processMessage(Chat chat, Message message) {
Toast.makeText(HelloFormStuffActivity.this, message.toString(), Toast.LENGTH_SHORT).show();

try {
newChat.sendMessage("IMing from my android");
} catch (XMPPException e) {
Toast.makeText(HelloFormStuffActivity.this, "ERROR", Toast.LENGTH_SHORT).show();

Don't forget to add the INTERNET permission to the manifest.xml, or you'll get "not connected" exceptions.

No comments: