Querying for Presence in Android

  • January 30, 2012

Presence is saved in the Android database for each user.  There is a presence table which stores multiple presences and statuses for each user from each presence source, such as skype, jabber, and gTalk.  The presence is derived from some enumeration which would typically include states such as “availible,” “away,” and “do not disturb”.  The status is the message that the user can enter when setting their status, such as if one sets themselves to away on gTalk they might want to include the following message, “Out to lunch be right back.” Typically we only want the most recent of any presence provider.  Therefore we can query for the presence and the status associated with this user.  NOTE: The following code is for Android 3.0 and beyond.  For 2.x and below, use a managed cursor instead of the cursor loader.

presenceUri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, Uri.encode(lookupKey));

String[] presenseProjection = {

cursorLoader = new CursorLoader(

Cursor presenceCursor = cursorLoader.loadInBackground();

if(presenceCursor.moveToFirst()) {
     int presence = presenceCursor.getInt(presenceCursor.getColumnIndex(Contacts.CONTACT_PRESENCE));
     String status = presenceCursor.getString(presenceCursor.getColumnIndex(Contacts.CONTACT_STATUS));

If we want to react to a new presence we can register a ContentObserver on the database.  We should register on the database table instead of the cursor.  If we register on the cursor then the cursor must stay open and that takes up valuable resources and will potentially slow down your application.

ContentObserver statusObserver = new ContentObserver(new Handler()) {
			public void onChange(boolean selfChange) {
				presenceCursor = cursorLoader.loadInBackground();
				// Do what you want with the cursor

		context.getContentResolver().registerContentObserver (presenceUri, true, statusObserver); 

No Comments

You can leave the first : )

Leave a Reply

Your email address will not be published. Required fields are marked *