Archive for the ‘java’ Category

Friday, February 26th, 2010

As I mentioned in my previous post I have been working through  the OpenGL ES 2.0 book and have been porting many of the examples to Android. I am going to go through some of the progress I have made so far.

Besides getting the various Android side of things set up the biggest annoyance I found was that all of the shaders in the examples were hard coded.  They all look something like this inlined in the code:


GLbyte vShaderStr[] =
"attribute vec4 vPosition;    \n"
"void main()                  \n"
"{                            \n"
"   gl_Position = vPosition;  \n"
"}                            \n";

GLbyte fShaderStr[] =
"precision mediump float;\n"\
"void main()                                  \n"
"{                                            \n"
"  gl_FragColor = vec4 ( 1.0, 0.0, 0.0, 1.0 );\n"
"}

Obviously this makes it fairly difficult to edit and test shaders in an external program so the first thing I did was create a mechanism to load a shader from the res/raw/ resource directory, drop it into native code, and compile/link into a shader program .  These code snippets should get you started:

In Android/Dalvik land load a shader into a string:


String vShader = readFileAsString(GL2JNIView.this.getContext().getResources()
.openRawResource(R.raw.vshader));

Send the string to native land and load it into a character array, compile/link the shader program, and free the pointer:


char *vertexShader = env->GetStringUTFChars(vShader, 0);

//load shader program

env->ReleaseStringUTFChars(vShader, vertexShader);

Here is a quick overview of some of the examples I have been working on, screen shots are straight from my Nexus One:

The mighty spinning cube demo, with a simple vertex and color fragment shader.  One major difference between ES 1.x and 2.0 is that all of the transformation functions have been done away with, instead you must manually manipulate a matrix and pass it into the vertex shader and multiply all the vertices by this matrix, fortunately the ES 2.0 book sample code comes with functions that map the old functions to the new approach.

Here is the multi texturing example from Chapter 10 of the ES 2.0 book, multitexturing becomes a fairly simple formula which is performed inside of the fragment shader.

The Cube Map texturing example from Chapter 9 of the book.  ES 2.0 provides a straight forward method for rendering things like reflections on objects by using a cube texture map.

This is a shot of the Particle System demo from Chapter 13 of the book.  It is difficult to get a good screen shot of all of the particle movement.  All of the particle parameter are passed into the shaders and calculations are performed by the GPU.

One of the first things I wanted to do after I got done with the basics was to load a textured .obj model in dalvik/Android and load it into native code and render it using vertex/fragment shaders.  This is a sample model from this very cool OpenGL ES android tutorial/project.

The ES 2.0 book assumes that you already know how to do graphics programming with OpenGL as well as program Shaders , so I have been using many other resources for learning GLSL and graphics programming in general.  I have found that the best resources are usually just OpenGL books from 5 years ago.  This is an example of a sepia filter from this great book: Shaders For Game Programmers And Artists.  The flag also waves using a simple sin() method on the z coord in the vertex shader.

This is a simple 4-sample blur shader from the above book.

This is my attempt at creating a motion blur shader. It renders the cube to a Frame Buffer Object then interpolates between a previous frame.  I haven’t gotten it to perform the proper blending of the two frames but I am pretty close to getting it to work.

Per-Pixel Lighting

I have been trying to get the per pixel lighting example from the ES 2.0 book to work but unfortunately they only provide the Shaders and a RenderMonkey workspace which leaves out some fairly crucial elements for actually getting it to run in code.

Next up I want to get familiar with all the various lighting effects you can do with shaders.  Shaders provide a much more flexible lighting model than the fixed function lighting options in ES 1.x, but it also makes doing lighting not as straight forward as it was.  After that I would like to put together some scenes and maybe get a simple game engine going with flexible shader options.

Friday, February 5th, 2010

* Update: r3 of the Android NDK has been released with OpenGL ES 2.0 support get it here *

The Motorola Droid and the Nexus One are the first Android phones with graphics hardware that support OpenGL ES 2.0.  Developers have not yet had access to the advanced graphics API in the latest Android SDK/NDK , but it looks like official support for ES 2.0 in the Android NDK is imminent as the latest NDK code in the Android Open Source Project includes the libraries needed to access the OpenGL ES 2.0 API.  If you are impatient like I am and would like to dip your toes into the strange world of vertex and fragment shaders,  here is a quick way of getting OpenGL ES 2.0 support up and running in the current release of the Android SDK. ( This has been tested on OS X and a Nexus One, I would imagine it would work with Linux and the Droid too, no idea about Windows)

The first step is to download the latest Android source code from AOSP.  The project we are interested in is in: development/ndk.  Copy the ndk directory wherever you want.  The NDK is  missing the platform specific ARM toolchain binaries so we are just going to get those from the 1.6 release of the NDK which you can find here.  Copy the build/prebuilt/  directory of the 1.6 NDk to the build/ directory of the 2.0 NDK.

The next step is to run the host-setup.sh script in build/

sh build/host-setup.sh

After the set up script runs we are ready to build the sample hello-gl2 that conveniently comes with the new NDK.  This project contains all the code you need to set up the application and native parts to support ES 2.0.

make APP=hello-gl2

This will compile all of the native code and copy the binary to the libs/ directory of the Android project.

After this is finished we can build and install the application found in apps/hello-gl2/project/ onto our Android 2.0+ device and see ES 2.0 in action!

Pretty awesome right?  I will save actual OpenGL ES 2.0 walkthroughs for later as I go through the ES 2.0 book, but the source included in the hello-gl2 project should be enough to get you started.  Obviously this is all unsupported and unofficial and you should more than likely not release apps using these APIs onto the market until the Official SDK is updated.

You certainly wouldn’t want to release a Live Wallpaper using this code because it would probably get 1 star as most users are unimpressed that you got ES 2.0 working ;)

Saturday, June 27th, 2009

By far the most popular post on this blog is the one regarding using OAuth and Java. At that time OAuth, was still fairly new and I was interested in using the Java implementation with some Android applications I had been working on. The Java reference implementation was new, difficult to build, sparsely documented, and the API was confusing to say the least. Months passed and very little was done to the library. I would probably attribute this to the lack of OAuth enabled web services. Public key signing was added eventually, but when Android upgraded to HttpClient 4.0, it broke compatibility with the original OAuth library. A ported version was eventually added to the repository by Sean Sullivan but the library was still fairly difficult to use. I, like many people, swore that I would eventually get around to eventually writing a Java OAuth library that was straight forward and easy to use.

Fortunately for us, Matthias Kappler has written an excellent library called Signpost that uses the standard Java URL class, and also supports HttpClient requests. Signpost does not attempt to perform both signing and requesting like the original library and focuses solely on token acquisition and request signing, which really should be the key parts of any implementation. There are many examples of using Signpost with a number of services, including Twitter and using the new OAuth 1.0a spec that addresses the vulnerability found in the OAuth spec recently.

You can go to the google code site to check out the library and the basics of token request and authorization (including the new “pin” authorization), but I will show you some quick code to perform a status update request with Twitter. This code assumes that you have a valid access token and secret.

Update the user’s status using URL:


       OAuthConsumer consumer = new DefaultOAuthConsumer(
                "yourappkey",
                "yourappsecret",
                SignatureMethod.HMAC_SHA1);
        OAuthProvider provider = new DefaultOAuthProvider(consumer,
                "http://twitter.com/oauth/request_token",
                "http://twitter.com/oauth/access_token",
                "http://twitter.com/oauth/authorize");
        consumer.setTokenAndSecret(AUTH_TOKEN,TOKEN_SECRET);//load these from a db or file
        URL url = new URL("http://twitter.com/statuses/update.xml?status=" + URLEncoder.encode("test one two three"));
        HttpURLConnection request = (HttpURLConnection) url.openConnection();
        request.setRequestMethod("POST");
        consumer.sign(request);
        request.connect();
        if(request.getResponseCode() == 200)
           return true;
       else
           return false;

Performing a status update using HttpClient, assumes mClient is an already initialized HttpClient and excludes exception handling code:


       OAuthConsumer consumer = new DefaultOAuthConsumer(
                "yourappkey",
                "yourappsecret",
                SignatureMethod.HMAC_SHA1);
        OAuthProvider provider = new DefaultOAuthProvider(consumer,
                "http://twitter.com/oauth/request_token",
                "http://twitter.com/oauth/access_token",
                "http://twitter.com/oauth/authorize");
        consumer.setTokenAndSecret(AUTH_TOKEN,TOKEN_SECRET);//load these from a db or file
            Uri.Builder builder = new Uri.Builder();
            builder.appendPath("statuses").appendPath("update.json")
                    .appendQueryParameter("status", status);
            Uri man = builder.build();
            HttpPost post = new HttpPost("http://twitter.com"  + man.toString());
            consumer.sign( post);
            HttpResponse resp = mClient.execute(post);
            if (resp.getStatusLine().getStatusCode() == 200) {
                    return true;
                } else {
                    return false;
                }

Hopefully you will also find Signpost to be as useful as I did. I was able to migrate my twitter application from using basic authentication to using OAuth with Signpost in an hour compared to the hours of pain spent trying to use the original implementation.

Filed under identity, java | 1 Comment »

Tuesday, February 10th, 2009

Android 1.1 was released this week and included a voice search application as part of the update. Like most parts of Android the speech recognition functionality has been abstracted into sub tasks that use intents to perform specific actions. You can now call an intent that will launch the speech recognizer “application” and return to your application a list of results. The Intent and a description of it’s results can be found in the Android source code in the android.speech package. This library is not officially supported by the Android SDK and it should not be used in any consumer facing applications. That said you should also make sure to include “” in your application’s manifest file so that the app cannot be installed on a phone that doesn’t have the 1.1 firmware on it.

Here is the code for launching a simple speech recognition intent:


Intent intent = new Intent("android.speech.action.RECOGNIZE_SPEECH");
startActivityForResult(intent, 0);

The intent launches the voice recognition activity which prompts the user to speak into the phone, your speech is then analyzed and a list of results is returned in a bundle to your activity.

Here is the code for extracting the results:


@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		...code for checking resultCode and data intent...
	ArrayList<String> results = data.getExtras().getStringArrayList("results");

	}

As you can see this makes it very easy to add a speech recognition element to an application, although I am not sure whether or not this functionality will be officially supported in a future version of the SDK.

h1h2h3h4

Filed under android, java | 3 Comments »

Monday, August 25th, 2008

QR Codes are a great way to share information with mobile phones. Originally used to track car parts, QR codes are now used to quickly and easily spread information to mobile users. For example a company can put a QR code in a magazine that contains the URL to their website. Instead of the user having to type in a long URL on their phone they can simply take a picture of the QR Code with their camera phone and have their decoding software open the link for them. For more uses of QR Codes check out this blog.

I am going to go through a quick example of encoding and decoding QR codes in Android.

Encoding

There are a number of services and libraries available for encoding QR Codes. The actual encoding process is a bit more involved than I would like to go through for this entry and we generally would not want to do the actual encoding on the client. Instead we will harness the power of the “cloud” to do the heavy lifting for us. In this case we will use the Google Charts API which just recently expanded to include QR codes. The API allows for a number of options such as size, error correction type, encoding type, and margins (the general rule for QR Codes is to have a 4 column/row white border around the barcode so that the decoding software can get a better “lock” on it)

The code below makes an http request to the Google Charts API with the URL encoded text we entered in the EditText view and populates our ImageView with the resulting image.


encodeButton.setOnClickListener(new OnClickListener(){

public void onClick(View arg0) {
    img.setImageBitmap(QR.this.encodeString(edit.getText().toString()));
}

});

private Bitmap encodeString(String input) {
     URL aURL;
     try {
      aURL = new URL("http://chart.apis.google.com/chart?chs=300x300&cht=qr&choe=UTF- 8chl="+URLEncoder.encode(input, "UTF-8"));
      URLConnection conn = aURL.openConnection();
      conn.connect();
      InputStream is = conn.getInputStream();
      BufferedInputStream bis = new BufferedInputStream(is);
      Bitmap bm = BitmapFactory.decodeStream(bis);
      bis.close();
      is.close();
      return bm;
      } catch (MalformedURLException e) {
       e.printStackTrace();
      } catch (IOException e) {
       e.printStackTrace();
      }
     return null;
}

Decoding

The ZXing library is an open source Java library for decoding numerous 1D and 2D barcodes. We will be using the core library but there is also an Android specific application that provides hooks into the camera. Since the emulator does not support capturing images just yet we will settle for using the image we just encoded. We will need one class specific to the Android ZXing library, RGBMonochromeBitmapSource which lets us convert Android bitmaps to the format that ZXing uses.

The code below takes the bitmap image from the ImageView and pushes it through the decoder populating a TextView.


decodeButton.setOnClickListener(new OnClickListener(){

public void onClick(View arg0) {

     try {
      tv.setText(((QR.this.decode(img.getDrawingCache()))));
     } catch (ReaderException e) {
      e.printStackTrace();
     }
}
});

private String decode(Bitmap bm) throws ReaderException {
     QRCodeReader reader = new QRCodeReader();
     Result r = reader.decode( new RGBMonochromeBitmapSource(bm));
     return r.getText();
}

We can use our friend Linkify to automatically make any text of the correct format (http://, mailto:, and even map locations) into a link that launches the appropriate application.


textView.setAutoLinkMask(Linkify.ALL);



I have even been experimenting with integrating the decoder with the built in WebView class which lets us decode images directly from the web browser. As you can see in this example I have clicked on a QR Code and a dialog pops up with the decoded information.

The code to do this is a little hackish but involves using the WebView.requestImageRef(msg) mechanism and calling decode from the handler that receives that message.

I know of a number of decoders being developed for android but hopefully there will be a standard one that can be called using Intents so that developers can just fire off an intent in their application and get text back, not having to worry about dealing with the camera or the decoder libraries.

Thursday, March 20th, 2008

OpenID is an open standard for decentralized authentication. The OpenID site has plenty of detailed documentation about the protocol so I will briefly explain the basics needed to understand how to integrate OpenID authentication into your grails project.

OpenID Provider
A user registers an OpenID through an OpenID provider. This is the site that provides the identifying URL for the user and handles the authentication request from the Relying Party.

There are a number of OpenID providers out there, with new ones cropping up all the time. I use myopenid simply because it was one of the first openid providers I had heard of. Many sites also provide an OpenID when you sign up for their service. This has lead to OpenID providers that aggregate all of your other OpenIDs. Since we want to drive adoption and there are probably more providers than consumers at this point, we are going to focus on just being an OpenID relying party.

Relying Party
The relying party is the web service that uses OpenID to handle it’s authentication. It prompts the user for their OpenID URL and redirects the user’s browser to the Provider’s authentication page, the provider prompts the user with information about the site making the authentication request, allows the user to accept or reject authentication with the site and then redirects the user back to the relying party with an authentication token that the relying party then verifies. The user never enters a password with the relying party, the provider can also allow automatic authentication with the relying party if they so choose.

Discovery
You can use any web address as your OpenID simply by including the following html in the head tag of your site.


<link rel="openid.server" href="http://youropenidserverendpoint">
<link rel="openid.delegate" href="http://youropenid/url">

This lets you use your blog and any other site you may have as your OpenID. The relying party will parse this information from whatever URL you pass to it.

Setup
I am using code and comments taken from the OpenID4Java getting started page and adapting it for quick integration with grails. If you need anymore detail than I have provided you should check out their wiki. The full source code for our example can be found here: UserController.groovy

1. Sign up for an OpenID, we want one to ease testing obviously.

2. Download the excellent OpenID java library OpenID4java and put the jar and its dependencies in your lib directory. Watch out for dependency versioning conflicts since grails uses many of the same dependencies.

3. For our example we will use a User controller, so go ahead and create a user controller. I won’t really go into modelling a User domain class but with OpenID you can skip all of the password management and storage and simply have a field for their OpenID URL instead.

Getting Started

We need to specify a return URL that the provider will redirect to after authentication is finished. You can store this in a number of places but I will just put it in the UserController. This URL corresponds to the auth action will will implement in UserController.


String _returnURL = "http://localhost:8080/openidtest/user/auth";

The controller actions share a ConsumerManager that is used to perform various steps of the OpenID authentication, I made it a static variable in the UserController because it seems to not work otherwise, there is probably a better way to do this.


  static ConsumerManager manager = new ConsumerManager();

Actions
We will define a few actions on our controller, these will be used to initiate and verify the OpenID authentication process.

login
The first action is login, this action simply presents the user with an OpenID entry field.


def login = {

    		if(session.user){
    			redirect(action: 'index') //redirect to main user page
    		}
    }

If the user is already logged in we redirect.

Here is gsp code for including an OpenID login field for your app, include it in your login.gsp view. Don’t forget to save the OpenID icon to your images directory.


<img src="${createLinkTo(dir:'images',file:'icon_openid.gif')}" alt="openid_logo" />
<g:form name="loginForm" action="handleLogin"><g:textField name="openid" value="http://yourname.myopenid.com" />
<g:actionSubmit value="Login" action="handleLogin" />
</g:form>

handleLogin
This action will take the user’s OpenID URL, create an authentication request and redirect the user to their OpenID Provider.


def handleLogin = {

    try{
		// disable realm verification
    		 RealmVerifier rv = new RealmVerifier();
    		 rv.setEnforceRpId(false);
    		 manager.setRealmVerifier(rv)

    		 // perform discovery on the user-supplied identifier
    		    List discoveries = manager.discover(params['openid']);
    		    DiscoveryInformation discovered = manager.associate(discoveries);

    		    // store the discovery information in the user's session for later use
    		    session.discovered = discovered

    		    // obtain a AuthRequest message to be sent to the OpenID provider
    		    AuthRequest authReq = manager.authenticate(discovered, _returnURL);

    		    response.sendRedirect authReq.getDestinationUrl(true)
    		    }catch(DiscoveryException e){
    		    	//add flash message , failed to find openid at address
    		    	flash.message = "Failed to find valid openid URI at specified address"
    		    	redirect(action:'login')
    		    }
    }

auth
The auth action is the action specified by our service that the OpenID provider will redirect the user to after authenticating with the provider. The provider includes a number of parameters so that the relying party can verify that the user has actually authenticated with the provider.


 def auth = {

    	    // check if this is an openid message, this is to avoid someone
	    // calling the auth action themselves
    	    if(!params['openid.mode']){
    	    	redirect(action:'err')
    	    return;
    	    }

    	    ParameterList openidResp = new ParameterList(request.getParameterMap());

    	    // retrieve the previously stored discovery information
    	    DiscoveryInformation discovered = (DiscoveryInformation) session.discovered;

    	    // extract the receiving URL from the HTTP request
	    // is there an easier way to get the full path including servername and port?
    	    StringBuffer receivingURL = new StringBuffer('http://' + request.getServerName() + ':' +
  request.getServerPort() +request.forwardURI);
    	    String queryString = request.getQueryString();
    	    if (queryString != null && queryString.length() != 0)
    	        receivingURL.append('?').append(request.getQueryString());

    	    // verify the response
    	    VerificationResult verification = manager.verify(receivingURL.toString(), openidResp, discovered);

    	    // examine the verification result and extract the verified identifier
    	    Identifier verified = verification.getVerifiedId();

    	    if (verified != null){
    	    	//User.findByUrl(verfied.getIdentifier())
    	    	session.user = verified
    	    	 // success, use the verified identifier to identify the user
    	    	redirect(action: 'index')

    	    }else{
    	        // OpenID authentication failed
    	        redirect(action: 'err')
    	    }

    }

request.forwardURI is a grails specific method that actually calls request.request.requestURI, this is needed to verify the previously called URL that made the authentication call to the provider.

err
The err action is the action we will redirect to if our authentication fails at any point. You can probably get away with just redirecting the the grails default error page.

Filter
Our final step is to set up an Authentication filter like the one we made for basic authentication . The only difference is that we have a number of controller actions that we want to allow to pass the filter, like login, handleLogin, auth, and err.


class SecurityFilters {
	class SecurityFilters {
	def filters = {
			loginCheck(controller:'*', action:'*') {
		           before = {
		        		   log.trace("inside of filter")
		              if(!session.user && !actionName.equals('login') &amp;amp;&amp;amp; !actionName.equals('handleLogin') && !actionName.equals('auth') && !actionName.equals('err')) {
		                  redirect(controller:'user' , action:'login')
		                  return false
		               }
		           }

		}
	}
}

OpenID, Authorization, and APIs
Since OpenID focuses on authentication there is not currently a good way to incorporate OpenID with API calls. Having to redirect a user to a web page is not something someone programming a mobile or desktop application wants to do in order to make API calls. There have been rumblings of integrating an API http header authorization mechanism into the OpenID standard, and of course you could always integrate OAuth and OpenID so the user would only have to do web based authorization once for your application.

Thursday, March 13th, 2008

Update 2 See this post or just skip straight to this excellent library for all of your OAuth and Java needs

*Update* The code in this entry no longer works with the Android SDK because of the upgrade to HttpClient 4. The OAuth Java library has been updated to work with HttpClient 4 but I have not looked at it recently *Update*
Fire eagle is a Yahoo! location sharing service that provides an API that allows external clients and services to update and query user location information. Besides the obvious interesting connection between a location sharing service and Android’s Location-Based-Services API, I became more interested in how fire eagle uses OAuth as it’s authorization scheme and how it can be used on a smart mobile device.

OAuth is an open authentication protocol that allows access to web service resources from other web services as well as desktop applications. Other open authentication schemes, like OpenID, use http redirects and require users input credentials onto a web page in order to authorize clients. This isn’t very useful for a desktop or mobile client that would like direct access to a web API. OAuth still requires the user to enter their credentials into a website, but this is only done during the initial application authorization step, after that step is complete the application can make authorized API calls directly without needing user intervention.

A web service that uses OAuth will let application developers to register for a consumer key which is paired with a consumer secret. The consumer key is used to identify the client application and the consumer secret is used to sign requests made by the client application which is then verified by the host web service.

Here is a general outline of the OAuth process from a client application’s perspective:
1. The client requests a request token from the service. They include their consumer key and a few other OAuth specific parameters including a hash signature using the consumer secret.The service replies with a request token.
2. The client application then directs the user to the service’s authorization page, with the request token as a parameter, where the user can log into the service and authorize the application to access their information.
3. Once the user is finished authorizing, the client application needs to request an access token which will be used to make authorized calls to the service’s API. The service replies to the request with an access token and access secret. The application needs to save both of these securely.
4. The client application can now make API calls by including the user’s access token, and signing the oauth parameters with the access secret.

Laserbeak
I am going to attempt to walk through a “simple” android application that performs the request and authorization steps of OAuth as well as makes an update call to fire eagle with the current location of the phone.

Setup
The first step will be getting your own application key and secret token from the fireeagle service. Fire eagle is currently invite-only but there are plenty of invites floating around.

The second step is to setup a new android project and give it GPS and LOCATION permissions.

The third step will be getting the OAuth java libraries from the OAuth Java repository. Since the libraries use the apache-commons and http libraries that are already included in android you can simply drop the net.oauth, net.oauth.client, and net.oauth.signature into your source directory. Note: The OAuth java libraries aren’t “finished” and not as well documented as the libraries for other languages but I have found them to be fairly straight forward and functional.

The Application
We will create a simple application that consists of an activity with three buttons. Each button’s onClick event will trigger a step in our authorization process. Complete source code for this activity can be found here

Initializing the OAuth provider, consumer, and accessor in the Activity’s OnCreate method:


		serviceProvider = new OAuthServiceProvider(OAUTH_REQUEST,
				OAUTH_AUTHORIZE, OAUTH_ACCESS);

		consumer = new OAuthConsumer("http://www.noredirectfordesktop.com",
				CONSUMER_KEY, CONSUMER_SECRET, serviceProvider);

		accessor = new OAuthAccessor(consumer);

		httpClient = new OAuthHttpClient(new HttpClientPool() {

			public HttpClient getHttpClient(URL server) {
				return new HttpClient();
			}
		});

Here we initialize the classes that will be used to make OAuth requests to the Fire eagle service, we include the three URLs as well as the consumer key and consumer secret. All of the OAuth specific parameters and operations will be performed by these classes.

The request token button:


Button requestButton = (Button) this.findViewById(R.id.req_button);
		requestButton.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {

				try {
					httpClient.getRequestToken(accessor);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				// manually set the access token to the request token...not sure
				// why
				accessor.accessToken = accessor.requestToken;

				// start browser application so user can authorize your
				// application
				Intent authIntent = new Intent(Intent.VIEW_ACTION);
				authIntent.setData(Uri.parse(FIRE_EAGLE_AUTHORIZE_URL
						+ accessor.requestToken));
				Laserbeak.this.startActivity(authIntent);
			}

		});

Here we use the built in getRequestToken method to make a token request to the service. If all goes well the token is stored in the requestToken field of the accessor, for the authorization step we need to manually set the accessToken field on the accessor to equal the requestToken.
The next step is interesting in that we need to have the user manually authorize our application, android makes it easy to launch the browser to the authorization URL using a VIEW_ACTION intent. This will launch a browser that the user can use and once they are finished they can simply close the browser and return to the application which is still running in the background.

The authorize button:


Button authButton = (Button) this.findViewById(R.id.auth_button);
		authButton.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {

				try {

					OAuthResponseMessage response = (OAuthResponseMessage) httpClient
							.invoke(accessor.newRequestMessage("GET",
									serviceProvider.accessTokenURL, null));

					// manually set these fields on the accessor from the
					// response
					accessor.accessToken = response.getParameter("oauth_token");
					accessor.tokenSecret = response
							.getParameter("oauth_token_secret");

					//at this point you should store the accessToken and tokenSecret
					//somewhere secure
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

		});

Our application is now authorized to make API calls, lets try calling update with the current Lat/Lon of our phone


Button updateButton = (Button) this.findViewById(R.id.update_button);
		updateButton.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {

					// get current location and use it as params to our API call
					LocationManager locMan = (LocationManager) Laserbeak.this
							.getSystemService(Context.LOCATION_SERVICE);
					Location loc = locMan.getCurrentLocation("gps");

					HashMap params = new HashMap();
					params.put("lat", loc.getLatitude());
					params.put("lon", loc.getLongitude());
					try {

						OAuthResponseMessage response2 = (OAuthResponseMessage) httpClient
								.invoke(accessor.newRequestMessage("POST",
										FIRE_EAGLE_UPDATE_URL, params
												.entrySet()));
					} catch (Exception e) {
						e.printStackTrace();
					}

			}
		});

Here we get the LocationManager and get the user’s current latitude and longitude and put them in a parameter map to be used in the request.

Those are the basic steps for using OAuth and fire eagle. There are a number of things I left out like saving and accessing the access token and access secret from a secure place, as well as saving the state of the accessor for when your application gets interrupted by an incoming call. You could also create a service that updates your location periodically in the background instead of explicitly updating it in an activity.

Unfortunately due to security issues, desktop and mobile applications are only allowed to access the user and update API calls. The more interesting calls that allow you to query all the users of your application and create a social location network are restricted to web applications.

Now that you know how to authorize an application in OAuth you can use the above steps to interact with any other OAuth capable API, like pownce.