Monday, January 7, 2013

Detect (And Cancel) Windows Phone Back Key

To detect when the user presses the back key, you just have to override the OnBackKeyPress function.

Just like this:
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
    // to cancel the event
    e.Cancel = true;
}
You can optionally cancel the navigation or allow it to occur.

You cancel the navigation by calling the instruction on line four.

Obviously you can code any logic to conditionally cancel the navigation.

Another use is to catch the event just to persist any information and then letting the navigation occur.

Detect (And Cancel) Android Back Key

To detect when the user presses the back key, you just have to override the onBackPressed function.

Just like this:
@Override
public void onBackPressed() {
    super.onBackPressed();
}
You can optionally cancel the navigation or allow it to occur.

You cancel the navigation by not calling the instruction on like two.

Obviously you can code any logic to conditionally cancel the navigation.

Another use is to catch the event just to persist any information and then letting the navigation occur.

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.