Saturday, December 22, 2012

Create Android User Control

There are several ways for creating reusable UI components in Android.

The one described here is creating a new view made with other views (much like a usercontrol in .Net).

Creating an Android user control requires a layout and a class just like creating an activity.

The layout can be whatever you want and the relevant aspect is the layout root you choose.

In this example, the layout root is a Framelayout (but can be any other):



    

Then, you must create a class to handle the logic of your user control.

The base class must be the same class of the layout root.

In the example, the class extends FrameLayout as it is the layout root of the previous example:
package YourPackage;

public class YourUserControl extends FrameLayout {
    public YourUserControl(Context context) {
        super(context);
    }
    public YourUserControl(Context context, AttributeSet attrs) {
        super(context, attrs);

        LayoutInflater inflater = LayoutInflater.from(context);
        inflater.inflate(R.layout.yourusercontrollayoutid, this);

        //more code if needed
    }

    //more code
}
You reference your new UI component in xml just like any Android view by referencing the package and class name:
<YourPackage.YourUserControl />

Wednesday, December 19, 2012

Prevent Screen Saver In WPF Application

Sometimes we want your application to be always visible, preventing the screen saver (or monitor off) to happen.

We can achieve this by calling an API of the OS.

First we have to declare the OS API:
[DllImport("kernel32.dll")]
private static extern uint SetThreadExecutionState(uint esFlags);
private const uint ES_CONTINUOUS = 0x80000000;
private const uint ES_SYSTEM_REQUIRED = 0x00000001;
private const uint ES_DISPLAY_REQUIRED = 0x00000002;

When the application starts (or any time you want to disable the screen saver):
SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED | ES_DISPLAY_REQUIRED);

When the application ends (or any time you want to enable the screen saver):
SetThreadExecutionState(ES_CONTINUOUS);

Tuesday, December 11, 2012

Detect Windows Phone Application In Edit Mode

Sometimes we have to know when your code is running in the editor.

When authoring a control, it's common to include code that must run outside the editor, otherwise it would cause an exception in edit mode.

The following code shows how to do it:
public partial class YourControl: UserControl
{
    public YourControl()
    {
        InitializeComponent();

        if (!DesignerProperties.IsInDesignTool)
        {
            //code to run outside the editor
        }
    }
}

Detect Android Application In Edit Mode

Sometimes we have to know when your code is running in the editor.

When authoring a control, it's common to include code that must run outside the editor, otherwise it would cause an exception in edit mode.

The following code shows how to do it:
public class YourControl extends FrameLayout {
    public YourControl (Context context, AttributeSet attrs) {
        super(context, attrs);

        if (!isInEditMode()) {
            //code to run outside the editor
        }
}

Tuesday, December 4, 2012

Speed Up Android Emulator

The android emulator runs an actual ROM of a physical device.

If the device is based on the ARM architecture lots of translation must be done to run it on a x86 system.

However, we can choose an x86 ROM when available.


We don't have to, but it's a good option to use the host GPU to speed the rendering.

Don't activate this option when targeting Intel Atom x86 System Image (Intel Corporation) - API Level 10. In my case this prevents the emulator to open.


In the Android SDK Manager download the Intel x86 Emulator Accelerator (HAXM) package.


The Android SDK Manager downloads the Intel x86 Emulator Accelerator (HAXM) package but doesn't run the installation, you must do it yourself.

Failing to do so, you will get the following message when starting a virtual device:
emulator: Failed to open the HAX device!
HAX is not working and emulator runs in emulation mode
emulator: Open HAX device failed
Locate and run the file IntelHaxm.exe.

In my case it can be found at C:\Program Files (x86)\Android\android-sdk\extras\intel\Hardware_Accelerated_Execution_Manager.

Thursday, November 29, 2012

Copy Windows Phone Content To Isolated Storage

Some times a database is deployed with the application as a content file.

However, the database can't be used directly, it must be copied to the storage first.

In this sample code, the content file is copied to the isolated storage if it isn't copied yet.
IsolatedStorageFile ISF = IsolatedStorageFile.GetUserStoreForApplication();
String DBFile = "DB.sqlite";
if (!ISF.FileExists(DBFile)) CopyFromContentToStorage(ISF, "Database/DB.sqlite", DBFile);

private void CopyFromContentToStorage(IsolatedStorageFile ISF, String SourceFile, String DestinationFile)
{
    Stream Stream = Application.GetResourceStream(new Uri(SourceFile, UriKind.Relative)).Stream;
    IsolatedStorageFileStream ISFS = new IsolatedStorageFileStream(DestinationFile, System.IO.FileMode.Create, System.IO.FileAccess.Write, ISF);
    CopyStream(Stream, ISFS);
    ISFS.Flush();
    ISFS.Close();
    Stream.Close();
    ISFS.Dispose();
}
private void CopyStream(Stream Input, IsolatedStorageFileStream Output)
{
    Byte[] Buffer = new Byte[5120];
    Int32 ReadCount = Input.Read(Buffer, 0, Buffer.Length);
    while (ReadCount > 0)
    {
        Output.Write(Buffer, 0, ReadCount);
        ReadCount = Input.Read(Buffer, 0, Buffer.Length);
    }
}
The code assumes that the file to be copied is named 'DB.sqlite' that resides in a folder named 'database' and was added to the project as a content file.

Copy Android Asset To Internal Storage

Some times a database is deployed with the application as an asset.

However, the database can't be used directly, it must be copied to the storage first.

In this sample code, the asset is copied to the internal storage if it isn't copied yet.
Context Context = getApplicationContext();
String DestinationFile = Context.getFilesDir().getPath() + File.separator + "DB.sqlite";
if (!new File(DestinationFile).exists()) {
  try {
    CopyFromAssetsToStorage(Context, "Database/DB.sqlite", DestinationFile);
  } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
  }
}

private void CopyFromAssetsToStorage(Context Context, String SourceFile, String DestinationFile) throws IOException {
  InputStream IS = Context.getAssets().open(SourceFile);
  OutputStream OS = new FileOutputStream(DestinationFile);
  CopyStream(IS, OS);
  OS.flush();
  OS.close();
  IS.close();
}
private void CopyStream(InputStream Input, OutputStream Output) throws IOException {
  byte[] buffer = new byte[5120];
  int length = Input.read(buffer);
  while (length > 0) {
    Output.write(buffer, 0, length);
    length = Input.read(buffer);
  }
}
The code assumes that the file to be copied is named 'DB.sqlite' and it resides in a folder named 'database' in the assets.

Wednesday, November 28, 2012

Start Thread On Android

You can start a new thread by extending the Thread class or implementing the Runnable interface.

Extending the Thread class:
Thread T = new NewThread();
T.start();

private class NewThread extends Thread {
  @Override
  public void run() {
    //Your asynchronous code
  }
}
Implementing the Runnable interface:
Thread T = new Thread(new NewRunnable());
T.start();

private class NewRunnable implements Runnable {
  public void run() {
    //Your asynchronous code
  }
}
Your activity may implement the Runnable interface directly.
In this case, when creating the Thread object you must pass the activity (this) as the parameter.

Wednesday, November 21, 2012

Prevent Android UI Resize When Keyboard Opens

An android activity may be resized when the soft keyboard opens.

Sometimes that's not the behavior we want.

To disable the resizing, add the following line to the activity declaration on the manifest:

If the UI contains a ScrollView, then you can also add the following to the view declaration to prevent the resizing:
android:isScrollContainer="false" 

Thursday, November 8, 2012

Update Android UI From Other Threads

Asynchronous functions are useful to run code in background so the UI will not freeze.

Those functions can't access the UI directly because they aren't running in the UI thread.

If you try to access the UI from those threads you will get the error:
"Only the original thread that created a view hierarchy can touch its views."

The solutions is to use Handlers.
private Handler YOURHANDLER = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        //do some code in the UI thread
    }
};

public void ASYNCHRONOUSFUNCTION() {
    Message Msg = new Message();
    Msg.obj = "SOME TEXT"; //can be any object
    YOURHANDLER.sendMessage(Msg);
}
In the example, the ASYNCHRONOUSFUNCTION function runs in another thread.

The Message object will contain any information in it's obj property that you want to send to the handler.

Finally, you invoke the sendMessage method of the YOURHANDLER handler.

Programmatically Hide Android SIP

Some times we want to programmatically hide the virtual keyboard (SIP, soft input panel).

This is how you do it:
InputMethodManager IMM = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); 
IMM.hideSoftInputFromWindow(v.getWindowToken(), 0);
In the code, the V variable may represent any view of the activity.

Friday, October 26, 2012

Force Windows Phone Theme

Windows Phone applications inherits the theme of the OS on launch.

When the UI is designed specially for the dark theme it won't look well on the light theme, or vice versa.

To prevent this the application can force the default dark or light theme.

In the application class' constructor put this code to force the dark theme:
if ((Visibility)Application.Current.Resources["PhoneLightThemeVisibility"] == Visibility.Visible) MergeCustomColors("/Themes/DarkStyles.xaml");
Or this code to force the light theme:
if ((Visibility)Application.Current.Resources["PhoneDarkThemeVisibility"] == Visibility.Visible) MergeCustomColors("/Themes/LightStyles.xaml");
Anywhere in your project put this method:
private void MergeCustomColors(String Theme)
{
    ResourceDictionary Dictionaries = new ResourceDictionary();
    String source = String.Format(Theme);
    var themeStyles = new ResourceDictionary { Source = new Uri(source, UriKind.Relative) };
    Dictionaries.MergedDictionaries.Add(themeStyles);
    ResourceDictionary appResources = Current.Resources;
    foreach (DictionaryEntry entry in Dictionaries.MergedDictionaries[0])
    {
        SolidColorBrush ColorBrush = entry.Value as SolidColorBrush;
        SolidColorBrush ExistingBrush = appResources[entry.Key] as SolidColorBrush;
        if (ExistingBrush != null && ColorBrush != null) { ExistingBrush.Color = ColorBrush.Color; }
    }
}
The code assumes that the projects contains the files DarkStyles.xaml and LightStyles.xaml in a folder named Themes.

A demo project can be found here.

Get Windows Phone Accent Color

Some times an application needs to know which accent color is currently in use on the device so it can adjust it's UI.

The PhoneAccentColor key indicates the accent color as a Color object.
The PhoneAccentBrush key indicates the accent color as a Brush object.

In XAML you can do something like:
<TextBlock Foreground="{StaticResource PhoneAccentBrush}" />
<Border>
  <Border.Background>
    <SolidColorBrush Color="{StaticResource PhoneAccentColor}" />
  </Border.Background>
</Border>
In C#:
Color AccentColor = (Color)Resources["PhoneAccentColor"];
Brush AccentBrush = (Brush)Resources["PhoneAccentBrush"];

Detect Windows Phone Theme

Some times an application needs to know which theme is currently in use on the device so it can adjust it's UI.

The PhoneLightThemeVisibility key indicates the visibility of the light theme.
The PhoneDarkThemeVisibility key indicates the visibility of the dark theme.

In XAML you can do something like:
<TextBlock Visibility="{StaticResource PhoneLightThemeVisibility}" />
<TextBlock Visibility="{StaticResource PhoneDarkThemeVisibility}" />
You can use a converter to manipulate other properties that are not of type Visibility.

In C#:
Visibility LightThemeVisibility = (Visibility)Resources["PhoneLightThemeVisibility"];
Visibility DarkThemeVisibility = (Visibility)Resources["PhoneDarkThemeVisibility"];

Thursday, October 25, 2012

Windows Phone Flip Animation

You can use the Projection class to produce the flip animation of a control.

The following XAML ilustrates this:
<UserControl.Resources>
    <Storyboard x:FieldModifier="private" x:Name="SBStartAnimation">
        <DoubleAnimation Storyboard.TargetName="SPPanel" Storyboard.TargetProperty="(UIElement.Projection).(PlaneProjection.RotationX)" From="-90" To="0" Duration="0:0:0.150" />
    </Storyboard>
</UserControl.Resources>

<Border x:FieldModifier="private" x:Name="BShade" Background="#aa000000">
    <StackPanel x:FieldModifier="private" x:Name="SPPanel" VerticalAlignment="Top" Background="#222222">
        <StackPanel.Projection> 
            <PlaneProjection CenterOfRotationY="0.5" RotationX="0" /> 
         </StackPanel.Projection> 
        <Image Source="/Background.png" HorizontalAlignment="Center" Stretch="None" />
        <LC:ProgressLine x:FieldModifier="private" x:Name="PLProgress" Margin="0,-5,0,10" /> 
        <TextBlock Text="Working, please wait..." HorizontalAlignment="Center" Margin="0,0,0,20" /> 
    </StackPanel>
</Border> 
The SPPanel Stackpanel is flipped as defined in the SBStartAnimation Storyboard.

Windows Phone Backgound Color Animation

In Silverlight for Windows Phone you can't animate a Brush so you can't animate the Background of a control.

However, you can use the ColorAnimation class to animate the color of a Brush.

The following XAML shows an example:
<UserControl.Resources>
    <Storyboard x:FieldModifier="private" x:Name="SBStartAnimation"> 
        <ColorAnimation Storyboard.TargetName="BShade" Storyboard.TargetProperty="(Border.Background).(SolidColorBrush.Color)" From="#00000000" To="#aa000000" Duration="0:0:0.150" /> 
    </Storyboard> 
</UserControl.Resources>

<Border x:FieldModifier="private" x:Name="BShade" Background="#aa000000" /> 
The BShade object must have it's Background property initialized.

Windows Phone Margin Animation

In Silverlight for Windows Phone the ThicknessAnimation class isn't available.

You have two solutions:
  • Place a transparent object on the left/top and animate it's Width/Height properties;
  • Place the object you want to animate in a Canvas and animate the object Left/Top properties.
If you choose the second options, the XAML can look like this:
<UserControl.Resources>
    <Storyboard x:FieldModifier="private" x:Name="SBUndeterminedAnimation">
        <DoubleAnimation x:FieldModifier="private" x:Name="DAUndeterminedAnimation" AutoReverse="True" RepeatBehavior="Forever" Duration="0:0:2.000" From="0" Storyboard.TargetName="BProgress" Storyboard.TargetProperty="(Canvas.Left)" />
    </Storyboard>
</UserControl.Resources>

<Grid>
    <Canvas x:FieldModifier="private" x:Name="CTrack" Background="#19ff0000" Height="5" HorizontalAlignment="Stretch">
        <Border x:FieldModifier="private" x:Name="BProgress" Background="#ffff0000" Height="5" Width="50" />
    </Canvas>
</Grid>
This XAML is actually a custom ProgressBar that has both determined and undetermined behavior.

The To property of the DAUndeterminedAnimation DoubleAnimation is set in code-behind.

Sunday, October 21, 2012

Cross-Platform Native Code Generator

When creating an application for different platforms, you can create an HTML application that will fit every deployment or create a native application for each platform you want to traget.

Creating an HTML application sure means less work, since the code (HTML+JavaScript+CSS) is fairly supported across web browsers.

Of course, the User Interface (UI) will not match every system where the application will be deployed.

Developing the application nativelly will allow the UI to be fully integrated with the OS.

But a native application means a software project for each platform and this can be unmanageable.

There are several solutions to this problem that minimize the coding of logic that is common to all of those software projects (business logic).

One of them is AppDevPoint.

This tool centralizes the business logic so that it's coded only once in one place.

There must be native project for each platform since the UI is created natively this way being truly integrated with the OS.

This methodology completely separates the UI from code.

If the business logic has to be changed, simply code it in the AppDevPoint, regenerate the builds and all of your native projects will be updated in a single action.

The binaries produced by the native compiler runs directly on the OS as this framework doesn't requires VMs or additional run-times to be installed.

This tool is free and open-source.

For more details, please visit:
http://appdevpoint.webs.com
http://appdevpoint.codeplex.com/

Saturday, October 20, 2012

Windows Phone Stateful Framework

For an windows phone application to pass the Microsoft certification, it must implement the tombstone state.

In concept this is easy to achieve, but in practice we must be careful.

This framework wraps the OnNavigatedTo and OnNavigatedFrom events of the page, exposing a set of methods one can override.

There are two types of methods: navigation methods and state manipulation methods.

The navigation methods allows the page to react to navigation events for initialization, clean-up, etc.

The state manipulation methods is where the code to persist and restore the state must be implemented.

A special state manipulation method is available for restoring the global state of the application.

The state can be immutable if it doesn’t change throughout the page life-cycle, or changeable if otherwise.

A page can be marked as transient this way optimizing the state manipulation methods.

For source code, please visit http://wpstatefulframework.codeplex.com/