Android Advanced Logger

2012/03/08

The Android Log utility class is simple enough and does the job, but there are a few nagging problems I’ve found with it.

No context. There is no supplied as to what triggered the log statement. This leads to log records like,

D/MyApp: Something happened ...

Great, but happened where? What class? Which method? For small apps with a single developer this isn’t a problem, but for larger projects where the person that’s doing the debugging did not write the code … By convention, developers can add contextual information into the log statements but this requires everyone to remember to do this, consistently. Can’t the log utility do it for us?

Tag inconsistencies. Some apps use different tags for each class, others use the same tag across the entire app. The former makes it impossible to tell which log statements came from the same app, unless you keep a mapping from tab to class to app around. That’s why I prefer the latter. However, now we are forced to pass the exact same argument (TAG) into every log statement. Can the logging framework insert it for us?

Level. The Android logger does not allow me to change the level, only filter the log output by level via logcat arguments. What if i simply want to avoid logging things at particular levels?

Argument evaluation. A common logging anti-pattern,

Log.i("here's the object: " + myObj);

This is problematic because regardless of the level, regardless whether the statement will actually get into the log, myObj.toString() is called and a new String object that is the concatenation of “here’s the object: ” and myObj.toString() is created. Over a large app with many log statements, this can significantly hamper performance. Commonly, the antidote is something like,

if (LOG_LEVEL == Level.INFO) {
    Log.i("here's the object: " + myObj);
}

But this really crufts up the code. Can we avoid this sort of check?

Small log window. The Android log buffer is about 50k. On a device with a good number of apps installed, the entire log window can scroll in a matter of minutes. This makes it impossible to go back and examine the log for specific events.

To solve these problems, I created a simple utility class, ALog (advanced log).

To add context, it automatically appends the class and method name, and line number to the beginning of every statement. The result is clear, contextual log statements like this,

W/my-app(23659): InstallManager.<init>@120: failed to make APK dir: /mnt/sdcard/Download

ALog avoids evaluating arguments by accepting a log pattern plus arguments,

ALog.w("oh noes, a problem occured when i %s and then also at %s", msg1, msg2);

The first argument, the format, must conform to the interface dedefined by String.format().

ALog support setting a global tag for the entire app, and setting the level. Do so in your application class,

public class MyApplication extends Application {
    @Override
    public void onCreate() {
        ALog.setTag("MyApp");
        ALog.setLevel(CLog.Level.D);
    }
}

ALog optionally writes every log record to a file on your SD card, to keep a nearly infinite log of exactly what happened in your app. Just enable file logging like,
ALog.setFileLogging(true);

Files are created at: <Environment.getExternalStorageDirectory()>/alog/<tag>.log
Note that this is extremely inefficient. It should only be used temporarily to find bugs then disabled. It should never be used in production. You can look at the code below, but it starts a thread that take()’s from a blocking queue. Logging a message offers()’s into this queue. The file is opened, appended, and closed at each log statement; it does not keep the file open.
Here’s the source,
public class ALog {
	private static class LogContext {
		LogContext(StackTraceElement element) {
			// this.className = element.getClassName();
			this.simpleClassName = getSimpleClassName(element.getClassName());
			this.methodName = element.getMethodName();
			this.lineNumber = element.getLineNumber();
		}

		// String className;
		String simpleClassName;
		String methodName;
		int lineNumber;
	}

	public enum Level {
		V(1), D(2), I(3), W(4), E(5);

		private int value;

		private Level(int value) {
			this.value = value;
		}

		int getValue() {
			return value;
		}
	};

	private static final DateFormat FLOG_FORMAT = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm:ss.SSS");
	private static final File LOG_DIR = new File(
			Environment.getExternalStorageDirectory() + File.separator + "alog");
	private static boolean fileLogging = false;
	private static String tag = "<tag unset>";
	private static Level level = Level.V;
	private static final BlockingQueue<String> logQueue = new LinkedBlockingQueue<String>();
	private static Runnable queueRunner = new Runnable() {
		@Override
		public void run() {
			String line;
			try {
				while ((line = logQueue.take()) != null) {

					if (!Environment.getExternalStorageState().equals(
							Environment.MEDIA_MOUNTED)) {
						continue;
					}
					if (!LOG_DIR.exists() && !LOG_DIR.mkdirs()) {
						continue;
					}

					File logFile = new File(LOG_DIR, tag + ".log");
					Writer w = null;
					try {
						w = new FileWriter(logFile, true);
						w.write(line);
						w.close();
					} catch (IOException e) {
					} finally {
						if (w != null) {
							try {
								w.close();
							} catch (IOException e1) {
							}
						}
					}
				}
			} catch (InterruptedException e) {
			}
		}
	};

	static {
		new Thread(queueRunner).start();
	}

	private static LogContext getContext() {
		StackTraceElement[] trace = Thread.currentThread().getStackTrace();
		StackTraceElement element = trace[5]; // frame below us; the caller
		LogContext context = new LogContext(element);
		return context;
	}

	private static final String getMessage(String s, Object... args) {
		s = String.format(s, args);
		LogContext c = getContext();
		String msg = c.simpleClassName + "." + c.methodName + "@"
				+ c.lineNumber + ": " + s;
		return msg;
	}

	private static String getSimpleClassName(String className) {
		int i = className.lastIndexOf(".");
		if (i == -1) {
			return className;
		}
		return className.substring(i + 1);
	}

	public static void setLevel(Level l) {
		level = l;
	}

	public static void setTag(String t) {
		tag = t;
	}

	public static void setFileLogging(boolean enable) {
		fileLogging = enable;
	}

	public static void v(String format, Object... args) {
		if (level.getValue() > Level.V.getValue()) {
			return;
		}
		String msg = getMessage(format, args);
		Log.v(tag, msg);
		if (fileLogging) {
			flog(Level.V, msg);
		}
	}

	public static void d(String format, Object... args) {
		if (level.getValue() > Level.D.getValue()) {
			return;
		}
		String msg = getMessage(format, args);
		Log.d(tag, msg);
		if (fileLogging) {
			flog(Level.D, msg);
		}
	}

	public static void i(String format, Object... args) {
		if (level.getValue() > Level.I.getValue()) {
			return;
		}
		String msg = getMessage(format, args);
		Log.i(tag, msg);
		if (fileLogging) {
			flog(Level.I, msg);
		}
	}

	public static void w(String format, Object... args) {
		if (level.getValue() > Level.W.getValue()) {
			return;
		}
		String msg = getMessage(format, args);
		Log.w(tag, msg);
		if (fileLogging) {
			flog(Level.W, msg);
		}
	}

	public static void w(String format, Throwable t, Object... args) {
		if (level.getValue() > Level.W.getValue()) {
			return;
		}
		String msg = getMessage(format, args);
		Log.w(tag, msg, t);
		if (fileLogging) {
			flog(Level.W, msg, t);
		}
	}

	public static void e(String format, Object... args) {
		if (level.getValue() > Level.E.getValue()) {
			return;
		}
		String msg = getMessage(format, args);
		Log.e(tag, msg);
		if (fileLogging) {
			flog(Level.E, msg);
		}
	}

	public static void e(String format, Throwable t, Object... args) {
		if (level.getValue() > Level.E.getValue()) {
			return;
		}
		String msg = getMessage(format, args);
		Log.e(tag, msg, t);
		if (fileLogging) {
			flog(Level.E, msg, t);
		}
	}

	public static void trace() {
		try {
			throw new Throwable("dumping stack trace ...");
		} catch (Throwable t) {
			ALog.e("trace:", t);
		}
	}

	public static String getStackTraceString(Throwable tr) {
		if (tr == null) {
			return "";
		}

		Throwable t = tr;
		while (t != null) {
			if (t instanceof UnknownHostException) {
				return "";
			}
			t = t.getCause();
		}

		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter(sw);
		tr.printStackTrace(pw);
		return sw.toString();
	}

	private static void flog(Level l, String msg) {
		flog(l, msg, null);
	}

	private static void flog(Level l, String msg, Throwable t) {
		String timeString = FLOG_FORMAT.format(new Date());
		String line = timeString + " " + l.toString() + "/" + tag + ": " + msg
				+ "\n";
		if (t != null) {
			line += getStackTraceString(t) + "\n";
		}
		logQueue.offer(line);
	}
}


Android Bitmap Scaling

2011/01/27

Scaling images is a common task for many applications including those written for Android. The most obvious approach, as described on this page, won’t work in most cases. The problem as you would soon find out if you tried it is that your phone doesn’t have enough memory. Luckily we can get around that, but not easily.

The trick ends up being a two step process. First we decode the bitmap, setting the sampling level as high as we can while avoiding loss of quality, then we scale this smaller bitmap in memory down to the exact specified size. I’ve included this in a nicely packaged class BitmapScaler, included at the end of this post.The class itself looks quite long but this is only because it has the flexibility of scaling bitmaps from resources, assets, and files.

BitmapScaler preserves the aspect ratio. You may only pass a new width. The resulting height will be scaled equal to the amount the width was scaled.

For example,

BitmapScaler scaler = new BitmapScaler(getResources(), R.drawable.moorwen, newWidth);
imageView.setImageBitmap(scaler.getScaled());

BitmapScaler class follows,

class BitmapScaler {
	private static class Size {
		int sample;
		float scale;
	}

	private Bitmap scaled;

	BitmapScaler(Resources resources, int resId, int newWidth)
			throws IOException {
		Size size = getRoughSize(resources, resId, newWidth);
		roughScaleImage(resources, resId, size);
		scaleImage(newWidth);
	}

	BitmapScaler(File file, int newWidth) throws IOException {
		InputStream is = null;
		try {
			is = new FileInputStream(file);
			Size size = getRoughSize(is, newWidth);
			try {
				is = new FileInputStream(file);
				roughScaleImage(is, size);
				scaleImage(newWidth);
			} finally {
				is.close();
			}
		} finally {
			is.close();
		}
	}

	BitmapScaler(AssetManager manager, String assetName, int newWidth)
			throws IOException {
		InputStream is = null;
		try {
			is = manager.open(assetName);
			Size size = getRoughSize(is, newWidth);
			try {
				is = manager.open(assetName);
				roughScaleImage(is, size);
				scaleImage(newWidth);
			} finally {
				is.close();
			}
		} finally {
			is.close();
		}
	}

	Bitmap getScaled() {
		return scaled;
	}

	private void scaleImage(int newWidth) {
		int width = scaled.getWidth();
		int height = scaled.getHeight();

		float scaleWidth = ((float) newWidth) / width;
		float ratio = ((float) scaled.getWidth()) / newWidth;
		int newHeight = (int) (height / ratio);
		float scaleHeight = ((float) newHeight) / height;

		Matrix matrix = new Matrix();
		matrix.postScale(scaleWidth, scaleHeight);

		scaled = Bitmap.createBitmap(scaled, 0, 0, width, height, matrix, true);
	}

	private void roughScaleImage(InputStream is, Size size) {
		Matrix matrix = new Matrix();
		matrix.postScale(size.scale, size.scale);

		BitmapFactory.Options scaledOpts = new BitmapFactory.Options();
		scaledOpts.inSampleSize = size.sample;
		scaled = BitmapFactory.decodeStream(is, null, scaledOpts);
	}

	private void roughScaleImage(Resources resources, int resId, Size size) {
		Matrix matrix = new Matrix();
		matrix.postScale(size.scale, size.scale);

		BitmapFactory.Options scaledOpts = new BitmapFactory.Options();
		scaledOpts.inSampleSize = size.sample;
		scaled = BitmapFactory.decodeResource(resources, resId, scaledOpts);
	}

	private Size getRoughSize(InputStream is, int newWidth) {
		BitmapFactory.Options o = new BitmapFactory.Options();
		o.inJustDecodeBounds = true;
		BitmapFactory.decodeStream(is, null, o);

		Size size = getRoughSize(o.outWidth, o.outHeight, newWidth);
		return size;
	}

	private Size getRoughSize(Resources resources, int resId, int newWidth) {
		BitmapFactory.Options o = new BitmapFactory.Options();
		o.inJustDecodeBounds = true;
		BitmapFactory.decodeResource(resources, resId, o);

		Size size = getRoughSize(o.outWidth, o.outHeight, newWidth);
		return size;
	}

	private Size getRoughSize(int outWidth, int outHeight, int newWidth) {
		Size size = new Size();
		size.scale = outWidth / newWidth;
		size.sample = 1;

		int width = outWidth;
		int height = outHeight;

		int newHeight = (int) (outHeight / size.scale);

		while (true) {
			if (width / 2 < newWidth || height / 2 < newHeight) {
				break;
			}
			width /= 2;
			height /= 2;
			size.sample *= 2;
		}
		return size;
	}
}

Or, try out the Eclipse test project.


Android Shortcuts

2011/01/23

Shortcuts are an often overlooked usability enhancer for your Android app.  They are a nice alternative to providing quick access to particular locations or views of data, where you would otherwise have “favorites” or “most recently used” function. I wanted to take a moment to share my implementation experience.

My use case: I am the author of the Clear Sky Droid (and the donate version) app which is available on the Android market. Being a tad esoteric, it’s probably not the best example, but I’ll try my best to explain the usability problem in abstract terms. Essentially, the user can define a list of favorites by searching for items. From the list of favorites, they can then select a detailed view of the item. The usability problem is that many users want direct access to the detailed view of a particular favorite – something that is normally 3 clicks away.

Shortcuts to the rescue. With this feature, the user can set up a desktop shortcut for direct access to the detailed view of a particular favorite. It’s now one click away.

What exactly is a shortcut? It’s an Android desktop artifact. It is not part of your application. When clicked, it broadcasts an intent that you have defined. So you can see where this is going. You simply need to set up your application to respond appropriately to whatever intent is configured into the shortcut.

First we will register an activity into the Android “create shortcuts” home screen menu. Create a new activity, or add the functionality to an existing activity. Respond to the create shortcut intent,

<intent-filter>
    <action android:name="android.intent.action.CREATE_SHORTCUT" />
    <category android:name="android.intent.category.DEFAULT" />
</intent-filter>

You can look at CSDroid’s AndroidManifest.xml to see this in context.

This is all it takes to make your application show up when the user long presses on the home screen and select “shortcuts”.

You must now make your application handle the intent. In CSDroid, look at the startService() method in the class TabwidgetActivity, find the line where it’s checking if the intent’s action is “android.intent.action.CREATE_SHORTCUT”. This means the user has long pressed the home screen and selected your app.

Gather any information necessary to customize the shortcut to access to a particular aspect of your application.  For CSDroid, we open a dialog that lets the user select a favorite item. Looking at the code in TabwidgetActivity mentioned above, you can see that a dialog  is shown when the CREATE_SHORTCUT intent is received.  The dialog builder class is FaveShortcutDialogBuilder.

FaveShortcutDialogBuilder just gets the favorite item then calls back to TabwidgetActivity‘s saveShortcut() method. This is where we request creation of the desktop shortcut. Here are the steps,

  1. Create an intent that targets your application, setting action, data, extras, etc accordingly to perform the specific action requested when the user clicks the shortcut
  2. Wrap that intent in another intent that will be sent back to the Android “create shortcut” activity
  3. Set this wrapping intent as the result of your activity, and finish

Here’s the code from CSDroid,

void saveShortcut(Site site) {
    Intent shortcutIntent = new Intent(this, TabWidgetActivity.class);
    shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    shortcutIntent.putExtra("org.jtb.csdroid.site.id", site.getId());

    Intent intent = new Intent();
    intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
    intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, site.getName());
    intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(this, R.drawable.icon));
    intent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
    setResult(RESULT_OK, intent);
    finish();
}

In this case, if CSDroid sees a site ID in the intent’s extras, it will perform the shortcut action for that site ID.

I should not that in the context of CSDroid the code could be organized better. A better pattern would separate the main activity from the short cut creation, and shortcut handling activities. So you might have MainActivity, CreateShortcutActivity, and HandleShortcutActivity.

One last gotcha … my first idea was to auto-create the shortcut from the app. In other words, circumvent the steps where the user must long-press the home screen, select shortcuts, select my app, then select a favorite – all from within the application. CSDroid already has an activity that lists the user’s favorites. I wanted to simply add a “add shortcut” option right there. Well, you can’t do that. You cannot programmatically create shortcuts. Only the user can do that.

CSDroid is open source. Visit the CSDroid Google code project page to find the source code, etc.

And finally, all due credit to Attilla Danko, the owner of ClearDarkSky.com, the data source for this application.


Gracefully Handle When Location is Unavailable (Android)

2010/12/24

This seemed like a useful pattern so I thought I’d document it here, as it seems quite common. The scenario is that you have an application that provides some location-based service or information, but needs to gracefully handle the situation when the location cannot be obtained.

Ther are various reason why the location might not be obtainable. The most common is that the user disabled one or all location services requested by your app. Just because you request location permissions and the user accepts doesn’t mean that they actually have those services enabled. And worse, when you request a location in this situation, you don’t get any sort of indicator that it has been disabled. Your location changed callback is just never called.

My application grabs earthquake data from USGS and provides information to the user with respect to their proximity to the quake. If the app can’t get the user’s location, it should functionally normally, minuses providing distances to quake epicenters. For reference, the app is called QuakeAlert! and you can find it on the market, and the source on Google code.

QuakeAlert! has a service that runs periodically and alerts the user of any new earthquakes that match their criteria. When the service runs, it should get the location if possible, process the data from USGS, and potentially alert the user. The problem is in how Android location callbacks operate. The service can request a location update, but there’s no guarantee it will ever be called (and it won’t if the user has disabled the location service).  Here is the solution,

UpdateService- this is an intent service that does the real work, whatever that may be. In the case of QuakeAlert! it fetches the data from USGS and processes it, sends notifications, and updates the user interface (if it’s running).

LocationService- this is a regular (non-intent) service that does the following,

  1. Registers for location updates
  2. Schedules a TimerTask for execution (say a few minutes in the future)

If the service gets an “on location changed” event before the time is up, it cancels the timer. If the timer runs first, it cancels the “on location changed” registration. In both cases, it calls the UpdateService to do the work.

UpdateService gets the location by calling getLastKnownLocation(). If there was a location obtained through the running of LocationService then it will get that location and use it. The last known location may have also been obtained by a different application at some earlier time getting location updates. That’s okay to, we know we’ve tried our best to get the most accurate location we can at the time.

The implementation of LocationService in QuakeAlert! is reusable. Just pass it a timeout (in milliseconds) and a broadcast intent to send when either the location in obtained or when the timer executes. For example,

// create broadcast intent that will ultimately start your
// intent service
Intent broadcastIntent = new Intent(...);

Intent locationIntent = new Intent(context, LocationService.class);
locationIntent.putExtra("timeout", 1000 * 60 * 2); // 2 minutes
locationIntent.putExtra("broadcastIntent", broadcastIntent);
context.startService(locationIntent);

Why pass a broadcast intent, instead of an intent that would start the update service directly? Since UpdateService is an intent service, we must obtain a wake lock before it is run, and the pattern for doing that is to receive an intent (in a receiver), grab the lock there, start the service from the reciever’s handler, then release the lock in the intent service when the work is done.

Note that this same pattern applied to a a foreground activity is much more straighforward: 1) register for location updates 2) open a cancelable progress dialog. If we get an “on location changed” event, dismiss the dialog, and start the UpdateService. If the user cancels, dismiss the dialog, and start the UpdateService. In both cases remember to remove thelocation listener.


3D Model Viewer for Android

2010/12/07

I just published a new application on the Android Market. It’s called ModelView and is a 3D model viewer. You can download it onto 1.6+ devices. It supports loading of standard .OFF and .OBJ format files, allows rotation and zoom (via multi-touch, on 2.0+ devices), and comes packaged with many interesting 3D models. You can also view your own .OBJ / .OFF files by placing them on the SD card.

This started out as a sample OpenGL project, with me learning how to define simple 3D objects with vertices and triangles. From there I started to think about how I could define the model’s data some other way than statically in the code. Then I started looking for standard ways to do that. Then getting lazy and wanting to take advantage of models defined by others.  I ended up learning quite a bit about OpenGL and 3D graphics. Now it’s time to get a book and put it all in it’s place. The app is really just a learning exercise and serves no real purposes, but it’s fun to play with so I posted on the market so other people can take a look. The code is available on Google code, and hopefully someone else can learn from this.


Netflix on Android

2010/11/20

Like many Android users I’m dismayed at the lack of a Netflix application. I loathe that I have to go grab my iPod when I want Netflix on the go. Apparently there’s a good reason for this, however, as a naive mid-level Android developer I’m at a loss trying to understand what that reason is. In a recent blog entry, Greg Peters from Netflix said,

“The hurdle has been the lack of a generic and complete platform security and content protection mechanism available for Android. The same security issues that have led to piracy concerns on the Android platform have made it difficult for us to secure a common Digital Rights Management (DRM) system on these devices.”

What does copy protection have to do with a streaming app? You authenticate the user and then stream. Nothing is every written to disk (except maybe a buffer) so there’s nothing to copy. The stream itself must be protected, so the point of comprise would need to be the memory space in the app itself, where the unencrypted stream is present. In Android, you’d need to have a rooted phone and a native library or app to access this. Sure, it’s relatively easy to root Android phones, but it’s easy to root an iPhone as well.

Also, what piracy concerns? It used to be the case that apps were pirated left and right, but that’s not true anymore. Android did away with its copy protection scheme and now uses a license management service which is built right into the Android SDK. Regardless, what do pirated apps have to do with digital content protection?

Content holders in general would do well to understand the purpose of DRM in 2010. It’s purpose should NOT be to prevent people from copying copy protected digital media. Why not? Because that’s impossible. The world contains an infinite supply of bored 15 year olds with nothing but time on their hands. They will beat whatever scheme you put in place. You can waste innumerable costly hours of  highly paid staff software developers coming up with a new methodology to have it broken in hours.

So what should be the purpose of DRM? To make stealing content annoying. To make it, for 99.9% of the schlubs out there, easier and more cost effective to pay for the content than it is to steal it … and write off your losses for that 0.1% of people that have way more time than money and will find a way to beat the DRM regardless.

Content holders should understand that any content (music, movies, bookes) is a bitorrent download away, and one need not be highly technical to grab it. Go to a site. Search. Click. Wait 10 minutes. That’s it. Make it easier and more cost effective than that to purchase content. If you don’t, people will steal it.

Coming back to Netflix and Android … a Netflix app doesn’t need to provide uber-safe device dependent hardware-level DRM. If it simply avoids writing the video file to a persistent store that would be enough.

Netflix tells us we can expect an app in 2011,

But I’m happy to announce we’ll launch select Android devices that will instantly stream from Netflix early next year.

That means we’ll see a Netflix app for the premiere devices / carriers – like whatever the latest Motorla Droid will be at the time. I don’t hold much hope for my poor Nexus One, relegated to a second class carrier like T-Mobile.


Android Themes: an Adventure

2010/10/25

I am the author of a simple Android app widget , “Uptime Widget” that shows the uptime, and max uptime of the user’s device. As widgets are rendered on the home screen their readability greatly varies depending on the user’s wall paper. I got a lot of request to provide “lighter” or “darker” versions of widget. This prompted me to investigate Android’s theming abilities.

My first attempt didn’t use themes or styles at all. I integrated the simple color picker dialog from the Android API demos, with the intention of having an app widget configuration activity that allowed the user to pick their background and text color, at the least. I found at the hard way the RemoteViews, the view class used to build app widgets doesn’t allow programmatic setting of the background color.  Back to the drawing board.

My next attempt was to use Android’s theme / style facilities in full. Essentially, define several themes and allow the user to pick one in a configuration activity. This page has an excellent example and sample code. I was quite frustrated before finding this, as there aren’t really any good examples of how to make dynamic references to styles, versus statically declaring their use in the layout. That’s critical if you are to have >1 theme for your application. Unfortunately, you can’t use this method for app widgets. I don’t understand why at this point, another limitation in RemoteViews. I filed an issue against the AOSP. I won’t hold my breath.

The only option left is to statically declare style usage in the app widget’s layout. To get multiple, dynamic themes, the app widget must build the RemoteViews object based on a dynamically picked layout ID. That means having one layout per theme (and in my case, additionally, per orientation). Uptime Widget has 8 very similar layouts. A terrible solution by all regards. Modifying the UI or adding a theme is a tedious error-prone endeavor. But it works. You can take a look at the source over at the Google code project if you are interested.

All in all, I found Android style / theme mechanism lacking. First. the method of referencing a theme is awkward. You must first declare a reference attribute,

<attr name="Caption" format="reference"/>

then, create various styles that map to the reference,

<style name="Dark.Caption">
  <item name="android:textColor">@android:color/black</item>
</style>
<style name="Light.Caption">
  <item name="android:textColor">@android:color/white</item>
</style>

Now, map that reference to real styles within a theme,

<style name="DarkTheme">
  <item name="Caption" value="@style/Dark.Caption"/>
</style>
<style name="LightTheme">
  <item name="Caption" value="@style/Light.Caption"/>
</style>

Finally, use the attribute reference in your layout,

<TextView style="?Caption" .../>

and set the theme using the android:theme attribute to either “DarkTheme” or “LightTheme” at either the application or activity level in your manifest. What’s missing? Selectors. For example, if you apply a theme with android:textColor=”…”, it applies to every element in the layout. The only way to get around this is to call out the specific style (or reference to a style, as shown above) in each view element. We need to be able to select on the element type and  ID like,

<item name="android:textColor" selector="@+id/topLayout/*.TextView">
  @android:color/black
</item>

This styles only TextViews under the element with the topLayout. There would need to be some advanced syntax, for example, to select elements recursively. CSS is not simple, and it would not be simple to mimic it either, but without this Android styles are sorely lacking.


aLogcat – Android Logcat Application

2009/11/30

aLogcat market barcode

There are several “log view” applications on the market. All of them provide a means to send your log file contents, typically via email. This is one good approach, but it doesn’t handle the use case where you don’t have immediate access to a PC email client to view the results. aLogcat is an Android application that allows you to view your Android device log from the device itself. It provides a scrolling, color-coded log that is filterable by keyword and log level. It also supports output in various log formats. aLogcat also covers the send log use case by allowing a snapshot of the log to be sent off to another device.

This is mainly an app for developers, but it is also useful for power users that are willing to get involved with developers to help them find problems in their applications. Most Android developers are small scale hobbyists and can’t devote full-time effort and money to rigorous testing across multiple devices. I hope this app lowers the barrier for involvement of the average user in the development cycle.

aLogcat


DroidLife – Conway’s Game of Life for Android

2009/10/27

icon

device-1

Gosper's Glider Gun in progress

I just posted a new Android app to the market: DroidLife, an implementation of Conway’s Game of Life. CGoL is a simulation (zero-player game) of cellular life (don’t confuse it with Milton Bradley’s Game of Life, a board game). The app bundles many interesting seeds, and allows users to download thousands of others and run them as well. Seeds are just initial simulation states, and more specifically are simply a set of one or more points on a grid representing live cells. There are around 4 “standard” seed file formats. DroidLife understands the most common / simple of those, Life 1.06. The most complete repository of seed files can be found on LifeWiki.

I was initially motivated to write this app as it was the topic of an interview question, for which I was only able to give a mediocre answer. One thing is for sure, if anyone ever asks me about CGoL again in my life, I have enough information to bore them for hours. I also saw it as a chance to get my feet wet with some trivial graphics on Android. Credit to “MrSnowFlake” for putting together this game template (bump) thread, based on Android’s Lunar Lander sample, which helped me get started. Without it my ramp up time would have been much greater.

Depending on my time, here are a few things I’d like to add to the app,

  1. Read other file formats: RLE, PlainText, Life 1.05
  2. Save game state to file
  3. Seed editor: define you own seeds
device-2

A b1s12 world seeded with a single cell


httpmon – HTTP Server Monitor

2009/10/23

icon

device-1I just published a new application to the Android Market: httpmon. In a nutshell, it allows you to monitor the status of any number of HTTP servers. A monitor is made up of 1) a request which describes how to contact the server, 2) one or more conditions that must hold true to consider the server “valid”, and 3) zero or more actions to take if the server is “invalid”.

This was another learning exercise. I wanted to play around with how I would structure an extensible object model in Android. The app source is structured so that the conditions and action class trees are easily extensible at both the model and view level to add new types of conditions and actions. I’m quite happy with how well it came out in that regard. None of this is probably visible from using the app however.

I hope that at least some people find this useful, as I’m looking forward to receiving input for new types of conditions and actions.

Supported conditions,

  • ping
  • response time
  • response code
  • content contains (substring, wildcard, or regex match)
  • header container (substring, wildcard, or regex match)

Supported actions,

  • notification (alert sound, flash, and / or vibrate)
  • send SMS

I wanted to have a “send email” action, but it turns out that there is no way to send an email programmatically, on behalf of the user, with Android. I am not sure why they would let an app send an SMS on behalf of the user, but not an email. An SMS seems more dangerous actually. Of course, I could have used JavaMail, but that means gathering an SMTP server and port, and supporting credentials. Most users will lack the will or the way to set that up I think.


Follow

Get every new post delivered to your Inbox.