Show me the code! – By Davanum Srinivas

November 23, 2007

Totally *Unofficial* Android GTalk Client (Send/Receive XMPP Messages)

Filed under: Uncategorized — Davanum Srinivas @ 11:21 am

Here is the screen shot

001

Functionality

  • Enter the recipient’s name in the edit box on top and press “setup” button
  • Enter the message text in the edit box on the bottom and press “send” button to send the message to the recipient

Source

package org.apache.gtalk;

import android.app.Activity;
import android.app.NotificationManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.os.Bundle;
import android.os.DeadObjectException;
import android.os.IBinder;
import android.provider.Im;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.*;
import com.google.android.xmppService.IXmppService;
import com.google.android.xmppService.IXmppSession;
import com.google.android.xmppService.Presence;

public class GTalkClient extends Activity implements View.OnClickListener {
    private static final String LOG_TAG = "GTalkClient";

    IXmppSession mXmppSession = null;
    EditText mSendText;
    ListView mListMessages;
    EditText mRecipient;
    Button mSend;
    Button mSetup;

    /**
     * Called with the activity is first created.
     */
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);

        // gather the troops
        mSendText = (EditText) findViewById(R.id.sendText);
        mListMessages = (ListView) findViewById(R.id.listMessages);
        mRecipient = (EditText) findViewById(R.id.recipient);
        mSend = (Button) findViewById(R.id.send);
        mSetup = (Button) findViewById(R.id.setup);

        // set up handler for on click
        mSetup.setOnClickListener(this);
        mSend.setOnClickListener(this);

        bindService((new Intent()).setComponent(
                com.google.android.xmppService.XmppConstants.XMPP_SERVICE_COMPONENT),
                null, mConnection, 0);
    }

    /**
     * Let the user know there was an issue
     *
     * @param msg
     */
    private void logMessage(CharSequence msg) {
        NotificationManager nm = (NotificationManager) getSystemService(
                Context.NOTIFICATION_SERVICE);

        nm.notifyWithText(123, msg, NotificationManager.LENGTH_LONG, null);
    }

    /**
     * Setup the XMPP Session using a service connection
     */
    private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
            // This is called when the connection with the XmppService has been
            // established, giving us the service object we can use to
            // interact with the service.  We are communicating with our
            // service through an IDL interface, so get a client-side
            // representation of that from the raw service object.
            IXmppService xmppService = IXmppService.Stub.asInterface(service);

            try {
                mXmppSession = xmppService.getDefaultSession();
                if (mXmppSession == null) {
                    // this should not happen.
                    logMessage(getText(R.string.xmpp_session_not_found));
                    return;
                }
                mXmppSession.setPresence(new Presence(Im.PresenceColumns.AVAILABLE, "Am here now!"));
            } catch (DeadObjectException ex) {
                Log.e(LOG_TAG, "caught " + ex);
                logMessage(getText(R.string.found_stale_xmpp_service));
            }

            mSendText.setEnabled(true);
        }

        public void onServiceDisconnected(ComponentName componentName) {
            // This is called when the connection with the service has been
            // unexpectedly disconnected -- that is, its process crashed.
            mXmppSession = null;
            mSendText.setEnabled(false);
        }
    };

    /**
     * Handle clicks on the 2 buttions
     *
     * @param view
     */
    public void onClick(View view) {
        if (view == mSetup) {
            Log.i(LOG_TAG, "onClick - Setup");
            // Run a query against CONTENT_URI = "content://im/messages"
            Cursor cursor = managedQuery(Im.Messages.CONTENT_URI, null,
                    "contact=\'" + mRecipient.getText().toString() + "\'", null, null);

            // Display the cursor results in a simple list
            // Note that the adapter is dyamic (picks up new entries automatically)
            ListAdapter adapter = new SimpleCursorAdapter(this,
                    android.R.layout.simple_list_item_1,
                    cursor, // Give the cursor to the list adatper
                    new String[]{Im.MessagesColumns.BODY},
                    new int[]{android.R.id.text1});

            this.mListMessages.setAdapter(adapter);
        } else if (view == mSend) {
            // use XmppService to send data message to someone
            String username = mRecipient.getText().toString();
            if (!isValidUsername(username)) {
                logMessage(getText(R.string.invalid_username));
                return;
            }

            if (mXmppSession == null) {
                logMessage(getText(R.string.xmpp_service_not_connected));
                return;
            }

            try {
                mXmppSession.sendTextMessage(username, 0, mSendText.getText().toString());
            } catch (DeadObjectException ex) {
                Log.e(LOG_TAG, "caught " + ex);
                logMessage(getText(R.string.found_stale_xmpp_service));
                mXmppSession = null;
            }
        }
    }

    private boolean isValidUsername(String username) {
        return !TextUtils.isEmpty(username) && username.indexOf('@') != -1;
    }
}

Download the sources and Application – GTalkClient.zip

About these ads

42 Comments »

  1. [...] 11.23 Totally *Unofficial* Android GTalk Client (Send/Receive XMPP Messages) [...]

    Pingback by Sending XMPP messages in Android - Standalone sample (Ant build.xml/intellij project) « Show me the code! — November 23, 2007 @ 11:26 am

  2. [...] site “Show me the code !” continue sur sa lancée et nous propose aujourd’hui un client GTalk pour Android qui fonctionne grâce à l’envoi et la réception de messages [...]

    Pingback by Android : Client GTalk — November 23, 2007 @ 12:20 pm

  3. [...] with Android this week, releasing new source code on an almost daily basis.  Today he releases a *totally* unofficial Gtalk client for Android.  He also includes source code for sending and receiving XMPP messages and authenticating with [...]

    Pingback by Source Code: A Gtalk Client from Davanum | Android Notes — November 23, 2007 @ 12:36 pm

  4. Great App. A way to learn more about android. Something I planned doing when I get a firm grasp of it. Anyway, great effort.

    Comment by Henry Addo — November 23, 2007 @ 5:37 pm

  5. [...] and download *Unoficial* Android’ GTalk Client Application here. Hurry [...]

    Pingback by gPhone Daily » Blog Archive » Android GTalk client application — November 23, 2007 @ 7:50 pm

  6. Last week a gave a quick look at XMPP support in Android and getting the service was quite simple, but I didn’t understand how to receive plain messages (p2p data messages are received as intents). Where did you find info about the android.provider.Im package? In the documentation there is nothing about it, and google is of no help.

    Comment by Fabio Forno — November 24, 2007 @ 4:41 pm

  7. [...] Totally *Unofficial* Android GTalk Client (Send/Receive XMPP Messages) Here is the screen shot [image] [...]

    Pingback by Top Posts « WordPress.com — November 24, 2007 @ 7:01 pm

  8. [...] Show me the code! via gPhone [...]

    Pingback by Google Talk using unnoficial Android GTalk client application — 3GWeek — November 24, 2007 @ 9:23 pm

  9. Thanks!!!

    Comment by milan — November 25, 2007 @ 9:20 am

  10. What moment do you detect the incoming message in?

    Comment by Quauhtli Martinez — November 26, 2007 @ 10:18 pm

  11. How do you delete the messages that have been read for an specific user?

    Comment by Quauhtli Martinez — November 27, 2007 @ 11:19 am

  12. [...] projets simples mais intéressant et fonctionnels. On peux citer en vrac son Client Twitter, son Client GTalk, son utilitaire de GéoLocalisation sans GPS et bien d’autre que nous vous laissons [...]

    Pingback by » Le développeur du mois — December 2, 2007 @ 1:34 pm

  13. It is not actually recieve messages. It prints jsut sent one. Do you know a way to actually recieve messages?

    Comment by simeon — December 16, 2007 @ 7:24 pm

  14. Simeon,
    It does show both received and sent message. Just that you need to scroll, they are at the end.

    The in message is detected as soon as it arrives.

    I added a line mSendText.setText(“”); after
    mXmppSession.sendTextMessage(username, 0, mSendText.getText().toString());

    Would be nice if the end of few lines from the list adapter show on the screen, once the screen is full you have to scroll the list down to see the latest messages. (other alternative is to set your query so that it will show you the latest message first. (in reverse order))

    This way you don’t have to erase the previous message to sent.
    Thanks.

    Comment by jsyadav — December 30, 2007 @ 12:19 am

  15. Simeon,
    It does show both received and sent message. Just that you need to scroll, they are at the end.

    The in message is detected as soon as it arrives.

    I added a line mSendText.setText(“”); after
    mXmppSession.sendTextMessage(username, 0, mSendText.getText().toString());

    This way you don’t have to erase the previous message to sent.

    Would be nice if the end of few lines from the list adapter show on the screen, once the screen is full you have to scroll the list down to see the latest messages. (other alternative is to set your query so that it will show you the latest message first. (in reverse order))

    Thanks.

    Comment by jsyadav — December 30, 2007 @ 12:21 am

  16. Very cool article, and useful. Keep up the good work.

    Comment by Dipankar Sarkar — January 6, 2008 @ 1:19 pm

  17. hi,

    The application work perfect, if I just need to sent the messages. But I want to do some processing on the received messages how can I get last received message.

    Regards

    Comment by Prashant — January 18, 2008 @ 12:15 am

  18. Very cool article, and useful. Keep up the good work.

    Comment by kimochi — January 19, 2008 @ 4:46 pm

  19. Hi ,

    I am new to android .

    How we can invoke web services on remote server through android.

    Any help?

    by
    vamsi

    Comment by vamsi — January 25, 2008 @ 3:32 am

  20. i see no message came in?

    please help

    is it really can receive text message from gtalk client?

    Comment by enshrentko — January 26, 2008 @ 11:42 am

  21. Hi, just read this post. Thank you!

    Comment by Serg — February 24, 2008 @ 10:30 am

  22. Hello!

    I have used this code, but there is a problem due to the change of version of the sdk. I have changed all xmpp appearences for gtalk. But i don´t know how to update this two calls:

    private void logMessage(CharSequence msg) {
    NotificationManager nm = (NotificationManager) getSystemService(
    Context.NOTIFICATION_SERVICE);

    nm.notifyWithText(123, msg, NotificationManager.LENGTH_LONG, null);
    }

    In the new sdk notificationmanager doesn´t work this way.

    And the other problem:

    mXmppSession.sendTextMessage(username, 0, mSendText.getText().toString());

    Now we can´t use sendTextMessage, we have to use sendDataMessage(String to, Intent broadcastintent)

    How is sendDataMessage(…) used? do we have to create a new class just to write the text message in the receipent??

    thank you very much!!

    Comment by xayide — February 28, 2008 @ 1:46 pm

  23. its the best post from you, thanks a lot

    Comment by SamaraRegion — February 28, 2008 @ 10:56 pm

  24. Hi,
    I’m getting problem to import import
    import com.google.android.xmppService

    I’m using eclipse platform. Any hint?

    Comment by Baishakhi — April 6, 2008 @ 3:44 pm

  25. Would be nice if the end of few lines from the list adapter show on the screen, once the screen is full you have to scroll the list down to see the latest messages.

    Comment by SEO collection links on optimization competitions — June 23, 2008 @ 9:09 am

  26. Nice work! This weekend i’ll try your source. Thanx a lot.

    Comment by Бизнес идеи — January 2, 2009 @ 3:44 pm

  27. Hi,
    Thenks for the blog!

    Comment by Все для женщин — January 13, 2009 @ 4:50 pm

  28. Dont cheat me..

    I’m not able to download the zip file from this page.
    give the file to download..

    Comment by Bose Pandian — February 19, 2009 @ 5:58 am

  29. Hi,
    I am trying to install XMPP client apk through adb install but i am getting PARSE FAILED NO CERTIFICATES error,how to remove this error?.

    Thanks

    Comment by Abhijit — September 15, 2009 @ 12:33 am

  30. Thnx for this sample, but I see only sending here. What part of the code receives messages?

    Comment by andrey — November 1, 2009 @ 3:16 pm

  31. I will try to apply at myself.

    Comment by keval — November 17, 2009 @ 10:39 am

  32. In the documentation there is nothing about it, and google is of no help.

    Comment by John — January 20, 2010 @ 4:07 pm

    • Why i can’t find any information about XMPP from sdk and code resource?

      Comment by paul — March 26, 2010 @ 4:37 am

  33. the download link is not working.. could you please mail it to me? thx

    Comment by suthansee — July 15, 2010 @ 2:02 pm

  34. I am new to this XMPP.I am developing Gatlk client.But this app is working fine but i am not able to get online friends status.now i am able to get only dnd and away only.Available persons i am not able to get it.plz reply me any one.
    Thanks,
    Madhusudhan D

    Comment by madhusudhan — August 2, 2010 @ 1:27 am

    • Use following code to get available status.
      if(presence.getType()==Presence.Type.available)
      {
      status=”Online”;

      }

      Comment by Amol — August 12, 2010 @ 8:57 am

  35. ввах

    Comment by Рома — September 20, 2010 @ 2:35 pm

  36. I can’t find the source code on given link.
    Please help.
    Thanks in advance…

    Comment by PJ — November 11, 2011 @ 8:14 am

  37. hi i am using Presence class to set status message but when i am closing or sign out from my app that status message was changed
    please tell me how to set status message permanently

    Comment by mallikpavan — November 29, 2011 @ 1:11 am

  38. Hi, good post. I have been thinking about this issue, so thanks for blogging. I will definitely be subscribing to your blog. Keep up the good posts

    Comment by Joni — March 18, 2012 @ 6:51 am


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

The Shocking Blue Green Theme. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.

Join 133 other followers

%d bloggers like this: