Using Animations and Creating Custom Animations for Android
September 25th, 2010
Using animations in your Android applications can help create an interesting and engaging experience for your users. They can be used in games and applications in a number of ways either as a visual treat or as a method to convey information. Fortunately Android has an animation framework that allows you to easily translate, rotate, scale and alter the alpha of (or a combination) a View. Common transitions like fade in/out or slide in from off screen are examples of animations the framework can produce.
Animations and Interpolators
The process of animating a View makes use of two classes the Animation and Interpolator classes. The Animation class describes various aspects of the animation such as the transformation (changes in position, alpha, etc) and the duration of the animation.
The Interpolator class describes the rate of change of the animation, for example a ScaleAnimation with an AccelerateIterpolator results in a View that scales slowly at first and speeds up until the end of the animation. There are a number of different interpolators the most basic LinearInterpolator to more complex ones such as AccelerateInterpolator, AccelerateDecelerateInterpolter and OvershootInterpolator.
Adding Animation to a View
Here is res/layout/main.xml, it contains a button called ‘butt’ that is centred in the screen.
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <Button android:id="@+id/butt" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="Shake!"/> </RelativeLayout>
Now we define our animation, res/anim/exampe_anim.xml , which is going to slide the button in from the bottom of the screen to the centre of the screen scaling from 0.5 to 1 as it travels all in 1.5 seconds. The p in 50%p means parent, since the Button is a primary child of the RelativeLayout this means 50% of the screen height.
<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android" android:interpolator="@android:anim/decelerate_interpolator" android:shareInterpolator="true"> <translate android:fromYDelta="50%p" android:toYDelta="0" android:duration="1500" /> <scale android:fromYScale="0.5" android:toYScale="1" android:fromXScale="0.5" android:toXScale="1" android:duration="1500" /> </set>
To start the animation use AnimationUtils.loadAnimation(context, resID) to load the animation and the startAnimation(animation) method of the View class.
butt.startAnimation(AnimationUtils.loadAnimation(getBaseContext(), R.anim.example_anim));
Casting vs Not Casting in Strict Mode and not in Strict Mode
September 18th, 2010
Preamble
Actionscript is, for the most part, a dynamically typed language, which means that the types (i.e. String, int, GameObject) of variables are checked at run-time rather than at compile-time like they are in C and Java. This is supposedly beneficial to the programmer since such a language is more flexible. All sorts of crap like this is valid:
var i = new GameObject(); i = "1";
As you can see it’s possible to change the type of a reference to something entirely different. This can generate type errors at run-time since later you may try to call i.update(). Although this example is very obvious real world examples can be more nuanced and thus more complicated to find and fix.
Casting and using ‘Strict Mode’ is a technique to essentially make Actionscript a little bit like a statically typed language. The performance boost comes from firstly doing as much as possible at compile-time (thus less at run-time) and secondly helping the process of type checking by casting.
On Android, and in general, you want your application or game to be responsive. So operations that take a long time to finish or block I/O should not be preformed on the UI thread otherwise the UI becomes clunky and unresponsive. To solve this problem any CPU intensive or I/O blocking operation are preformed in a separate thread. Unfortunately this creates another problem, which is how do we update and control the UI from this separate worker thread.
This is where Handlers come into play they allow you to send Messages (information and instructions) from the worker thread to the UI thread. A Message can contain ints using the fields arg1 and arg2 and an arbitrary Object using the obj or a Bundle using the setData(Bundle data) method.
So here’s an example of how to use Handlers:
public class DataView extends View {
final static int FAILURE = 123, DATA = 124;
DataHandler handler;
ArrayList data;
boolean failure = false;
public DataView(Context context, AttributeSet attrs) {
super(context, attrs);
handler = new DataHandler();
(new Thread(new WorkerRunnable(this))).start();
}
@Override
protected void onDraw(Canvas canvas) {
// draw something based on data…
}
private class DataHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case FAILURE:
failure = true;
invalidate();
break;
case DATA:
data = (ArrayList) msg.obj;
invalidate();
break;
default:
super.handleMessage(msg);
break;
}
}
}
@Override
public Handler getHandler() {
return handler;
}
}
public class WorkerRunnable implements Runnable {
private DataView dataView;
private ArrayList dataObjects = new ArrayList(10);
public WorkerRunnable(DataView dataView) {
this.dataView = dataView;
}
@Override
public void run() {
boolean success = true;
// some io or cpu heavy operations
Message msg = Message.obtain();
if(success){
msg.what = DataView.DATA;
msg.obj = dataObjects;
}else{
msg.what = DataView.FAILURE;
}
dataView.getHandler().sendMessage(msg);
}
}
Explanation
The DataView spawns a Thread that runs a WorkRunnables code, which performs some IO or CPU heavy operations. The WorkRunnable informs the UI once it has finished (or failed) by sending messages to the custom written Handler.
Android GPS Example
April 11th, 2010
For some reason there doesn’t seem to be a clear example showing how to use GPS on Android. Here is some code I have written that listens for location changes and displays the data in a TextView. The example also shows how to open the GPS setting with code via an Intent, since sometimes the GPS will be turned off by the user.
Code
package uk.co.hejp.GPSExample;
import android.app.Activity;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
public class Main extends Activity implements LocationListener {
/* this class implements LocationListener, which listens for both
* changes in the location of the device and changes in the status
* of the GPS system.
* */
static final String tag = "Main"; // for Log
TextView txtInfo;
LocationManager lm;
StringBuilder sb;
int noOfFixes = 0;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/* get TextView to display the GPS data */
txtInfo = (TextView) findViewById(R.id.textInfo);
/* the location manager is the most vital part it allows access
* to location and GPS status services */
lm = (LocationManager) getSystemService(LOCATION_SERVICE);
}
@Override
protected void onResume() {
/*
* onResume is is always called after onStart, even if the app hasn't been
* paused
*
* add location listener and request updates every 1000ms or 10m
*/
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 10f, this);
super.onResume();
}
@Override
protected void onPause() {
/* GPS, as it turns out, consumes battery like crazy */
lm.removeUpdates(this);
super.onResume();
}
@Override
public void onLocationChanged(Location location) {
Log.v(tag, "Location Changed");
sb = new StringBuilder(512);
noOfFixes++;
/* display some of the data in the TextView */
sb.append("No. of Fixes: ");
sb.append(noOfFixes);
sb.append('\n');
sb.append('\n');
sb.append("Londitude: ");
sb.append(location.getLongitude());
sb.append('\n');
sb.append("Latitude: ");
sb.append(location.getLatitude());
sb.append('\n');
sb.append("Altitiude: ");
sb.append(location.getAltitude());
sb.append('\n');
sb.append("Accuracy: ");
sb.append(location.getAccuracy());
sb.append('\n');
sb.append("Timestamp: ");
sb.append(location.getTime());
sb.append('\n');
txtInfo.setText(sb.toString());
}
@Override
public void onProviderDisabled(String provider) {
/* this is called if/when the GPS is disabled in settings */
Log.v(tag, "Disabled");
/* bring up the GPS settings */
Intent intent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
@Override
public void onProviderEnabled(String provider) {
Log.v(tag, "Enabled");
Toast.makeText(this, "GPS Enabled", Toast.LENGTH_SHORT).show();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
/* This is called when the GPS status alters */
switch (status) {
case LocationProvider.OUT_OF_SERVICE:
Log.v(tag, "Status Changed: Out of Service");
Toast.makeText(this, "Status Changed: Out of Service",
Toast.LENGTH_SHORT).show();
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
Log.v(tag, "Status Changed: Temporarily Unavailable");
Toast.makeText(this, "Status Changed: Temporarily Unavailable",
Toast.LENGTH_SHORT).show();
break;
case LocationProvider.AVAILABLE:
Log.v(tag, "Status Changed: Available");
Toast.makeText(this, "Status Changed: Available",
Toast.LENGTH_SHORT).show();
break;
}
}
@Override
protected void onStop() {
/* may as well just finish since saving the state is not important for this toy app */
finish();
super.onStop();
}
}
Permissions
Of course the Android framework has security permissions to protect the user. To get the permission to use GPS add a uses-permission tag with attribute android:name set to “android.permission.ACCESS_FINE_LOCATION” to the AndroidManifest.xml document as a direct child of the manifest tag, i.e:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Notes
When testing this code in the emulator, you can send mock fixes by connecting to the emulator using telnet, i.e. ‘telnet localhost 5554′ and typing:
geo fix -10.223, 40.549
Adding Google AJAX Search API to your Blog
February 4th, 2010
Search is the way that content is found on the Internet, if your content can’t be searched in some way users simply won’t be able to find content particularly past content.
For some time now my blog hasn’t actually had any accessible search functionality, because the theme I’ve been using Simpla is a very minimalist theme (more of a template really). This is what I wanted since it is very small, clean and quick; but due to it’s simplicity some common features were left out. I have since sort to rectify this problem. After a little consideration and Googling I decided to use the Google AJAX Search API, firstly because it probably offers better results than the WordPress search and my server does not do the indexing and processing.
Google AJAX Search API
The Google AJAX Search API can return many types of search: Web, Local, Video, Blog, News, Book, Image and Patent. The most relevant for a blog search is Web search, to return relevant posts. There are of course restrictions for example the maximum number of results is 64 and you’re not allowed to modify the results, as far as I’m aware there is no query limit, which is good.
To get started you require an API key, which are free, Sign Up. The key will only work for the domain that you signed up with.
Basic Example
Firstly import the Google AJAX Search API:
<script src=http://www.google.com/jsapi?key=YOUR_API_KEY" type="text/javascript"></script>
google.load('search', '1');
The function specified in setOnLoadCallback is called once the library loads. This example specifies OnLoad function that creates a web search, tells the API to use an element called “results“ to display the results and then performs an initial search for “hello kitty”.
function OnLoad() {
// create a search control
var searchControl = new google.search.SearchControl();
// add just a web searcher
searchControl.addSearcher(new google.search.WebSearch());
// tell the searcher to draw itself and tell it where to attach
searchControl.draw(document.getElementById("results"));
// execute an inital search
searchControl.execute("hello kitty");
}
google.setOnLoadCallback(OnLoad);
Read more: Customisation, Adding to WordPress, Example search.php
Playground: HEJP ColourPicker
February 3rd, 2010
Just been messing around with the Robot class, which is designed for automated testing of applications but has other uses. Here I have used it to write an application to get the pixel colour of any pixel on the screen. The GUI consists of a Canvas magnifying the area around the mouse pointer and a text field to display the pixel hex value.

How to Use
Move the mouse pointer to the pixel you’d like to know the colour of and hit Enter.
Source and Jar
Notes Regarding the Robot Class
getColorPixel is very slow as I found out as soon as using it, the solution is to use createScreenCapture to get the pixels around the mouse pointer then read the colours from the BufferedImage.
ActionScript 3: Socket Programming
January 27th, 2010

What is a Socket?
A Socket is a mechanism used to send data over a network (e.g. the Internet), it is the combination of an IP address and a port. The IP address is used to specify the computer (on the network) to connect to and the port (which is not a physical port just a software construct represented by a number) specifies which port on the computer to connect to. There are multiple ports to allow multiple distinct connections to a single IP address, certain ports traditionally have certain uses for example HTTP servers use 80 and POP3 servers use 110.
Restrictions and Security
ActionScript has many restrictions that (to be brutally honest) cripple, but not entirely, the usefulness of Sockets.
Firstly, there are security issues, for a Flash application to connect to a particular server that server must host a policy file defining what ports Flash is allowed to connect to. This restricts Flash from connecting to most of the servers on the Internet although it isn’t too much trouble to put a policy file on your server.
Secondly, Flash isn’t allowed to create server sockets (sockets that clients can connect to) either, so to make a multiplayer game would require that the game is hosted on a server which all of the clients connect to. The server would have to constantly send data to all of the clients; this could potentially use a lot of bandwidth.
Finally, only one type of transportation protocol is supported that is TCP. Although TCP is very good for sending data like webpages and such it is not so good at sending real-time data. This means that multiplayer real-time games are slower than they could be or infeasible.
Never mind all that though, Flash Sockets are still useful.
Creating a Socket
Creating a socket is fantastically straight forward, since there are no decisions to make about the type of Socket. Here is an example with all of the event listeners added:
import flash.net.Socket;
import flash.events.*;
var socket:Socket = new Socket();
Security.allowDomain("*");
socket.addEventListener(Event.CONNECT, onConnect);
socket.addEventListener(Event.CLOSE, onClose);
socket.addEventListener(IOErrorEvent.IO_ERROR, onError);
socket.addEventListener(ProgressEvent.SOCKET_DATA, onResponse);
socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecError);
socket.connect("hejp.co.uk", 80);
It is wise to connect after adding the event listeners because an event could be dispatched without any code to respond to it, or something strange like that. This example connects to hejp.co.uk using port 80 i.e. my web server.
Quick description of the Events:
- CONNECT: dispatched when the connection is established
- CLOSE: dispatched when the connection is closed
- IO_ERROR: dispatched when an error occurs
- SOCKET_DATA: dispatched when socket can be read
- SECURITY_ERROR: dispatched when security gets in the way
Using the Socket
Using the socket involves implementing the listener functions. In this example we’ll make a request for the index page of hejp.co.uk and trace the response.
Doing so involves writing a HTTP request to the port and then reading the response.
function onConnect(e:Event):void {
socket.writeUTFBytes("GET / HTTP/1.1\n");
socket.writeUTFBytes("Host: hejp.co.uk\n");
socket.writeUTFBytes("\n");
}
function onClose(e:Event):void {
// Security error is thrown if this line is excluded
socket.close();
}
function onError(e:IOErrorEvent):void {
trace("IO Error: "+e);
}
function onSecError(e:SecurityErrorEvent):void {
trace("Security Error: "+e);
}
function onResponse(e:ProgressEvent):void {
if (socket.bytesAvailable>0) {
trace(socket.readUTFBytes(socket.bytesAvailable));
}
}
Notes
A Flash app running the Flash IDE runs in a completely different security sandbox to a Flash app running in the browser, therefore even though an works running in the IDE errors (usually security errors) can crop up while running in the browser.