Friday, August 14, 2009

How to Open Gmail Attachments with Android Apps

I've just added a new feature to my Android cook book application Bites! You can now send and receive recipes as xml files attached to emails.

From the users point of view the feature works like this:
  1. The sender simply long clicks on a recipe and selects send via email in the context menu. The gmail application opens up with the recipe attached to an email, all that is left to do is enter a contact name in the to field and hit send.
  2. The receiver simply opens their gmail inbox and hits the preview button next to the recipe file attachment, then Bites opens with a dialog box asking if they want to import the recipe. That's it, couldn't be easier!

Now the technical details for those of your that are looking to include the ability to open a gmail file attachment in your own Android applications.

First up you'll need an intent filter to handle the attachment file type you are interested in opening with your activity, so to open xml files your activity needs the following in the manifest (leading underscores to allow display in blogger).

<_action name="android.intent.action.VIEW">
<_category name="android.intent.category.DEFAULT">
<_data mimetype="text/xml">

Then in your activity you'll need to handle the gmail attachment intent uri which has a content:// scheme. This intent contains a uri to a gmail content provider that points to the file attachment on google servers. To read a file attachment you have to open an input stream from the content provider using the uri in the intent created by the gmail application like this:

if (getIntent().getScheme().equals("content")) {
InputStream attachment = getContentResolver().openInputStream(getIntent().getData());

In my application this input stream is an xml file, which I can then create a document object from and parse using the following:

DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(attachment);
Element recipe = doc.getDocumentElement();
String strRecipe = recipe.getAttribute("name");

To see the full code in context take a look at the Bites source code (available under GPLv3).

If you would like to install Bites just scan the QR code below with your Android phone (you'll need to use the barcode scanner app).

No comments:

Post a Comment