Posted in | Posted on 06-27-2009 | 2,834 views
Gary asked me an interesting question relating to AIR applications. He wanted to know if there was a way for an AIR application to know the username of the current user. I would have guessed that this would be part of the AIR API, but after a bit of searching and asking around, it turns out that this is not the case.
While there isn't a direct API, there is a nice workaround that I found on Stack Overflow (Get the current logged in OS user in Adobe Air). The solution simply assumes that all users have a base directory that includes their username. On my Mac, it is "/Users/ray". On my Windows box (yes, I'm ashamed, I still keep one around), the directory is "c:\documents and settings\administrator". So this technique seems like a good one. You could certainly use it to suggest the current username. Here is a simple demo that Gary cooked up using this technique:
2<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" horizontalAlign="center" verticalAlign="middle">
3
4<mx:Script>
5<![CDATA[
6
7public function currentOSUser():String {
8 var userDir:String = File.userDirectory.nativePath;
9 var userName:String = userDir.substr(userDir.lastIndexOf(File.separator) + 1);
10 return userName;
11}
12
13]]>
14</mx:Script>
15
16<mx:Text text="{currentOSUser()}" fontSize="75" horizontalCenter="true"/>
17<mx:Text text="is a winner!" fontSize="20" />
18
19</mx:WindowedApplication>
I modified it a bit just to simplify things. Running it on my Mac I see:

On my PC (oh, and I loved how the AIR installer noticed my PC was a bit behind on the AIR SDK and updated itself) it displayed:

Ok, one last tip. Gary was trying to use binding with this method and had trouble getting it working. Let's look at what he did.
2var userDir:String = File.userDirectory.nativePath;
3var userName:String = userDir.substr(userDir.lastIndexOf(File.separator) + 1);
4return userName;
5}
6
7protected function list_creationCompleteHandler(event:FlexEvent):void {
8getMyUnitResult.token = Widget.getMyUnit("{currentOSUser()}");
9}
This didn't work for him. Notice the binding inside the function? That's simply not a place where you can use binding. In this case the solution was simpler code:
My understanding is that you can only use bindings in the attributes of components. However, don't take my word for it. I found a nice article at Adobe specifically on binding: Using data binding
Hope this helps!


I can see this coming in handy for internal air apps.
p.s. add me on twitter 'samhamilton'
Sam.
Now, how about one to get the Computer Name. Please....