Friday, January 29, 2010

Mass storage device detection on connection using Flex 4 or AIR 2

Prerequisites: AIR 2.0 ,Flash Builder 4 with Flex 4(build 10485) , a brief knowledge of using flex.

OK guys, I am pretty sure that every flex developer is excited abotu this amazing capability of detection of mass storage when a device is mounted on an OS.The following is the code snippet which allows users to open a file browser with the current directory as the root of the new mounted volume.

<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/halo"
creationComplete="windowedapplication1_creationCompleteHandler(event)"
>
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<fx:Script>
<![CDATA[
import flash.events.StorageVolumeChangeEvent;

import mx.events.FlexEvent;


protected function windowedapplication1_creationCompleteHandler(event:FlexEvent):void
{
// TODO Auto-generated method stub
var s:StorageVolumeInfo=StorageVolumeInfo.storageVolumeInfo;
s.addEventListener(StorageVolumeChangeEvent.STORAGE_VOLUME_MOUNT,USBMounted);
}
public function USBMounted(event:StorageVolumeChangeEvent):void
{
var file:File=event.rootDirectory;
var files:Array=file.getDirectoryListing();
for each(var f:File in files)
{
trace(f.nativePath);
}
file.browse();
}

]]>
</fx:Script>
</s:WindowedApplication>


In the above code there are two major objects you need to know about, the StorageVolumeInfo and the StorageVolumeChangeEvent that is dispatched whenever there is a change in the StorageVolumeInfo.
The StorageVolumeInfo object is an object which as the name suggest, is an object which stores information about all the storage devices currently connected to the system.

The line:
s.addEventListener(StorageVolumeChangeEvent.STORAGE_VOLUME_MOUNT,USBMounted);
adds an event listener to the StorageVolumeInfo object , to listen to the event dispatched whenever there is a new volume mounted on the system.

After this in the function USBMounted , using the event object you can access the newly mounted filesystem using the method :
var file:File=event.rootDirectory;

Right now all this program does is opens a browser window with the current directorty as the root of the newly mounted filesystem.But there are many amazing things you can do , like creating a synchonization gadget for specific flash drives, creating your own file browser etc.

Stay tuned for next tutorial on using server sockets.

No comments:

Post a Comment