I’ve recently finished work on an app that registers itself as a handler for a given file extension, let’s call it “.mytype”, so if the user attempts to open a file named “file1.mytype” our app would launch and receive an Intent containing the information on the file’s location and its data can be imported. Specifically I wanted this to happen when the user opened an email attachment, as data is shared between users via email attachment for this app.

There are many pitfalls to doing this, and the Stack Overflow answers I saw given for the question had various side-effects or problems. The most common was that your app would appear in the chooser dialog whenever the user clicked on an email notification, for any email – not just those with your attachment. After some trial and error, I came up with this method.

Create IntentFilters in AndroidManifest.xml

The first step is to add <intent-filter> nodes to the application node of the AndroidManifest.xml. Here’s an example of that:

<intent-filter>
  <action android:name="android.intent.action.VIEW" />
  <action android:name="android.intent.action.EDIT" />
  <category android:name="android.intent.category.DEFAULT" />
  <data
    android:mimeType="application/octet-stream"
    android:host="*" 
    android:pathPattern=".*\\.mytype"
  />
</intent-filter>
<intent-filter>
  <action android:name="android.intent.action.VIEW" />
  <action android:name="android.intent.action.EDIT" />
  <category android:name="android.intent.category.DEFAULT" />
  <data
    android:mimeType="application/mytype"
    android:host="*" 
    android:pathPattern=".*\\.mytpe"
  />
</intent-filter>

Now something to note here, I’ve specified a filter for both “application/mytype” mimetype and also the more generic “application/octet-stream” mime type. The reason for this is because we can’t guarantee the attachment’s mime-type has been set correctly. We have iOS users and Android users sharing timers via email, and with iOS the mime type is set, with Android, at least in my tests on Android 4.2, the mime-type reverts to application/octet-stream for attachments sent from within the app.

Permissions

I initially put these IntentFilters on the “home” Activity of my app, however I soon started encountering security exceptions in LogCat detailing how my Activity didn’t have access to the data from the other process (Gmail). I realised this was because my Activity’s tag had the launch mode set to:

android:launchMode="singleTask"

Which prevents multiple instances of it being launched, this is important when users can launch the app from either the launcher icon or in this case via attachment (I didn’t want to have multiple instances of my home Activity running as that would confuse the user). So the solution was simply to create a new “ImportDataActivity” that handled the data import from the attachment, and then launched the home Activity with the Intent.FLAG_ACTIVITY_CLEAR_TOP flag added.

Importing Data

So in ImportDataActivity we need to import the data stored in the attachment, in my case this was JSON. The following shows how you might go about doing this:

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  Uri data = getIntent().getData();
  if(data!=null) {
    getIntent().setData(null);
    try {
      importData(data);
    } catch (Exception e) {
      // warn user about bad data here
      finish(); 
      return;
  }

  // launch home Activity (with FLAG_ACTIVITY_CLEAR_TOP) here…
}

private void importData(Uri data) {
  final String scheme = data.getScheme();

  if(ContentResolver.SCHEME_CONTENT.equals(scheme)) {
    try {
      ContentResolver cr = context.getContentResolver();
      InputStream is = cr.openInputStream(data);
      if(is == null) return;

      StringBuffer buf = new StringBuffer();			
      BufferedReader reader = new BufferedReader(new InputStreamReader(is));
      String str;
      if (is!=null) {							
        while ((str = reader.readLine()) != null) {	
          buf.append(str + "\n" );
        }				
      }		
      is.close();

      JSONObject json = new JSONObject(buf.toString());

      // perform your data import here…

  }
}

That’s all that’s needed to register-for, and read data from custom file-types.

Sending Email with Attachments

Now how about sending an email with a custom attachment. Here’s a sample of how you might do that:

String recipient = "", 
  subject = "Sharing example", 
  message = "";

final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.setType("message/rfc822");

emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{recipient});
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, message);

// create attachment
String filename = "example.mytype";

File file = new File(getExternalCacheDir(), filename);
FileOutputStream fos = new FileOutputStream(file);
byte[] bytes = json.toString().getBytes();
fos.write(bytes);
fos.close();

if (!file.exists() || !file.canRead()) {
  Toast.makeText(this, "Problem creating attachment", 
      Toast.LENGTH_SHORT).show();
  return;
}

Uri uri = Uri.parse("file://" + file.getAbsolutePath());
emailIntent.putExtra(Intent.EXTRA_STREAM, uri);

startActivityForResult(Intent.createChooser(emailIntent, 
        "Email custom data using..."), 
        REQUEST_SHARE_DATA);

Please note that “REQUEST_SHARE_DATA” is just an static int const in the class, used in onActivityResult() when the user returns from sending the email. This code will prompt the user to select an email client if they have multiple apps installed.

As always, please do point out any inaccuracies or improvements in the comments.

The latest Android app I’ve been working for Runloop, the hugely successful iOS interval timer Seconds Pro, is now live. Packed with the following features:

• Quickly create timers for interval training, tabata, circuit training
• Save your timers, as many as you need
• Organize Timers into groups
• Text to speech
• Install timers from the timer repository
• Send your timers to your friends
• Full control over every interval
• Assign music to intervals or timers
• Large display
• The choice of personal trainers up and down the country

seconds

You can download the app now from the Google Play Store.

If you’re looking for high quality Android development, head over to my company’s website – Valis Interactive.

A tutorial I wrote for .NET Magazine is now up on their site. This tutorial takes you through the basics of getting NFC working with Android 4.0+ with a “Top Trumps” like demo. It covers both reading and writing data to/from NFC tags, stickers or cards.

nfc-netmag

Head over to .NET Magazine to read the tutorial!

We had what was probably the first BBQ weather of the year over the weekend, but I wouldn’t know about that. Instead I spent the time coding away at the NFC Hackathon (sponsored by O2) with my fellow team members George Medve and Aaron Newton.

The idea was to spend 28 hours designing and coding something that made use of NFC (Near Field Communication). We were supplied with NFC enabled Galaxy S2s and some useful SDKs from Proxama and BlueVia for tracking NFC campaigns, making payments and tracking users.

We spent the night before the event thinking about just what we could do that was new. Even at this fledgling stage it felt as if everything had been done in some way already, we needed something unique. One idea we explored was transforming shopping by allowing customers to scan NFC price stickers in the many aisles instead of at the till; simply weighing in their shopping at the self checkout (to reduce unpaid bagging) and scanning their phone to transfer the shopping list and payment. Fortunately we didn’t go with this idea as another team at the event did (albeit without the weighing part).

At some point that night another idea came to me, “StreetScreen“. We could allow retailers and advertisers to directly interact with customers by using an NFC sticker in shop windows to initiate a connection between the screen and the phone, and with a multi-user server allow the customer to control the screen in real time.

At the event we used technologies like node.js, HTML, JavaScript and Flash to create some demos including browsing and rotating products, buying flowers for mother’s day and even a 2 player game (see “Connect 4″ game pictured). I’m pleased to say with this we won the Finance category prize sponsored by Visa. Thanks to the truly excellent Isobar and sponsors, the whole event was a lot of fun and I think I’ll be looking forward to developing a product around NFC in the near future.

The potential applications for this technology are endless. The number of NFC enabled handsets is expected to reach 1 in 6 by 2014, but that’s not going to stop us pushing the envelope in the meantime.

If you are interested in using this technology in your campaign please get in touch via the contact form. You can read more about the event over at the Isobar site.

My latest Android project is now live. This app for FanChants.com provides access to the 20,000 real football chants as sung by fans all over the world. Chants include lyrics and through an in-app-purchase chants can be set as your phone’s ringtone.

FanChants

View FanChants over at Google Play

I’m pleased to announce a game we’ve been working on is now out. A collaboration between The Creation Agency and Bitmode (my previous home), we bring you The Great Snowball Fight!

Snowball Fight

The game is played over Google Maps, launching virtual snowballs at unsuspecting players in order to rank up, earn points and even win prizes from retailers you hit. You can also add buddies, connect via Facebook and receive special powerups.

Utilising Flash with AIR 3 and native extensions, we were able to build a game for iOS, Android and also PC. The game uses native extensions for deeper platform integration, such as the compass sensor or push notifications, as well as GPS to pin-point your location.

Head on over to the site to download the game and get throwing some snowballs!

Update: See comments for iOS compass extension source.

I recently wrote a tutorial for .NET Magazine covering styling and theming components in Android. This includes how to use resolution independent units so that your UI looks crisp across a wide range of devices and 9-patch images for smooth scaling.

netmag_android

Here’s a link to the article.

I was absolutely delighted to hear that the app I put together for the Vodafone Smart Accessibility Awards has been made a finalist. The app, “Are You OK” falls under the wellbeing category. If you’re not familar with the awards, the idea is to improve the lives of the elderly or disabled through technology.

Are You OK is a simple app that was inspired by the panic button pendants many elderly use in their homes. The button communicates with a base-station plugged into the phone which contacts an emergency call center and and a voice can be heard over the speakerphone. The problem is these buttons are often left lying around out of reach, and many hours, or at worst days can go by before they get help after something like a fall. On top of this there’s a monthly fee for the service.

Are You OK works in reverse. It has an easily configurable alarm which goes off every X hours throughout the day, asking if they are OK with two big buttons, yes or no. If they hit no or fail to get to the phone within a certain time, it sends a text message to chosen friends or family asking them to check in by phone or by dropping by.

Tomorrow I’m off to Brussels to present the app before a panel. Here’s hoping it all goes well and if I’m very lucky I’ll get to bring back good news!

You can view the final 12 apps here.

The Android Workshop is coming to TechHub in London, tickets are now available for Thursday 24th and Friday 25th of November this year. It’s a full 2 day introduction covering a wide range of topics from layouts and widgets to styling and database access, for more info please head over to the site. Sign up fast to guarantee your Early Bird price, or add yourself to the mailing list for future events.

Finally there’s the Twitter account @androidws, feel free to shoot over any questions you may have or drop them in the comment form below. Look forward to seeing you there.

Earlier today Paulo Fierro blogged an example of how to build a dynamic application cache manifest for HTML5 web apps using Ruby.

A cache manifest is a text file that browsers look for in order to determine which files to store locally on the device, this lets you open the site/app offline, great for web apps (on iOS bookmarking a site to the home screen also let’s you specify an icon and removes browser chrome). Creating a cache manifest dynamically means that you don’t have to worry about modifying a text file every time you add or remove a file from the app.

This prompted me to upload my PHP version that works pretty much in the same way. I built it for an iPad web app that needed to run completely offline collecting peoples details at a car show (it later synced data with a server when it found a connection). It’s pretty basic, it just creates an MD5 of all the files in a directory (apart from excluded files, including itself!), so that when one is changed, either the content or the name, the MD5 value changes and that results in the contents of the manifest changing, causing the browser to re-evaluate it.

Below is the dynamic manifest, let’s call it “cache.manifest.php”:


<?php 
	header("Cache-Control: max-age=0, no-cache, no-store, must-revalidate");
	header("Pragma: no-cache");
	header("Expires: Wed, 11 Jan 1984 05:00:00 GMT");
	header('Content-type: text/cache-manifest'); 
	
	$hashes = "";
	
	function printFiles( $path = '.', $level = 0 ){ 
		global $hashes;
	    $ignore = array('.', '..','.htaccess','cache.manifest.php','index.html','submit.php', "video.mp4");  

	    $dh = @opendir( $path ); 

	    while( false !== ( $file = readdir( $dh ) ) ){ 
	        if( !in_array( $file, $ignore ) ){ 
	            if( is_dir( "$path/$file" ) ){ 
	                printFiles( "$path/$file", ($level+1) ); 
	            } else { 
					$hashes .= md5_file("$path/$file");
	                echo $path."/".$file."n";
	            } 
	        } 
	    } 

	    closedir( $dh ); 
	}
?>
CACHE MANIFEST
<?php 
printFiles('.');
// version hash changes automatically when files are modified
echo "#VersionHash: " . md5($hashes) . "n";
?>

NETWORK:
./submit.php
./video.mp4

FALLBACK:
./video.mp4 ./images/offline.jpg
./images/video.jpg ./images/offline.jpg

Remember that cache space is extremely limited. I think it was about 5mb on the iPad first gen. If you need more space you’ll have to use local SQLLite (perhaps storing blobs) and request more DB space from the user.

So you probably don’t want to be including things like video files, you also don’t want to cache the output of dynamic server-side scripts. This is what the NETWORK and FALLBACK portions of the manifest are used for. You can force the browser to only look to the network for certain files, and also provide fallbacks for files it won’t find offline (in the case above, it shows an offline image in place of the video).

To make the browser look for the manifest, you just add the manifest attribute to the HTML tag:

<html manifest="cache.manifest.php">

Now when it comes to actually forcing your client app to check for updates, the following JavaScript should provide some insights. Sorry it’s a bit rough and ready, but it should illustrate how you might invoke an update:


var cacheStatus = getCacheStatus(window.applicationCache.status);
	console.log("App cache status: " + cacheStatus); 
	
	var appCachedHandler = function () {
		console.log("AppCache cached");
		dialog.dialog("close");
	}
	var updateReadyHandler = function() {
		console.log("AppCache update ready");
		
		$("#versionImg").attr("src", src="images/update_available.png");
		$("#versionImg").css("visibility", "visible");
		
		dialog.dialog("close");
			
		if(	!isSyncing && confirm("Update available, update now?") ) {
			window.applicationCache.update();
			window.applicationCache.swapCache();
			window.location.reload(true);
		}
	}
	var downloadingCacheHandler = function() {
		console.log("AppCache downloading...");
		dialog.dialog({modal: true, title: 'Downloading update...'});
			
		$("#versionImg").attr("src", src="images/loading_small.gif");
		$("#versionImg").css("visibility", "visible");
	}
	var cacheErrorHandler = function(obj) {
		console.log("AppCache error " + obj);
		dialog.dialog({modal: true, title: 'Cache error:'+obj});
	}
	window.applicationCache.addEventListener('cached', appCachedHandler, false);
	window.applicationCache.addEventListener('updateready', updateReadyHandler, false);
	window.applicationCache.addEventListener('downloading', downloadingCacheHandler, false);
	window.applicationCache.addEventListener('onerror', cacheErrorHandler, false);