<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>a walking city</title>
	<atom:link href="http://awalkingcity.com/blog/feed/" rel="self" type="application/rss+xml" />
	<link>http://awalkingcity.com/blog</link>
	<description></description>
	<lastBuildDate>Mon, 08 Mar 2010 22:22:24 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Android OpenGL ES 2.0 Progress</title>
		<link>http://awalkingcity.com/blog/2010/02/26/android-opengl-es-2-0-progress/</link>
		<comments>http://awalkingcity.com/blog/2010/02/26/android-opengl-es-2-0-progress/#comments</comments>
		<pubDate>Sat, 27 Feb 2010 00:45:52 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[android]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[mobile]]></category>

		<guid isPermaLink="false">http://awalkingcity.com/blog/?p=379</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p>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.</p>
<p>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:</p>
<pre name="code" class="c">

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

GLbyte fShaderStr[] =
&quot;precision mediump float;\n&quot;\
&quot;void main()                                  \n&quot;
&quot;{                                            \n&quot;
&quot;  gl_FragColor = vec4 ( 1.0, 0.0, 0.0, 1.0 );\n&quot;
&quot;}
</pre>
<p>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:</p>
<p>In Android/Dalvik land load a shader into a string:</p>
<pre name="code" class="java">

String vShader = readFileAsString(GL2JNIView.this.getContext().getResources()
.openRawResource(R.raw.vshader));
</pre>
<p>Send the string to native land and load it into a character array, compile/link the shader program, and free the pointer:</p>
<pre name="code" class="c">

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

//load shader program

env-&gt;ReleaseStringUTFChars(vShader, vertexShader);
</pre>
<p>Here is a quick overview of some of the examples I have been working on, screen shots are straight from my Nexus One:</p>
<p style="text-align: center;"><a href="http://awalkingcity.com/blog/wp-content/uploads/2010/02/spincube.png"><img class="size-full wp-image-382  aligncenter" title="spincube" src="http://awalkingcity.com/blog/wp-content/uploads/2010/02/spincube.png" alt="" width="400" height="240" /></a></p>
<p>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.</p>
<p style="text-align: center;"><a href="http://awalkingcity.com/blog/wp-content/uploads/2010/02/mt.png"><img class="aligncenter size-full wp-image-383" title="mt" src="http://awalkingcity.com/blog/wp-content/uploads/2010/02/mt.png" alt="" width="173" height="288" /></a></p>
<p style="text-align: center;"><a href="http://awalkingcity.com/blog/wp-content/uploads/2010/02/mt.png"></a>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.</p>
<p style="text-align: center;">
<p style="text-align: center;"><a href="http://awalkingcity.com/blog/wp-content/uploads/2010/02/cubemap.png"><img class="aligncenter size-full wp-image-388" title="cubemap" src="http://awalkingcity.com/blog/wp-content/uploads/2010/02/cubemap.png" alt="" width="173" height="288" /></a></p>
<p style="text-align: center;">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.</p>
<p style="text-align: center;"><a href="http://awalkingcity.com/blog/wp-content/uploads/2010/02/particles.png"><img class="aligncenter size-full wp-image-387" title="particles" src="http://awalkingcity.com/blog/wp-content/uploads/2010/02/particles.png" alt="" width="173" height="288" /></a></p>
<p style="text-align: center;">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.</p>
<p style="text-align: center;"><a href="http://awalkingcity.com/blog/wp-content/uploads/2010/02/ship.png"><img class="aligncenter size-full wp-image-389" title="ship" src="http://awalkingcity.com/blog/wp-content/uploads/2010/02/ship.png" alt="" width="173" height="288" /></a></p>
<p style="text-align: center;">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 <a href="http://code.google.com/p/android-gamedev/">OpenGL ES android tutorial/project</a>.</p>
<p style="text-align: center;"><a href="http://awalkingcity.com/blog/wp-content/uploads/2010/02/sepia.png"><img class="aligncenter size-full wp-image-385" title="sepia" src="http://awalkingcity.com/blog/wp-content/uploads/2010/02/sepia.png" alt="" width="173" height="288" /></a></p>
<p style="text-align: center;">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: <a href="http://books.google.com/books?id=iggJf7oIly8C&amp;lpg=PP1&amp;ots=kqZk-SuOcN&amp;dq=Shaders%20for%20Game%20Programmers&amp;pg=PP1#v=onepage&amp;q=&amp;f=false">Shaders For Game Programmers And Artists</a>.  The flag also waves using a simple sin() method on the z coord in the vertex shader.</p>
<p style="text-align: center;"><a href="http://awalkingcity.com/blog/wp-content/uploads/2010/02/blur.png"><img class="aligncenter size-full wp-image-386" title="blur" src="http://awalkingcity.com/blog/wp-content/uploads/2010/02/blur.png" alt="" width="173" height="288" /></a></p>
<p style="text-align: center;">This is a simple 4-sample blur shader from the above book.</p>
<p style="text-align: center;"><a href="http://awalkingcity.com/blog/wp-content/uploads/2010/02/mb.png"><img class="aligncenter size-full wp-image-384" title="mb" src="http://awalkingcity.com/blog/wp-content/uploads/2010/02/mb.png" alt="" width="173" height="288" /></a></p>
<p style="text-align: center;">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&#8217;t gotten it to perform the proper blending of the two frames but I am pretty close to getting it to work.</p>
<p style="text-align: center;">
<p style="text-align: center;">Per-Pixel Lighting</p>
<p style="text-align: center;">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.</p>
<p style="text-align: center;">
<p style="text-align: left;">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.</p>
]]></content:encoded>
			<wfw:commentRss>http://awalkingcity.com/blog/2010/02/26/android-opengl-es-2-0-progress/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Using OpenGL ES 2.0 With Android 2.0 and up</title>
		<link>http://awalkingcity.com/blog/2010/02/05/using-opengl-es-2-0-with-android-2-0-and-up/</link>
		<comments>http://awalkingcity.com/blog/2010/02/05/using-opengl-es-2-0-with-android-2-0-and-up/#comments</comments>
		<pubDate>Sat, 06 Feb 2010 00:27:38 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[android]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[mobile]]></category>

		<guid isPermaLink="false">http://awalkingcity.com/blog/?p=365</guid>
		<description><![CDATA[* 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 , [...]]]></description>
			<content:encoded><![CDATA[<p>* Update: r3 of the Android NDK has been released with OpenGL ES 2.0 support get it <a href="http://android-developers.blogspot.com/2010/03/android-ndk-r3.html">here</a> *</p>
<p>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)</p>
<p>The first step is to <a href="http://source.android.com/download">download</a> the latest Android source code from <a href="http://source.android.com">AOSP</a>.  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 <a href="http://d.android.com/sdk/ndk/1.6_r1/index.html">here</a>.  Copy the build/prebuilt/  directory of the 1.6 NDk to the build/ directory of the 2.0 NDK.</p>
<p>The next step is to run the host-setup.sh script in build/</p>
<blockquote><p>sh build/host-setup.sh</p></blockquote>
<p>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.</p>
<blockquote><p>make APP=hello-gl2</p></blockquote>
<p>This will compile all of the native code and copy the binary to the libs/ directory of the Android project.</p>
<p>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!</p>
<p style="text-align: center;"><a href="http://awalkingcity.com/blog/wp-content/uploads/2010/02/hax.png"><img class="size-full wp-image-367  aligncenter" title="hax" src="http://awalkingcity.com/blog/wp-content/uploads/2010/02/hax.png" alt="" width="240" height="400" /></a></p>
<p>Pretty awesome right?  I will save actual OpenGL ES 2.0 walkthroughs for later as I go through the<a href="http://opengles-book.com/"> ES 2.0 book</a>, 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.</p>
<p>You certainly wouldn&#8217;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 <img src='http://awalkingcity.com/blog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p style="text-align: center;"><a href="http://awalkingcity.com/blog/wp-content/uploads/2010/02/wpaper.png"><img class="size-full wp-image-368  aligncenter" title="wpaper" src="http://awalkingcity.com/blog/wp-content/uploads/2010/02/wpaper.png" alt="" width="240" height="400" /></a><a href="http://awalkingcity.com/blog/wp-content/uploads/2010/02/red.png"><img class="aligncenter size-full wp-image-374" title="red" src="http://awalkingcity.com/blog/wp-content/uploads/2010/02/red.png" alt="" width="400" height="240" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://awalkingcity.com/blog/2010/02/05/using-opengl-es-2-0-with-android-2-0-and-up/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Applications And The New Year</title>
		<link>http://awalkingcity.com/blog/2010/01/03/applications-and-the-new-year/</link>
		<comments>http://awalkingcity.com/blog/2010/01/03/applications-and-the-new-year/#comments</comments>
		<pubDate>Mon, 04 Jan 2010 00:11:55 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://awalkingcity.com/blog/?p=333</guid>
		<description><![CDATA[Over two years have passed since the first Android SDK was released.  The first entry on this blog was written a little under two years ago.  It has been a long, fun ride and even though this blog hasn&#8217;t been too active I have been working with Android much of that time.
For the last one [...]]]></description>
			<content:encoded><![CDATA[<p>Over two years have passed since the first Android SDK was released.  The first entry on this blog was written a little under two years ago.  It has been a long, fun ride and even though this blog hasn&#8217;t been too active I have been working with Android much of that time.</p>
<p>For the last one and a half years I have been working on a full time Android consulting project.  The contract doesn&#8217;t let me talk about what I do during the day, but I have kept myself busy in my spare time with some personal projects as well as a tiny bit of side-client work.  I have decided to create a <a href="http://awalkingcity.com/blog/applications/">&#8220;portfolio&#8221;</a>, of sorts, of some of my most complete and polished applications.  I have written some short descriptions of some of the more interesting pieces of each application and a little background on how they came about.  They are all available on the Android Market and feedback is definitely welcome.</p>
<p>We are just a few days away from the public release of the Nexus One and Android is finally getting the attention it deserves.  This will be the year that Android really breaks out with tons of devices on the way.  It is a great time to be an Android developer and I definitely look forward to all the new opportunities this exciting year will bring!</p>
<p><a href="http://awalkingcity.com/blog/applications/">Applications</a><br />
<a href="http://awalkingcity.com/blog/applications/visible-vote/"><img class="alignleft size-full wp-image-282" title="vv2" src="http://awalkingcity.com/blog/wp-content/uploads/2010/01/vv2.png" alt="" width="240" height="360" /></a><a href="http://awalkingcity.com/blog/applications/rev3remote/"><img class="alignleft size-full wp-image-319" title="r3" src="http://awalkingcity.com/blog/wp-content/uploads/2009/12/r3.png" alt="" width="240" height="360" /></a><a href="http://awalkingcity.com/blog/applications/tweet-assist/"><img class="alignleft size-full wp-image-273" title="zaneshott" src="http://awalkingcity.com/blog/wp-content/uploads/2010/01/zaneshott.png" alt="" width="240" height="360" /></a></p>
<p style="text-align: center;"><a href="http://awalkingcity.com/blog/applications/emotiparty/"><img class="size-full wp-image-262 aligncenter" title="emo2" src="http://awalkingcity.com/blog/wp-content/uploads/2010/01/emo2.png" alt="" width="240" height="360" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://awalkingcity.com/blog/2010/01/03/applications-and-the-new-year/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Java, OAuth, Signpost</title>
		<link>http://awalkingcity.com/blog/2009/06/27/java-oauth-signpost/</link>
		<comments>http://awalkingcity.com/blog/2009/06/27/java-oauth-signpost/#comments</comments>
		<pubDate>Sun, 28 Jun 2009 05:47:59 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[identity]]></category>
		<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://awalkingcity.com/blog/?p=163</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p>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 <a href="http://code.google.com/p/jfireeagle/">Sean Sullivan</a> 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.  </p>
<p>Fortunately for us, Matthias Kappler has written an excellent library called <a href="http://code.google.com/p/oauth-signpost/">Signpost</a> 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 <a href="http://code.google.com/p/oauth-signpost/">Signpost</a> with a number of services, including <a href="http://code.google.com/p/oauth-signpost/wiki/TwitterAndSignpost">Twitter</a> and using the new <a href="http://oauth.net/core/1.0a">OAuth 1.0a</a> spec that addresses the <a href="http://blog.oauth.net/2009/04/22/acknowledgement-of-the-oauth-security-issue/">vulnerability</a> found in the OAuth <a href="http://oauth.net/core/1.0a">spec</a> recently.</p>
<p>You can go to the google code site to check out the library and the basics of token request and authorization (including the new &#8220;pin&#8221; 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.</p>
<p>Update the user&#8217;s status using URL:</p>
<pre name="code" class="java">

       OAuthConsumer consumer = new DefaultOAuthConsumer(
                &quot;yourappkey&quot;,
                &quot;yourappsecret&quot;,
                SignatureMethod.HMAC_SHA1);
        OAuthProvider provider = new DefaultOAuthProvider(consumer,
                &quot;http://twitter.com/oauth/request_token&quot;,
                &quot;http://twitter.com/oauth/access_token&quot;,
                &quot;http://twitter.com/oauth/authorize&quot;);
        consumer.setTokenAndSecret(AUTH_TOKEN,TOKEN_SECRET);//load these from a db or file
        URL url = new URL(&quot;http://twitter.com/statuses/update.xml?status=&quot; + URLEncoder.encode(&quot;test one two three&quot;));
        HttpURLConnection request = (HttpURLConnection) url.openConnection();
        request.setRequestMethod(&quot;POST&quot;);
        consumer.sign(request);
        request.connect();
        if(request.getResponseCode() == 200)
           return true;
       else
           return false;
</pre>
<p>Performing a status update using HttpClient, assumes mClient is an already initialized HttpClient and excludes exception handling code:</p>
<pre name="code" class="java">

       OAuthConsumer consumer = new DefaultOAuthConsumer(
                &quot;yourappkey&quot;,
                &quot;yourappsecret&quot;,
                SignatureMethod.HMAC_SHA1);
        OAuthProvider provider = new DefaultOAuthProvider(consumer,
                &quot;http://twitter.com/oauth/request_token&quot;,
                &quot;http://twitter.com/oauth/access_token&quot;,
                &quot;http://twitter.com/oauth/authorize&quot;);
        consumer.setTokenAndSecret(AUTH_TOKEN,TOKEN_SECRET);//load these from a db or file
            Uri.Builder builder = new Uri.Builder();
            builder.appendPath(&quot;statuses&quot;).appendPath(&quot;update.json&quot;)
                    .appendQueryParameter(&quot;status&quot;, status);
            Uri man = builder.build();
            HttpPost post = new HttpPost(&quot;http://twitter.com&quot;  + man.toString());
            consumer.sign( post);
            HttpResponse resp = mClient.execute(post);
            if (resp.getStatusLine().getStatusCode() == 200) {
                    return true;
                } else {
                    return false;
                }
</pre>
<p>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.</p>
]]></content:encoded>
			<wfw:commentRss>http://awalkingcity.com/blog/2009/06/27/java-oauth-signpost/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Using Java With The Twitter Streaming API</title>
		<link>http://awalkingcity.com/blog/2009/06/22/using-java-with-the-twitter-streaming-api/</link>
		<comments>http://awalkingcity.com/blog/2009/06/22/using-java-with-the-twitter-streaming-api/#comments</comments>
		<pubDate>Tue, 23 Jun 2009 05:03:29 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://awalkingcity.com/blog/?p=155</guid>
		<description><![CDATA[Twitter recently made a streaming API available that allows developers to get real-time status updates using HTTP streaming.  You can read about the specifics of the API here.  There are a few different levels of streaming that developers can use, most of the more heavyweight streams require explicit permission and some kind of [...]]]></description>
			<content:encoded><![CDATA[<p>Twitter recently made a streaming API available that allows developers to get real-time status updates using HTTP streaming.  You can read about the specifics of the API <a href="http://apiwiki.twitter.com/Streaming-API-Documentation">here</a>.  There are a few different levels of streaming that developers can use, most of the more heavyweight streams require explicit permission and some kind of agreement with Twitter.  Streams are available in JSON and XML, you can also get a delimited stream which tells you how many bytes each status uses to make I/O a little easier. I am going to show you how to use  <a href="http://hc.apache.org/downloads.cgi">Apache HttpClient 4.0</a> and the <a href="http://www.extreme.indiana.edu/xgws/xsoap/xpp/mxp1/">XPP XML Pull Parser library</a> to write a simple client to consume the publicly available &#8220;spritzer&#8221; stream.  </p>
<p><strong>Setting Up The Client</strong><br />
The first step is to set up the HTTP client.  The API uses your twitter username and password with basic authentication to authenticate. We will configure our HttpClient with our twitter user name and password as the credentials for the &#8220;stream.twitter.com&#8221; scope.</p>
<pre name="code" class="java">

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, &quot;utf-8&quot;);

         SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme(&quot;http&quot;, PlainSocketFactory.getSocketFactory(), 80));

         ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(params,
                registry);
        DefaultHttpClient client = new DefaultHttpClient(manager, params);

        client.getCredentialsProvider().setCredentials(new AuthScope(&quot;stream.twitter.com&quot;, 80),
                new UsernamePasswordCredentials(&quot;username&quot;, &quot;password&quot;));
</pre>
<p><strong>Requesting And Parsing</strong><br />
Next we will create the Get request for the &#8220;spritzer&#8221; stream and perform the request.  After that we will open a pull parser on the network stream and &#8220;pull&#8221; the xml from the stream as it comes in. </p>
<p>Each status update comes in the format: </p>
<pre name="code" class="xml">

&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;status&gt;
....
&lt;/status&gt;
</pre>
<p>It is important to note that each status has the xml document tag at the beginning. </p>
<p>Most of the parsing code is the result of a lot of trial and error so it is not the prettiest.  See the comments towards the bottom for some important comments about the implementation.</p>
<pre name="code" class="java">

        HttpGet get = new HttpGet(&quot;http://stream.twitter.com/spritzer.xml&quot;);
        try {
            HttpResponse resp = client.execute(get);
            int statusCode = resp.getStatusLine().getStatusCode();

        if (statusCode == 200) {
                InputStream stream = resp.getEntity().getContent();
                XmlPullParserFactory factory;
                factory = XmlPullParserFactory.newInstance();
                XmlPullParser parser = factory.newPullParser();

                parser.setInput(stream, &quot;utf-8&quot;);
                while (true) {
                    int event = parser.next();
                    if (event == XmlPullParser.START_TAG) {
                        String name = parser.getName();
                        if (name.equals(&quot;status&quot;)) {
                            String text = null;
                            String screenName = null;
                            while (true) {
                                event = parser.next();
                                if (event == XmlPullParser.START_TAG) {
                                    name = parser.getName();
                                    if (name.equals(&quot;text&quot;)) {
                                        text = parser.nextText();
                                    } else if (name.equals(&quot;user&quot;)) {
                                        String userName;
                                        while (true) {
                                            int eventUser;
                                            eventUser = parser.next();
                                            userName = parser.getName();
                                            if (eventUser == XmlPullParser.START_TAG) {
                                                if (userName.equals(&quot;screen_name&quot;)) {
                                                    screenName = parser.nextText();
                                                }
                                            } else if (eventUser == XmlPullParser.END_TAG
                                                    &amp;&amp; userName.equals((&quot;user&quot;))) {
                                                break;
                                            }
                                        }
                                    }
                                } else if (event == XmlPullParser.END_TAG
                                        &amp;&amp; parser.getName().equals(&quot;status&quot;)){
                                    break;
                                }

                            }
                            //output username and status to console, you will want to parse and dispatch whatever
                            //information you need to something that does something a bit more substantial

                            System.out.println(screenName + &quot;: &quot; + text); //insert money making method here

                            //IMPORTANT HACK
                            //because each stream starts with an &lt;xml/&gt; document tag
                            //we have to reset the input of the parser to the stream
                            parser.setInput(stream, &quot;utf-8&quot;);
                        }
                    } else if (event == XmlPullParser.END_TAG
                            &amp;&amp; parser.getName().equals(&quot;statuses&quot;))
                        break;

                }

            }

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        }
</pre>
<p><a href="http://gist.github.com/134362">Here is the entire source </a> you should be able to build it and run it in the console without many problems, but remember never try to actually read the stream.</p>
<p><img src="http://awalkingcity.com/blog/wp-content/uploads/2009/06/stream.png" alt="stream" title="stream" width="400" height="244" class="aligncenter size-full wp-image-156" /></p>
]]></content:encoded>
			<wfw:commentRss>http://awalkingcity.com/blog/2009/06/22/using-java-with-the-twitter-streaming-api/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Android:  Fun With Speech Recognition</title>
		<link>http://awalkingcity.com/blog/2009/02/10/android-fun-with-speech-recognition/</link>
		<comments>http://awalkingcity.com/blog/2009/02/10/android-fun-with-speech-recognition/#comments</comments>
		<pubDate>Wed, 11 Feb 2009 06:06:55 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[android]]></category>
		<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://awalkingcity.com/blog/?p=140</guid>
		<description><![CDATA[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 &#8220;application&#8221; and [...]]]></description>
			<content:encoded><![CDATA[<p>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 &#8220;application&#8221; and return to your application a list of results.  The Intent and a description of it&#8217;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 &#8220;<uses-sdk minSdkVersion="2" />&#8221; in your application&#8217;s manifest file so that the app cannot be installed on a phone that doesn&#8217;t have the 1.1 firmware on it.</p>
<p>Here is the code for launching a simple speech recognition intent:</p>
<pre name="code" class="java">

Intent intent = new Intent(&quot;android.speech.action.RECOGNIZE_SPEECH&quot;);
startActivityForResult(intent, 0);
</pre>
<p>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.</p>
<p>Here is the code for extracting the results:</p>
<pre name="code" class="java">

@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		...code for checking resultCode and data intent...
	ArrayList&lt;String&gt; results = data.getExtras().getStringArrayList(&quot;results&quot;);

	}
</pre>
<p>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.</p>
<p><img src="http://awalkingcity.com/blog/wp-content/uploads/2009/02/h1.png" alt="h1" title="h1" width="160" height="240" class="aligncenter size-full wp-image-142" /><img src="http://awalkingcity.com/blog/wp-content/uploads/2009/02/h2.png" alt="h2" title="h2" width="160" height="240" class="aligncenter size-full wp-image-143" /><img src="http://awalkingcity.com/blog/wp-content/uploads/2009/02/h3.png" alt="h3" title="h3" width="160" height="240" class="aligncenter size-full wp-image-147" /><img src="http://awalkingcity.com/blog/wp-content/uploads/2009/02/h4.png" alt="h4" title="h4" width="160" height="240" class="aligncenter size-full wp-image-148" /></p>
]]></content:encoded>
			<wfw:commentRss>http://awalkingcity.com/blog/2009/02/10/android-fun-with-speech-recognition/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Qr Codes Made Even Easier With Android</title>
		<link>http://awalkingcity.com/blog/2008/10/23/qr-codes-made-even-easier-with-android/</link>
		<comments>http://awalkingcity.com/blog/2008/10/23/qr-codes-made-even-easier-with-android/#comments</comments>
		<pubDate>Thu, 23 Oct 2008 22:31:17 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://awalkingcity.com/blog/?p=116</guid>
		<description><![CDATA[The G1 came out this week and I have been putting it through the paces.  I really like the seamless transition between developing with the emulator and developing on the device.  I think overall it is a very strong first device for Android, but I think that normal users may not recognize some [...]]]></description>
			<content:encoded><![CDATA[<p>The G1 came out this week and I have been putting it through the paces.  I really like the seamless transition between developing with the emulator and developing on the device.  I think overall it is a very strong first device for Android, but I think that normal users may not recognize some of the more powerful features of the platform.  </p>
<p>The Intent system allows for applications and activities to interact with each other, so that you can have applications using the features of other applications.  I think this is a really interesting concept and think it could lead to a less application-centric view of phone operation towards a more feature-centric view.  Instead of developing an entire application, developers can develop specific features that perform a very specific task.  These features can be used by other applications to create new and interesting functionality.  </p>
<p>I think the best example of this concept is Barcode Scanner.  Barcode Scanner is the application specific manifestation of <a href="http://code.google.com/p/zxing/">ZXing</a> which I blogged about previously.  Installing it lets you scan bar and QR Codes and lets you perform search actions or interact with the results(like an e-mail address or phone number).  The two shopping applications CompareAnywhere and ShopSavvy use the ZXing library themselves for doing barcode scanning, but they include the ZXing library as part of their application bundle.  </p>
<p>In my previous entry I mentioned that I would like to see specific Intents that let you use the encoding and decoding ability of ZXing from other applications and the ZXing team responded that the latest build had this exact functionality!  Now all you have to do is install Barcode Scanner on your phone and your applications can take advantage of its features.  Specifically, it provides Intents that allow your application to use the encoding and decoding functionality.  The Intent mechanism makes it almost too simple to integrate this functionality into your application.<br />
<strong><br />
Encoding &#8211; &#8220;com.google.zxing.client.android.ENCODE&#8221;</strong></p>
<p>To encode a string into a QR Code Simply create an Intent with the Decode action specified, two string extras specifying the Type and Data and call startActivity():</p>
<pre name="code" class="java">

Intent intent = new Intent(&quot;com.google.zxing.client.android.ENCODE&quot;);
				intent.addCategory(Intent.CATEGORY_DEFAULT);
				intent.putExtra(&quot;ENCODE_TYPE&quot;, &quot;TEXT_TYPE&quot;);
				intent.putExtra(&quot;ENCODE_DATA&quot;,&quot;HELLO WORLD&quot;);
startActivity(intent);
</pre>
<p>The string values for the Intents and the extras values can be found in the Intents and Content classes in the <a href="http://code.google.com/p/zxing/">ZXing</a> source code.<br />
<center><a href="http://awalkingcity.com/blog/wp-content/uploads/2008/10/bs1.png"><img src="http://awalkingcity.com/blog/wp-content/uploads/2008/10/bs1.png" alt="" title="bs1" width="320" height="480" class="alignnone size-medium wp-image-117" /></a></center></p>
<p><strong>Decoding &#8211; &#8220;com.google.zxing.client.android.SCAN&#8221;</strong></p>
<p>Bringing up the decoding camera interface is just as easy as encoding with the added step of having it return the decoded value of the barcode to our main application.</p>
<pre name="code" class="java">

Intent intent = new Intent(&quot;com.google.zxing.client.android.SCAN&quot;);
				intent.addCategory(Intent.CATEGORY_DEFAULT);
				startActivityForResult(tent,0);
</pre>
<p>The big difference here is that we are using startActivityForResult which will allow the scanning activity to return the results of the scan back to our app.  In the Activity that launched the decode intent we can extract the results of the scan in the onActivityResult method by simply accessing the string extra &#8220;SCAN_RESULT&#8221;.</p>
<pre name="code" class="java">

data.getStringExtra(&quot;SCAN_RESULT&quot;);
</pre>
<p><center><br />
<a href="http://awalkingcity.com/blog/wp-content/uploads/2008/10/bs2.png"><img src="http://awalkingcity.com/blog/wp-content/uploads/2008/10/bs2.png" alt="" title="bs2" width="480" height="320" class="alignnone size-medium wp-image-120" /></a></p>
<p><a href="http://awalkingcity.com/blog/wp-content/uploads/2008/10/bs3.png"><img src="http://awalkingcity.com/blog/wp-content/uploads/2008/10/bs3.png" alt="" title="bs3" width="480" height="320" class="alignnone size-medium wp-image-121" /></a></center></p>
<p>You can now use these features to do all kinds of interesting things.  I am currently interested in transferring data between phones by encoding the data in a QR code and having the other phone retrieve it by simply pointing it at the other camera&#8217;s screen.  You could also encode movie ticket information into a QR code and have it displayed on the phone so it can be scanned at the theater.  </p>
<p>I hope this post showed you how useful Barcode Scanner can be for your application and it&#8217;s users.  Now if someone could do something about the reviewers in the android app store&#8230;..</p>
]]></content:encoded>
			<wfw:commentRss>http://awalkingcity.com/blog/2008/10/23/qr-codes-made-even-easier-with-android/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>An Actual Walking City..almost</title>
		<link>http://awalkingcity.com/blog/2008/10/23/an-actual-walking-cityalmost/</link>
		<comments>http://awalkingcity.com/blog/2008/10/23/an-actual-walking-cityalmost/#comments</comments>
		<pubDate>Thu, 23 Oct 2008 18:10:25 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://awalkingcity.com/blog/?p=112</guid>
		<description><![CDATA[Long since the radical ideas of the 60s (and the namesake of this blog), comes  a walking house!   
]]></description>
			<content:encoded><![CDATA[<p>Long since the <a href="http://www.designmuseum.org/design/archigram">radical ideas of the 60s</a> (and the namesake of this blog), comes  <a href="http://www.telegraph.co.uk/news/newstopics/howaboutthat/3235261/Walking-house-can-escape-floods-or-unruly-neighbours.html">a walking house</a>!   </p>
]]></content:encoded>
			<wfw:commentRss>http://awalkingcity.com/blog/2008/10/23/an-actual-walking-cityalmost/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>QR Codes Made Easy In Android</title>
		<link>http://awalkingcity.com/blog/2008/08/25/qr-codes-made-easy-in-android/</link>
		<comments>http://awalkingcity.com/blog/2008/08/25/qr-codes-made-easy-in-android/#comments</comments>
		<pubDate>Tue, 26 Aug 2008 04:59:39 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[android]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[mobile]]></category>

		<guid isPermaLink="false">http://awalkingcity.com/blog/?p=39</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p>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 <a href="http://mobile.kaywa.com/">blog</a>.</p>
<p>I am going to go through a quick example of encoding and decoding QR codes in Android.</p>
<p><strong>Encoding</strong></p>
<p>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 &#8220;cloud&#8221; to do the heavy lifting for us.  In this case we will use the <a href="http://code.google.com/apis/chart/#qrcodes">Google Charts API</a> 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 &#8220;lock&#8221; on it)</p>
<p>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. </p>
<pre name="code" class="java">

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(&quot;http://chart.apis.google.com/chart?chs=300x300&amp;cht=qr&amp;choe=UTF- 8chl=&quot;+URLEncoder.encode(input, &quot;UTF-8&quot;));
      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;
}
</pre>
<p><center><a href="http://awalkingcity.com/blog/wp-content/uploads/2008/08/qrfest.png"><img class="aligncenter size-medium wp-image-40" title="qrfest" src="http://awalkingcity.com/blog/wp-content/uploads/2008/08/qrfest.png" alt="" width="320" height="480" /></a></center></p>
<p><strong>Decoding</strong></p>
<p>The <a href="http://code.google.com/p/zxing/">ZXing</a> 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.</p>
<p>The code below takes the bitmap image from the ImageView and pushes it through the decoder populating a TextView.</p>
<pre name="code" class="java">

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();
}
</pre>
<p>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.</p>
<pre name="code" class="java">

textView.setAutoLinkMask(Linkify.ALL);
</pre>
<p><center><br />
<a href="http://awalkingcity.com/blog/wp-content/uploads/2008/08/device.png"><img class="aligncenter size-medium wp-image-43" title="device" src="http://awalkingcity.com/blog/wp-content/uploads/2008/08/device.png" alt="" width="320" height="480" /></a><br />
</center></p>
<p>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.</p>
<p><a href="http://awalkingcity.com/blog/wp-content/uploads/2008/08/qrbrowse1.png"><img class="aligncenter size-medium wp-image-41" title="qrbrowse1" src="http://awalkingcity.com/blog/wp-content/uploads/2008/08/qrbrowse1.png" alt="" width="320" height="480" /></a><a href="http://awalkingcity.com/blog/wp-content/uploads/2008/08/qrbrowse2.png"><img class="aligncenter size-medium wp-image-42" title="qrbrowse2" src="http://awalkingcity.com/blog/wp-content/uploads/2008/08/qrbrowse2.png" alt="" width="320" height="480" /></a></p>
<p>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.</p>
<p>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.  </p>
]]></content:encoded>
			<wfw:commentRss>http://awalkingcity.com/blog/2008/08/25/qr-codes-made-easy-in-android/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Build Your Own Micro Location Sharing Service With Google&#8217;s AppEngine&#8230; and use it with android</title>
		<link>http://awalkingcity.com/blog/2008/04/09/build-your-own-micro-location-sharing-service-with-googles-appengine-and-use-it-with-android/</link>
		<comments>http://awalkingcity.com/blog/2008/04/09/build-your-own-micro-location-sharing-service-with-googles-appengine-and-use-it-with-android/#comments</comments>
		<pubDate>Thu, 10 Apr 2008 01:21:55 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[android]]></category>
		<category><![CDATA[mobile]]></category>

		<guid isPermaLink="false">http://awalkingcity.com/blog/?p=23</guid>
		<description><![CDATA[In case you hadn&#8217;t heard, Google has released a preview of AppEngine, it&#8217;s cloud/platform service.  It provides a full application development and deployment stack that has access to google services like email, login, and datastore.   It also provides a python-based application development environment called webapp as well as supporting other python web [...]]]></description>
			<content:encoded><![CDATA[<p>In case you hadn&#8217;t heard, Google has released a preview of <a href="http://googleappengine.blogspot.com/2008/04/introducing-google-app-engine-our-new.html">AppEngine</a>, it&#8217;s cloud/platform service.  It provides a full application development and deployment stack that has access to google services like email, login, and datastore.   It also provides a python-based application development environment called <a href="http://code.google.com/appengine/docs/webapp/">webapp</a> as well as supporting other python web frameworks, like <a href="http://www.djangoproject.com/">django</a>.</p>
<p>Since location-based services for mobile phones are all the rage, I thought I would walk through how to create a simple location sharing web service on AppEngine and interact with it in Android.  I will show you how to create a simple REST-ish API that consumes HTTP requests and outputs simple XML data.  It probably won&#8217;t be exciting for people interested in shiny web applications, but using this approach provides a flexible protocol for interacting with remote service from a mobile phone, allowing the data to be consumed and displayed in a native phone application.  </p>
<p>After that, I will show you how to use Android&#8217;s LBS and networking APIs to interact with the service.</p>
<p><strong>Setup</strong><br />
Create a new AppEngine project and create a file called location.py.  First, we need to configure the app.yml with the url mapping for our service.  For this example I will simply use &#8220;/endpoint&#8221; as my mapping to the location.py handler.</p>
<pre name="code" class="python">

application: location
version: 1
runtime: python
api_version: 1

handlers:
- url: /endpoint
  script: location.py
</pre>
<p>There are many more ways to define your url mapping to provide RESTful urls for your app, <a href="http://code.google.com/appengine/docs/configuringanapp.html#Script_Handlers">see here for more info</a>.</p>
<p><strong>location.py</strong><br />
The source for the service can be found <a href='http://awalkingcity.com/blog/wp-content/uploads/2008/04/location.py'>here</a>.  I am going to step through the file from the top down.</p>
<p><strong>Model </strong><br />
We want to create a location domain model that can be used with the datastore api.  To do this we define a Location class that inherits from db.Model.  We will create fields for latitude, longitude, and date.</p>
<pre name="code" class="python">

class Location(db.Model):
  lat = db.IntegerProperty()
  lon = db.IntegerProperty()
  date = db.DateTimeProperty(auto_now_add=True)
</pre>
<p>lat and lon are stored as Integers because it makes things a little easier to use with some of the Android Map and Location APIs.</p>
<p>Since we want to be able to output our model as XML we make a helper method that makes a one line XML element with lat and lon as attributes:</p>
<pre name="code" class="python">

def printloc(self,location):
      return '&lt;location lat=\'%(lat)s\' lon=\'%(lon)s\'&gt;&lt;/location&gt;\n' % {'lat':location.lat, 'lon':location.lon} 
</pre>
<p>Models in AppEngine/webapp have a to_xml() method that allows them to be exported to XML automatically, the format is much more verbose than I would like to deal with in this tutorial, but they do provide an interesting look as to how the data is stored and read in the datastore/BigTable.  </p>
<p><strong>Methods</strong><br />
The next two methods get called when a request is made.  They are mapped to the GET and POST http methods, this makes it easy to design RESTful interfaces for our web service.  In our example we want a POST to create a new location, while GET will fetch a list of the 10 most recent locations.</p>
<p><strong>Post</strong></p>
<pre name="code" class="python">

  def post(self):
      location = Location()
      location.lat = int(self.request.get('lat'))
      location.lon = int(self.request.get('lon'))
      location.put()
      self.response.out.write(self.printloc(location))
</pre>
<p>This creates a new location object and stores the two parameter values in it and saves the location to the data store.  We then write the location out to the response.  </p>
<p>The output of this method will look something like this:</p>
<pre name="code" class="xml">

&lt;location lat=&quot;37422375&quot; lon=&quot;-122096532&quot;/&gt;
</pre>
<p><strong>Get</strong></p>
<pre name="code" class="python">

def get(self):
    locations = db.GqlQuery(&quot;SELECT * FROM Location ORDER BY date DESC LIMIT 10&quot;)
    self.response.headers['Content-Type'] = 'text/xml'
    self.response.out.write('&lt;list&gt;')
    for l in locations:
        self.response.out.write(self.printloc(l))
    self.response.out.write('&lt;/list&gt;')
</pre>
<p>This code fetches the latest 10 locations using a <a href="http://code.google.com/appengine/docs/datastore/queryclass.html">GQL</a> query and wraps them in a
<list> element.  </p>
<p>The output of this call will look something like this:</p>
<pre name="code" class="xml">

&lt;list&gt;
&lt;location lat=&quot;37422375&quot; lon=&quot;-122096532&quot;/&gt;
&lt;location lat=&quot;37429756&quot; lon=&quot;-122100756&quot;/&gt;
&lt;location lat=&quot;37428218&quot; lon=&quot;-122101459&quot;/&gt;
&lt;location lat=&quot;37422383&quot; lon=&quot;-122096532&quot;/&gt;
&lt;location lat=&quot;37422378&quot; lon=&quot;-122096531&quot;/&gt;
&lt;location lat=&quot;37422384&quot; lon=&quot;-122096533&quot;/&gt;
&lt;location lat=&quot;37449370&quot; lon=&quot;-122119525&quot;/&gt;
&lt;location lat=&quot;37449355&quot; lon=&quot;-122119523&quot;/&gt;
&lt;location lat=&quot;37454563&quot; lon=&quot;-122130219&quot;/&gt;
&lt;location lat=&quot;37454443&quot; lon=&quot;-122130012&quot;/&gt;
&lt;/list&gt;
</pre>
<p><strong>main</strong></p>
<pre name="code" class="python">

def main():
  application = webapp.WSGIApplication(
                                       [('/endpoint', LocationService)],
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == &quot;__main__&quot;:
  main()
</pre>
<p>This code binds our handler to the /endpoint address, and runs the service.</p>
<p><strong>Android integration</strong><br />
I will now briefly demonstrate how to interact with the service from within Android.  If you are like me, and were a little late trying to sign up for the AppEngine preview program,  you are running your web service locally. You need to run the development server with the &#8220;-a ADDRES&#8221;  where ADDRESS is your internal network address.  Android has an internal network loopback that loops any requests made from the phone to &#8220;localhost&#8221; back to the phone so you won&#8217;t be able to access your service if it is running on localhost.  </p>
<p>Our first step is to build a new MapActivity that contains a MapView and two menu actions &#8220;Update Location&#8221; and &#8220;Fetch Locations&#8221;.  The source for this activity can be found <a href='http://awalkingcity.com/blog/wp-content/uploads/2008/04/minilocationmap.java'>here</a>.</p>
<p>Update Location:<br />
The definition of our Post Current Location menu item which is defined inside of public boolean onCreateOptionsMenu(Menu menu):</p>
<pre name="code" class="java">

menu.add(0, 1, &quot;Post Current Location&quot;, new Runnable(){

			public void run() {

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

				 Map headers = new HashMap();

		        String text= &quot;lat=&quot; +(int)(loc.getLatitude()*1E6) + &quot;&amp;lon=&quot; + (int)(loc.getLongitude()*1E6;
		        byte[] bytes = text.getBytes();
		        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
				mRequestQueue.queueRequest(
		                &quot;http://10.0.0.199:8080/endpoint&quot;,
		                &quot;POST&quot;, headers, new LocationEventHandler(mHandler), bais, bytes.length, false);
			}

		});
</pre>
<p>This gets your current location in the same way that we did in our <a href="http://awalkingcity.com/blog/?p=13">fire eagle example</a>.  It then constructs a POST request with the latitude and longitude as parameters for our web service.  You need to convert the latitude and longitude to integers, there is probably a simpler way to do it than above.  This example uses the RequestQueue class which provides an interface for making http requests.  For more information on performing these requests you should definitely check out this <a href="http://davanum.wordpress.com/">blog</a>, which is full of great android examples. </p>
<p>The LocationEventHandler class handles the data returned from the request.  In my example the EventHandler uses the  XML pull parser to parse the XML data into a DemoLocation object which is then passed back to the Map Activity using it&#8217;s handler.  In the Handler the location is extracted from the Message object and used to center the map on the location just posted:</p>
<pre name="code" class="java">

public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);

			if(msg.what == 123){
				DemoLocation currentLocation = (DemoLocation) msg.getData().get(&quot;location&quot;);
				mMapController.centerMapTo(new Point(currentLocation.lat, currentLocation.lon), true);

			}
				}
		}
</pre>
<p>Retrieving Locations</p>
<pre name="code" class="java">

menu.add(0, 0, &quot;Retrieve Locations&quot;, new Runnable(){

			public void run() {
				 Map headers = new HashMap();
				mRequestQueue.queueRequest(
		                &quot;http://10.0.0.199:8080/endpoint&quot;,
		                &quot;GET&quot;, headers, new LocationListHandler(mHandler), null, 0, false);
			}

		});
</pre>
<p>This creates a GET http request and uses LocationListHandler to create an ArrayList of locations that can be used by our map.  To keep the tutorial short I won&#8217;t actually do anything with the list of locations, but they could be used with an overlay to draw points on the map of all the places you have recently been.<br />
<center><br />
<a href='http://awalkingcity.com/blog/wp-content/uploads/2008/04/lbs.png'><img src="http://awalkingcity.com/blog/wp-content/uploads/2008/04/lbs.png" alt="" title="lbs" width="320" height="480" class="alignnone size-medium wp-image-24" /></a></center></p>
<p>This fairly primitive implementation should be enough to get you started creating web services in AppEngine and using them in android.  Security is obviously an issue I ignored.  The built-in google user account api is built around user authentication using web forms and http redirects, similar to <a href="http://awalkingcity.com/blog/?p=18">OpenID</a>.  This makes it a little difficult to create APIs using just google accounts.  Implementing OAuth and having the web-based authorizorization part of the process use the google user api, then having a seperate table storing a reference to the user&#8217;s account, applications, and access tokens would be one approach to solving this problem.    </p>
<p>Overall, AppEngine was easy to use and provides a nice set of functionality to build on top of.  Having your web stack and client stack all under the google umbrella is kind of interesting.  The barrier of entry to developing and deploying a web app is now so low that I can see people building their own personal web services for things like their desktop and mobile phones.  You now control your personal information and can use open standards for sharing that information.  </p>
]]></content:encoded>
			<wfw:commentRss>http://awalkingcity.com/blog/2008/04/09/build-your-own-micro-location-sharing-service-with-googles-appengine-and-use-it-with-android/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
