Archive for April, 2013

Many people frequently ask me what the steps to put your android environment quickly running, it looks like the documentation isn’t clear enough and the books don’t go to the detail we need to quickly start developing. Since today someone had start building an enviroment and ask me for help online, for some moments i remember the kick in the ass that was to do this the first time i need this, so i decided to share a step by step tutorial about how to start your engines in android development

https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ811ym0tjkzWeJ8Bmh8eZCkizNr-vDf2x2_-Pehg1k_foqJngM

Get the Java Development Kit

First thing you need to get is the Java Development Kit.  This is available on the Sun Microsystems website.  You are going to be looking for Java Standard Edition JDK 5 or 6 and on the site you will be able to find installation info for your particular OS.  Click this link to get the Java Development Kit.  You will probably see two options for the standard edition: “JDK” & “JRE”.  Ultimately, you need both but you may already have the Java Runtime (JRE) on your machine as this is what is used to run Java code for applets and such.  Just try to install them both.

Once you click on either the “JDK” or “JRE” button, you will be prompted to accept the Terms of Use and then a list of links are made available for downloading of installer files (executables).  Find the one appropriate for your OS, download and then run it.

Get the Eclipse IDE

Your actual code for your Android application can be written in the free Eclipse IDE.  Download Eclipse for Java EE Developers here.

Note that Eclipse does not come with an installer.  You will be downloading a zip folder which will need to be unzipped and placed into your preferred directory.  There will be a readme file in the zip folder for your particular OS.  For my particular Windows installation, I just placed the “eclipse” root folder contained in the zip I downloaded on my C drive (C:\eclipse) and then opened the folder and right-clicked on the eclipse application file to send a shortcut to my desktop so I could launch eclipse from there.

Install the Android SDK

The Android software development kit is available for free download here.  This SDK includes Android application framework classes, documentation, tools, etc.  You have the option of downloading a zip file or an installer (exe file).  I recommend the installer, it’s much easier.  Just download it, double-click it and then follow the wizard.

NOTE: If you are running the SDK on a Windows machine then you have one more step before the SDK is ready to go.  You need to update the PATH variable in your Windows system variables.  Here are the steps (may vary slightly from version to version of Windows):

1- Right-click on “Computer” and then click “Properties”.

2- Click “Advanced System Settings” and then select the “Advanced” tab.

3- Click the “Environment Variables” button.

4- In the “System Variables” section, look for a variable named “Path” and double-click it.

5- In the “Variable Value” textbox, go to the end of the string and add a semicolon followed by the path to your Android tools folder (example: “C:\Program Files (x86)\Android\android-sdk-windows\tools”).

6- Click “OK” three times to exit all of the Windows system dialogs.

Install and configure the Android Plug-in for Eclipse

The Android plug-in for Elcipse integrates the Android tools into the Eclipse IDE seamlessly.  In order to install this plug-in, you are going to have to run an Eclipse update.  The steps to do this will vary depending on the version of Eclipse that you have so if you get lost, visit the this page on the Android Developer website.  Here are the steps you need to follow for Eclipse version 3.5 (Galileo):

1- Launch Eclipse.  NOTE: The first time you launch Eclipse, you will get a dialog asking for the location of your default workspace (example: “C:\Users\Matt Cashatt\workspace”).  This is where all of your Android projects will be stored.  So just set the location that you want, check the box by “Set this location as default. . .” and click “OK”.

2- Go to “Help” in the toolbar and then select “Install New Software”.

3- You will probably already be in a screen titled “Available Software”, but if not, select the “Available Software”.  Now click the “Add” button.

4- Add the remote site “https://dl-ssl.google.com/android/eclipse/”.  If this site fails, then just drop the “s” from http and try again.  You can name the site whatever you want.  I named mine “AndroidSDK”.

5- If everything went ok, Eclipse should have found “Developer Tools” on the remote site and listed it for you with a checkbox.  Check the “Developer Tools” and “NDK plugin”box.

6- Click “Next” and then follow the instructions for installing the tools.  At the end, accept the license and terms and then click “Finish”.

7- After the software update is complete, re-start Eclipse for the changes to take effect.

Update Eclipse Preferences to point to the Android SDK

Phew!  Almost done.  The last step is to point the Eclipse IDE to the Android SDK:

1- Launch Eclipse.

2- Click “Window” , then “Preferences”.

3- Select “Android” in the tree on your left and you will then see “Android Preferences” on your right.  Now point to the file path of your Android SDK Installation (example: “C:\Program Files (x86)\Android\android-sdk-windows”).  If you now see a bunch of target SDK versions listed, then you did everything correctly and Eclipse has found the SDK.  If this is not the case, then check your file path.

Foot note:

If you need a quick start to the platform you can use my slides deck avaible on slideshare

credits of this post go to Matt Cashatt who had help me start in the past

Async calls and the .NET 4.5

Posted: April 1, 2013 in .NET, Multi Thread

Multi Processing and multi thread is always a challenge for any developer. The .Net Framework offers a very rich multithreading and parallel programming model, in the new framework we have an easy way to use multi processing, in this post we will take a look on the way we can use the new .net keywords and we will remember some of the basics about multi threading in the .Net platform.

In the analysis of this topic we will use C# as our language,

Remember the basics

thread

We can define a Thread as a execution path within an application. Under the .NET framework there is not a correspondence between an application and domain Threads, a appDomain can have different execution paths running at the same time. A Thread is not confined to a single appDomain, they are free to cross application boundaries, but a thread can execute in only a appdomain in each moment.

“the CLR is the entity that is in charge of moving threads into (and out of) application domains and contexts. As a .NET developer, you can usually remain blissfully unaware where a given thread ends up (or exactly when it is placed into its new boundary). Nevertheless, you should be aware of the various ways of obtaining the underlying primitives.” (Andrew Troelsen).

Like we had said before .NET framework offer’s a rich api for parallel and multi Threading program, you can use Delegates as a way to have different execution paths in concurrency or the Thread object you also have parallel programming, but one off the things a lot of developer’s say is that the objects .NET offer’s are not easy to use, for that reason in .NET 4.5 the API offer us a new way to deal with async calls.

async and await

The async keyword qualify a call as asynchronous (this is valid for methods, lambda expressions, anonymous methods), the use of this keyword pass the message that the call will be automatically async. In the backstage what happens when you call a  method that was tagged with the async keyword, the CLR will create a new thread of execution to handle the task at hand.

example:

Class Test{

public async void asyncMethod(){  …… }

}

It should be very clear in your mind that when you call a method that was declared as a async method is that your call will be called in a asynchronous manner. If you wish to stay blocked in the call of a method that was declared as async you should use other helper C# keyword named await.

Based in what we had seen a call to our method without need to block would be something like this (consider obj as an instance of Test)

obj.asyncMethod();

If we intend to wait for the method processing we should do something like:

await obj.asyncMethod();

Right now maybe you are thinking that this keywords helps you to do more clean code, but how to use this anti pattern to execute asynchronous result dependent tasks (this is fair away the most interesting thing of the use f this keywords). Let´s reconsider our Test class and a asyncMethod2 that returns a task

Class Test{

public async Task asyncMethod2(){  …… }

}

A Task is an object that represents a paralell action (http://msdn.microsoft.com/en-us/library/system.threading.tasks.task.aspx).

“The Task parallelism refers to one or more independent tasks running concurrently. A task represents an asynchronous operation, and in some ways it resembles the creation of a new thread or ThreadPool work item, but at a higher level of abstraction. Tasks provide two primary benefits:

  • More efficient and more scalable use of system resources.Behind the scenes, tasks are queued to the ThreadPool, which has been enhanced with algorithms (like hill-climbing) that determine and adjust to the number of threads that maximizes throughput. This makes tasks relatively lightweight, and you can create many of them to enable fine-grained parallelism. To complement this, widely-known work-stealing algorithms are employed to provide load-balancing.
  • More programmatic control than is possible with a thread or work item.Tasks and the framework built around them provide a rich set of APIs that support waiting, cancellation, continuations, robust exception handling, detailed status, custom scheduling, and more.

One example of a call to wait 2000 ms after the return of the asynchronous method

await obj.asyncMethod2.Run(() => { Thread.Sleep(2000); });

Other most sophisticated example:

public class Worker
{
    public async void DoWorkAsync(Action action)
    {
        Console.WriteLine("  Before DoWorkAsync");
        await Task.Factory.StartNew(action.Invoke);
        Console.WriteLine("  After DoWorkAsync");
    }
}

(...)
//Step 1
        Console.WriteLine("Init");
        var sl = new SpinWait();
        int max = 100000;
        Worker w = new Worker();

        //Step 2
        Console.WriteLine("Start worker");
        w.DoWorkAsync(() =>
            {
                Console.WriteLine("  Before actual work");
                for (int i = 0; i < max; i++)
                {
                    sl.SpinOnce();
                }
                Console.WriteLine("  After actual work");
            });

        //Step 3
        Console.WriteLine("Returned to main");
        Console.WriteLine("Block");

(...)

as a result we will see in the console the output

Init
Start worker
  Before DoWorkAsync
Returned to main
Block
  Before actual work
  After actual work
  After DoWorkAsync

I hope this post had help you to understand where async and await feet in, and what the opportunities this keywords bring. One off the great values of this 2 keywords is the simplicity to do asynchronous calls.

If you have any question feel free to ask.

Foot Note

to know event better the async keyword we recommend you to go to the MSDN article http://msdn.microsoft.com/en-us/library/vstudio/hh191443.aspx