Published: 19 Mar 2012
By: Dino Esposito

In this article, I'll discuss the features and capabilities required by an Android application to talk with Twitter. In particular, I'll focus on authentication and updates.

Contents [hide]

The Android for .NET Developers Series

  • Part 1 Starting with this article, I'll discuss what you need to know to approach Android programming without any aid from your .NET expertise.
  • Part 2 In this article, we'll go through an Android application that accepts input from the user and handles user's clicking.
  • Part 3 In this article, you will learn how to build the user interface.
  • Part 4 In this article, I'll be delving deep into menus and dialog boxes in Android for .NET, and discuss a few very common (and frequently used) types of menus and dialogs.
  • Part 5 In this article, Dino Esposito focuses on the options that the Android SDK offers for local storage.
  • Part 6 In this article, Dino Esposito shows how to build settings dialog boxes using a built-in feature of Android for .NET.
  • Part 7 In this article, I'll dissect the code of a realistic application - a waterpolo score manager - to show how to save and resume the status of a game using both the internal storage and SD card.
  • Part 8 In this article, I'll focus on the execution of common tasks from within an Android application. I'll build the skeleton of an application that takes a photo and emails to the specified address. For both tasks I'll use native Android components.
  • Part 9 In this article, I'll discuss how to arrange an Android view where the dominant element is the list. I'll start with a plain list of strings and then improve up to populating a listview with downloaded content arranged using a custom layout.
  • Part 10 In this article, I'll discuss the features and capabilities required by an Android application to talk with Twitter. In particular, I'll focus on authentication and updates.
  • Introduction

    A mobile device is always with you and must be able to connect you to the world. Twitter and social networks are definitely an important part of the world you want to see and interact with from within a mobile device. In this article, I'll discuss the features and capabilities required by an Android application to talk with Twitter. In particular, I'll focus on authentication and updates.

    The OAuth Protocol

    Twitter and Facebook expose their API via web services but it doesn't mean that connecting to these sites is as simple as sending a HTTP GET or POST request. A sophisticated protocol governs the interaction between Twitter and Facebook and their client applications. This protocol is known as OAuth.

    OAuth (see http://oauth.net) is a protocol through which a server application accepts requests from third-party applications to interact with its logged users. Twitter is the canonical example. Twitter, in fact, sets up an OAuth layer through which authors of third-party applications can request to authenticate users and ask authorization to perform some tasks on behalf of Twitter users. OAuth can save third-party applications the burden of maintaining a database of users and can give third-party applications a way to automate the behavior of the OAuth provider. In this article, I'll use OAuth from within an Android application to authenticate a user via his Twitter account and post updates from a mobile phone.

    The OAuth protocol is based on a few steps. First and foremost, the third-party application needs to register with the site that exposes an OAuth interface. You start by visiting the http://dev.twitter.com site and create an account for an application-let's say we call it webTWEETer. At the end of the registration process, Twitter returns a couple of strings that must be used for any successive programmatic access to the site-the consumer key and consumer secret.

    These two keys are always necessary but may not be sufficient for a full interaction with the site. The keys are necessary to obtain from Twitter the authorization to operate on behalf of an agreeable user. To command every single operation, though, you need to perform an extra step and obtain an access token.

    Reasons for Twitter authentication

    The sample application I'm going to build does two basic things: it allows the user to log in to Twitter using her own account and it provides a user interface through which the user can update her Twitter status. Let's tackle the log-in aspect first in the context of an application that behaves like a plain Twitter client.

    Twitter requires that an application interested in using its services directs users to an authorization page on the main site. There, the user is asked to provide her Twitter credentials. If credentials are successfully validated the user is then redirected back to any URL that the application specified. If the client is a web application, the redirect URL is merely another page in the same web application. If the client is a desktop or mobile application, well, things are only a bit more complicated.

    Suppose that you have an Android application with a Login button by tapping which you want your users to authenticate using their Twitter account. You go through the maze of Twitter authentication for one of two main reasons. One reason is that your Android application needs to have a membership system but you don't want to implement it from scratch. The second reason is that you just want to operate on Twitter on behalf of a given user (i.e., make automatic posts).

    In the first case, authentication is your main purpose and the user name is all that you need. In the latter case, authentication is only the means to obtain an access token-a user-specific piece of information that enables holders to operate on behalf of the user.

    Obtaining the Access Token for a Twitter User

    When the user clicks the Login button you open up a web page with the Twitter authentication page. The user types credentials and confirms. What happens next? Where's the user redirected? In an Android application, the user must be redirected back to the originally requesting activity. Let's see some code that will likely be invoked from the handler of a Login button.

    This code is based on Twitter4j-a popular helper library for Twitter programming. You can get Twitter4j at http://twitter4j.org. The first two steps initialize the twitter service and configure it to use the provided consumer key and consumer secret strings. As mentioned, you get these strings from Twitter when you register your application.

    Next, you make a first request to Twitter according to the OAuth protocol. You begin by requesting a request token. A request token is a token that gives you permission to request the canonical Twitter authorization page. When you place the first request you indicate consumer key and secret to identify the registered application that is operating. In addition, you indicate the URL you want Twitter to call back once the authentication and authorization steps are successfully completed. The body of the response you receive is similar to what you see below:

    The Twitter4j library encapsulates this response in an instance of the RequestToken class. In particular, the oauth_token element is used to prepare the URL for the next request. The oauth_token element is the token you need to present in order to get the access token-the passport that enables the software to operate on behalf of the user. The oauth_token element is embedded as a query string parameter in the URL that points to the authorization page where the user will type her credentials and explicitly authorize the software to operate on the account. A sample of the traffic that takes place between the phone and Twitter is illustrated below:

    Figure 1: Traffic due to the initial handshake of OAuth.

    Traffic due to the initial handshake of OAuth.

    In Android, displaying the Twitter web page is your responsibility. The simplest way to display a web page is the following:

    The result is shown in Figure 2.

    Figure 2: Displaying the Twitter authorization page.

    Displaying the Twitter authorization page.

    At the end of the interaction the browser redirects to whatever URL you specified when making the getOAuthRequestToken request. The interesting thing is that in some circumstances Android can capture the browser redirect and bring up an activity. You can drive this behavior from the manifest. Here's what you need to have in the manifest to enable the browser to display a page and capture the redirect:

    In Android an intent-filter indicates a capability of the activity. So the TweetActivity is capable of starting up the application and viewing documents through the browser. The activity is also able to handle any browsable document that matches the provided scheme. The <data> element filters URLs that will be handled by the activity. The custom scheme in the listing just indicates that webtweeting:// is a URL that will be handled by TweetActivity class. At this point, it is not coincidental that the callback URL we passed to Twitter looked like below:

    So the main activity launches the browser on a Twitter authorization URL and is called back when the browser redirects to a URL that activity itself is registered to handle. Which event is then fired on the activity? Is it onCreate or something else? That depends on how you set the launch mode on the activity.

    If you pick up singleInstance (as in the preceding manifest) then only one instance of the activity will be used in the application. Subsequently, when the control returns to the activity you won't pass through onCreate. Instead, the activity is reactivated with a new intent message you can handle via the onNewIntent overridable method:

    In the onNewIntent method you retrieve the oauth_verifier string from the query string of the callback URL. Twitter, in fact, appends the oauth_verifier string to the URL before redirecting. If the oauth_verifier string is null then the user didn't authorize the request; otherwise, you make another request to Twitter and present the oauth_verifier to get the very well deserved access token.

    Saving the Access Token

    The access token is a very valuable piece of information. Twitter4j represents it with an AccessToken object. From the AccessToken object you need to extract at least three data elements-the display name of the user (the Twitter handle), the token string and the token-secret string. The latter two are what enable you to post, read tweets or find followers. This information must be safely stowed to be retrieved when appropriate.

    The SaveLoginInfo method uses any storage mechanism you like to persist the data. In this example, I'm using the shared preferences infrastructure.

    Updating Your Status

    Once you have available the access token strings you can do whatever you like with just a couple of lines of code. Here's how to update your status:

    The access token is based on the user so to log a user out, you just delete the access token strings.

    Summary

    The ability to integrate mobile applications with social networks is a key asset today and will be a necessity soon. Understanding the OAuth protocol is mandatory if you want to interact with Facebook and Twitter and some specialized libraries help reducing the lines of code one has to write. In Java and Android, Twitter4j does a good job of getting the access token and from there automating the authorized account.

    The Android for .NET Developers Series

  • Part 1 Starting with this article, I'll discuss what you need to know to approach Android programming without any aid from your .NET expertise.
  • Part 2 In this article, we'll go through an Android application that accepts input from the user and handles user's clicking.
  • Part 3 In this article, you will learn how to build the user interface.
  • Part 4 In this article, I'll be delving deep into menus and dialog boxes in Android for .NET, and discuss a few very common (and frequently used) types of menus and dialogs.
  • Part 5 In this article, Dino Esposito focuses on the options that the Android SDK offers for local storage.
  • Part 6 In this article, Dino Esposito shows how to build settings dialog boxes using a built-in feature of Android for .NET.
  • Part 7 In this article, I'll dissect the code of a realistic application - a waterpolo score manager - to show how to save and resume the status of a game using both the internal storage and SD card.
  • Part 8 In this article, I'll focus on the execution of common tasks from within an Android application. I'll build the skeleton of an application that takes a photo and emails to the specified address. For both tasks I'll use native Android components.
  • Part 9 In this article, I'll discuss how to arrange an Android view where the dominant element is the list. I'll start with a plain list of strings and then improve up to populating a listview with downloaded content arranged using a custom layout.
  • Part 10 In this article, I'll discuss the features and capabilities required by an Android application to talk with Twitter. In particular, I'll focus on authentication and updates.
  • <<  Previous Article Continue reading and see our next or previous articles Next Article >>

    About Dino Esposito

    Dino Esposito is one of the world's authorities on Web technology and software architecture. Dino published an array of books, most of which are considered state-of-the-art in their respective areas. His most recent books are “Microsoft ® .NET: Architecting Applications for the Enterprise” and “...

    This author has published 54 articles on DotNetSlackers. View other articles or the complete profile here.

    Other articles in this category


    Android for .NET Developers - Location and Maps
    In Windows Phone and iOS getting the current position of the device in terms of latitude and longitu...
    Developing a Hello World Java Application and Deploying it in Windows Azure - Part I
    This article demonstrates how to install Windows Azure Plugin for Eclipse, create a Hello World appl...
    Android for .NET Developers - Using Web Views
    In this article, I'll show a native app that contains a web-based view. The great news is that HTML ...
    Developing a Hello World Java Application and Deploying it in Windows Azure - Part II
    In this article we will see the steps involved in deploying the WAR created in the first part of thi...
    Ref and Out (The Inside Story)
    Knowing the power of ref and out, a developer will certainly make full use of this feature of parame...

    You might also be interested in the following related blog posts


    WPF 4 (VS 2010 and .NET 4.0 Series) read more
    ClientIDMode in ASP.NET 4.0 read more
    OAuth in action Linq2Twitter read more
    TechEd South Africa Slides and Code - .NET RIA Services and ViewModel read more
    WebResource access in ASP.NET MVC read more
    Problems with the clientaccesspolicy.xml for Silverlight access to HTTPS read more
    ASP.NET 4.0 AJAX - Caching Data on the client read more
    Meet Me at PDC2008 -- T-05 Weeks and Counting read more
    Creating a Dynamic Data-Driven User Interface (Part 3) read more
    Creating a Dynamic Data-Driven User Interface (Part 2) read more
    Top
     
     
     

    Please login to rate or to leave a comment.