Share via


Introducing Windows 8 for Android Developers–Part 1

Introduction

This two-part series (Part 1 & Part 2) is aimed at the Android developers who are looking for opportunities to build Windows Store applications. In order for the easy onboarding of an Android developer to the Windows 8 platform, we will take a fundamental approach towards outlining the mobile development tasks and show how to accomplish them on Windows 8. The tasks include the setting up of the development environment, UI design, handling widget events, local storage, integration with external systems and device notifications. Given the similarities between the two platforms in the mobile space, Android developers will feel right at home with application development for Windows Store.

Please note that the intention of this article is not to show that one is superior to the other but to simply outline how a developer can mentally map the development tasks from one platform to the other. You may see Windows 8 being treated at a more detail level as I know Windows 8 a little better than Android and any bias you may see is unintentional.

Most of the Windows 8 discussion in this series focuses on XAML and C# programming model. However, this is one of the many programming models supported in Windows 8; others include HTML5/Javascript, VB.NET, C++ and DirectX.

The Platform

Windows 8 is available on various device types including desktops, tablets, and yet to be built devices of various form factors; however, our focus for this article is Windows 8 in the context of tablets. With very little effort Android developers can be at home with Windows 8 as it has a lot of similarities with Android from the OS architecture, mobile development concepts, developer tools and SDKs perspective. Figure 1 shows both platforms side-by-side illustrating components that are important to developers.

Android: Kernel

Android is built on top of the Linux kernel that is adapted for mobile devices; the changes to the kernel include efficient power management, increase in security, support new hardware, improve performance of the flash file system, and improved error reporting. User programs on Android are hosted inside Java virtual machine at run time and consequently the developers can take advantage of the subset of Java APIs fundamental to JDK. Android also provides Java binding under android namespace for platform specific programming like power management, user interface, location based programming, local storage and cloud integration.

Windows 8: Kernel

Enhancements to the Windows 8 kernel are too numerous to mention however, here are a few: enhance boot performance, enable System-on-Chip features, improve run-time power management of the devices, performance enhancements to user mode driver framework, and security enhancements to user mode driver framework.

Most developers probably don’t care about the finer details of the driver architecture however, it is worth to note that, Windows 8 supports a driver architecture that allows user mode as well as kernel mode drivers. User mode drivers (e.g. camera, printer) run in a low privileged environment (in user mode) which prevents system crashes resulting from driver quality issues. Note that the diagram shows all the Windows 8 drivers running in kernel-mode just for the sake of showing the symmetry between Android and Windows 8. 

fig1- architecture

Figure 1: Architecture Side-by-side

 

Android: Runtime

Typical applications created by developers for Android run inside a Dalvik VM instance which is a register based Java Virtual Machine that is optimized for low memory and devices with mobile friendly processors. Java class files gets converted into Dalvik Executable files which are known as DEX files. These DEX files are interpreted excepting cases where the runtime can JIT compile a hot trace. A subset of the Java libraries are distributed as a part of the Android SDK. Natively coded Android libraries are available to the Java programming environment as language specific bindings. These Android API calls from Java will be dispatched to native code through JNI which is totally opaque to the developers.

Windows 8: Runtime

Android Runtime equivalent in Windows 8 is WinRT which is a sand box for running Windows Store applications. Windows 8 supports two types of applications – desktop applications and Windows Store applications. Windows Store applications run inside a security sand box which tightly controls access to system resources while the traditional desktop applications run with privileges implicitly inherited from the user principal that started the application. In case of desktop applications, the code is completely trusted and hence no discretionary permission grants required by the end user unless the code originated from a mobile location like an external share or internet.

WinRT makes no such assumptions about Windows Store applications; permissions for accessing system resources (e.g. network, file system, location) will have to be explicitly requested by the application at development time. At run time when the protected resource is accessed end user grants permission through consent dialogs. Another difference is that desktop applications can be installed from any source while Windows Store applications targeting WinRT can only be installed from trusted sources like Windows Store or an on premise repository in a controlled setting.

For this discussion we will only be focusing on Windows Store applications (aka Windows Store apps) as these are the equivalent of Android applications. Windows Store applications are published into Windows Store which is analogous to Google Play and other Android stores into which developers must submit their applications for the certification and subsequent publication.

Windows 8’s equivalent of Android’s Dalivik VM is .NET CLR; each process in Windows Store application creates an instance of .NET CLR (Common Language Runtime) for running application code written in .NET languages like C# and VB.net. .NET code gets deployed as MSIL (Microsoft Intermediate Language) byte code that gets JIT compiled into X86 or ARM instruction set at run time. This is similar to compiling Java source code to DEX files and the interpretation of DEX files at run time in Android.

WinRT allows only a subset of .NET to be used inside Windows Store applications written with .NET languages. This includes IO, LINQ collections, networking, http, object serialization, threading, WCF (Windows Communications Foundation) and XML. Complete list of .NET APIs for Windows Store applications can be found at: .NET for Windows Store apps - supported APIs.

Windows Store applications written using HTML/Javascript and C++ will directly call into WinRT API for implementing application functionality. WinRT API is a collection of COM components that sit on top of Windows Core; these components are made available to various languages including C#, VB.NET, C++ and Javascript through language specific projections. The projections are metadata files which will be used by Visual Studio IDE and the language compiler to replace language specific API calls with native WinRT API calls.

Libraries

WinRT API is a collection of native components implemented in COM (Component Object Model) that is familiar to most of the Windows programmers. For Android developers who are new to Windows platform, COM is an RPC based technology that creates and manages object life cycle through class factories and reference counting. The developers are shielded from the complexity of the COM part of the WinRT APIs through language projections.

Similar to Android, WinRT has libraries for media playback, networking, storage, geo location and other important components for developing mobile applications. Some of the libraries shown for Android like SGL, libc and SSL have their counterparts in Windows 8 through XAML rendering engine, C runtime and SSL implementation. Even though SQLite is not distributed as part of the WinRT, there are WinRT compatible open source libraries that allows developers to embed server-less relational database functionality inside Windows 8 Windows Store applications.

Equivalent to WebKit on Android, HTML rendering is done through IE10’s Trident which helps HTML rendering on Windows 8. Both the platforms have similarly named class– WebView for embedding web sites within applications.

Development Environment

Eclipse with Android plug-in, Net Beans and IntelliJ are a few development environments that support Android application development. These tools support multiple operating systems that include Windows, Mac and various flavors of Linux. Windows 8 development requires Windows 8 operating system and Visual Studio 2012 Express for Windows 8 at the minimum. Visual Studio 2012 comes with its own drag and drop UI designer similar to Android designer on Eclipse. Visual Studio 2012 also comes bundled with Blend for Visual Studio 2012 which is a designer-centric tool that allows the creation of rich user experiences through drag and drop of widgets, animations and transitions.

Usually Android development is done in Java (in exceptional cases with C/C++) while Windows 8 supports C++, C#, VB.NET and Javascript. Declarative screen design in Android is captured into XML file which gets injected into the corresponding Activity code at run time. Similarly, declarative screen designs in Windows 8 is captured into XML which has a special designation called XAML which stands for eXtensible Application Markup Language. XAML is a declarative object composition language with each XML node representing the corresponding object from the WinRT API. Windows 8 uses the same XAML format with C#, VB.NET and C++ while Javascript uses HTML/CSS as its declarative screen design language. DirectX programming in C++ doesn’t use any declarative UI.

fig2 - Development Environment

Figure 2: Development Environment

Since Windows 8 OS is a pre-requisite for Windows Store application development, those developers who use Windows 7, Linux or Mac as their main OS, needs to either use virtualization technologies (e.g. VirtualBox, VMWare, or Parallels) to run Windows 8 as a VM or install Windows 8 in a dual boot setting.

Figure3 - publication process

Figure 3: App Publication Process

 

Figure 3 shows the sequence of activities that calumniates with the submission of the application in both Android and Windows 8 platforms. Dev.windows.com is the flagship site for all the Windows 8 design and developer resources which includes tools and SDK download, create your first application, API documentation, and lot of samples both from Microsoft as well from the developer community.

One difference between Android development and Windows 8 development is that Windows Store application requires a developer license which is free of cost. The license is downloaded into Visual Studio 2012 during the first use of the IDE and subsequently whenever it expires which is every 30 days. Once a developer registers for Windows Store Account, the license gets renewed every 90 days. The license acquisition process requires the user to log into dev.windows.com using Microsoft Account.

Windows Store registration is not needed during the app development but required at the time of publishing the app to the store. The exception being the usage of push notifications which requires Windows Store account during development. Windows Store requires an annual subscription that costs $49 for individuals and $99 for company accounts. Compared to this, Google Play registration only costs $25. The Windows Store registration is free to MSDN subscribers who already have software download rights from msdn.microsoft.com.

See Getting Started on dev.windows.com for setting up of the development environment and building your first Windows Store application.

User Interface Concepts

UI Design and Development has a lot of parallels between Android and Windows 8 store applications. Activity is the unit of display on Android which is analogous to the Page in Windows 8. An Android Activity composes the UI from the deeply nested group of widgets after applying the layout specification. View is the root class for all the widgets (e.g. EditText, Button, CheckBox) while ViewGroup is the base class for the invisible layout controls (e.g. LinearLayout, GridLayout) in Android. View is the root class of the ViewGroup as well. Windows 8 slightly differs here as Control is the base class for all the widgets (e.g. TextBox, Button, CheckBox) while Panel is the base class for the invisible layout controls (e.g. StackPanel, GridLayout). At run time the content contained inside a Page object is attached to the Windows object before it can display and be ready for receiving event streams.

 

Figure4 - UI Elements

Figure 4: UI Elements

Here are a few attributes of Android and Windows Store applications in the context of the unit of display:

Android

Windows 8

An application is a collection of Activities

An application is a collection of Pages

Activity is the unit of display as seen by the end user

Page is the unit of display as seen by the end user

Each Activity is designed to perform a function (e.g. send mail, take a photo, pick a contact)

Each Page is designed for the end user to interact with the application

Activity is composed of a collection of layout controls and widgets (e.g. Button, EditText, CheckBox)

Page is composed of a collection of layout controls and widgets (e.g. Button, TextBox, CheckBox)

Only one Activity can be seen by the end user at a time

Only one Page can be seen by the end user at a time

Activities are stacked on a LIFO back stack in the context of a Task as they come to life. Back button or completion of an Activity will pop the activity destroying it in the process. Application specific tasks can constructed if the semantics of navigation has to be contained within the application.

Pages are placed on a navigation stack within a given application. There is no concept of a system wide navigation stack. Information sharing between applications is through contracts. Invocation of a contract (e.g. Search) displays the target app and upon completion of the processing in the target app the control will revert to the application that initiated the contract message. Within an application, users can navigate between pages through “back” button semantics

Unit of display in both the platforms use a connected pair of a declarative component for UI and an imperative component for event handling and processing logic. For each Android Activity, the declarative part of the UI is captured into the XML layout file while the imperative component is coded into the corresponding Java file.

For each Page in Windows 8 development, the declarative component is captured into the XML file with an extension .XAML while the imperative component is coded into the corresponding C# (or VB.NET, C++) code-behind file. Exception being the Javascript based Windows Store application where the declarative UI is captured into a HTML file while the imperative component is coded into the corresponding Javascrtipt file. Both the platforms combine the declarative and imperative components during the early phases of compilation before producing java or .NET class libraries.

In Android the event handling is done through the observer interfaces while Windows Store applications use .NET delegates which are analogous to C function pointers but only simpler to program. Both Android and Windows 8 development hides the complexity of binding the handler logic to the widget events by allowing the specification the handler name declaratively in the XML file.

Both the platforms allow the development of composite UI parts that can be reused across multiple units of display. Android developers typically build Compound Components and Fragments while Windows 8 developers build UserControls which have Control as the parent class in its inheritance hierarchy. The Windows control concept is rooted in the traditional Windows development paradigm and is very popular with control vendors for extending the Windows 8 development platform.

UI Navigation

In Android, the developers display activities and navigate between the activities contained within the same application or across multiple applications. As the end user navigates from one activity to the other, the activities are placed on a stack that can be unwound from a soft or hard “back” button typically located in the bottom task bar or through the in-app completion of the activity. Once an activity finishes its work, the activity is removed from the stack and the activity below the completed activity will come to the foreground. Android uses an explicit Intent to invoke activities within the same application while an implicit Intent helps with the invocation of activities located in a different application or system activities.

Intra app navigation in Windows 8 is similar to the explicit Intent mechanism in Android. In Windows 8, developers display pages and navigate between pages within the same application with the help of the application specific navigation stack. There is no system level page stack in Windows 8 and no system level “back” button to unwind the screen stack.

figure5 - Screen Navigation

Figure 5: Screen Navigation

 

Figure 5 shows typical navigation schematic for an application workflow that progressively navigates through two activities in App1 and a third activity in App2 and comes back to App1’s activity 1 through activity 2. In Android, intra application activity navigation is through explicit intents as shown below:

 

//Android: Java – display second activity

public class Activity1 extends: Activity {

  //code left for brevity

  void startActivity2() {

  Intent activity2 = new Intent(this, Activity2.class);

  startActivity(activity2);

  }

}

When the above code is executed Android stops Activity1 and displays Activity2 after automatically adding Activity2 to the back stack. The state of the UI including the context in the screen fields is preserved but it is not in the foreground anymore and Activity is stopped.

Similarly in Windows 8, intra application navigation in XAML is enabled by Page.Frame property which is set when the Frame loads the Page before rendering it for display. Frame.Navigate() method activates a new Page and adds it to the navigation stack. The Frame object also supports both GoBack() and GoForward() methods for navigating the page stack relatively. The default behavior of Frame.Navigate() is to create a brand new instance every time. However, this behavior can be overridden by caching pages through the setting of Page.NavigationCacheMode to “enabled”. The following code shows the activation of Page2 from inside Page1.

//Windows 8: C# - display Page2

public partial class Page1: Page

{

   //code left for brevity

   void StartPage2()

   {

       this.Frame.Navigate(typeof(Page2));

   }

}

 

In Android, inter application navigation is achieved through explicit Intents which will be broadcast by the operating system to all the applications that can respond to the received intent type.

In Windows 8, inter application information sharing is done through contracts and extensions. A contract is meant for a well-defined interaction between two or more applications while an extension is meant to extend the operating system features through a well-defined agreement. The contract is conceptually similar to the explicit Intent in the Android platform. Examples of Windows 8 contracts include FileOpenPicker, Search and Share. The extensions include Camera Settings (allows to definition of custom user interface when a manufacturer’s camera is connected), AutoPlay (the system displays all the applications that declare AutoPlay as a supported extension) and Print task settings (the application can display printer settings specific to a particular make and model when the printer is connected).

Similar to Android intent filters, the contacts and extensions are specified in the Package.appxmanifest file of the Visual Studio 2012 project. When the “Share” charm is touched or sharing is invoked programmatically, the system will list all the applications that declared themselves as “Share Target” in their respective application manifests. The end user will pick the right application before proceeding further. Windows 8 application declares its intention to share by implementing the DataTransferManager.DataRequested handler which will be inspected by the system when a share charm is invoked. This handler is responsible for packaging the data that will be delivered to the share target by the system.

App1 shown in Figure 5, implemented DataRequested handler that will package the data and send it to App2 which declared itself as a “Share Target” in the manifest. The following code snippet shows DataTransferManager.DataRequested event handler implemented in App1:

//App1.Page2: shares text with other apps

public sealed partial class Page2 : Page

{

  public Page2()

  {

  this.InitializeComponent();

   RegisterForSharing();

  }

  private void RegisterForSharing()

  {

   DataTransferManager dataTransferManager = DataTransferManager.GetForCurrentView();

      dataTransferManager.DataRequested += new TypedEventHandler<DataTransferManager,

                                         DataRequestedEventArgs>(this.DataRequested);

  }

 

  private void DataRequested(DataTransferManager sender, DataRequestedEventArgs e)

  {

   DataRequest request = e.Request;

   request.Data.Properties.Title = "Sharing text from App1";

  request.Data.Properties.Description = "Demo of Sharing contract";

  request.Data.SetText(textBox.Text);

  }

}

When App2 is selected by the user from the list of share targets displayed, the system invokes OnShareTargetActivated method of the Application class. Each Windows 8 application creates “App” as a child class of the Application for bootstrapping the application and displaying the first page. Share target application will override and provide custom implementation for Application.OnShareTargetActivated method that is responsible for extracting the data and passing control to the application Page. In the code snippet below, App2 is activating Page3 after extracting the shared data received from App1:

//App2: App class overrides OnShareTargetActivated to display the sharing page

 

sealed partial class App2 : Application

{

  //code omitted for brevity

  protected override void OnShareTargetActivated(ShareTargetActivatedEventArgs args)

  {

    Page3 shareTargetPage = new Page3();

    shareTargetPage.Activate(args);

  }

}

 

//App2.Page3 receives shared text

public sealed partial class Page3 : Page

{

  ShareOperation _shareOperation;

  string _data;

 

  public Page3()

  {

    this.InitializeComponent();

  }

  public async void Activate(ShareTargetActivatedEventArgs args)

  {

    this._shareOperation = args.ShareOperation;

    this._data = await this._shareOperation.Data.GetTextAsync();

    Window.Current.Content = this;

    Window.Current.Activate();

    await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>

    {

      this.tbShareResult.Text = this._data;

    });

   }

}

Once App2 is done with the processing of the shared data, it can easily dismiss Page3 by calling this._shareOperation.ReportCompleted() method in a button handler or any appropriate widget handler returning control back to Page2 of App1. As shown Figure 5, once Page2 completes its work it may dismiss itself to give control back to Page1.

Widget/Control Map

Both Android and Windows 8 platforms support similar widgets in the programming model. The widgets include the functionality for text layout and display, text editing, lists, image display, radio buttons and checkboxes. The widgets also include non-visual elements for content layout in a vertical and horizontal stacks, grids and other custom layout controls. Figure 6 shows a subset of the widget list from both the platforms:

Figure 6 - Widget Map

Figure 6: Widget Map

 

Event Handling

Event handlers bind the declarative and the imperative parts of the application together into a functioning application. Both Android and Windows 8 programming models support event handlers in the similar way with minor differences in how the handlers access the widget state. Android projects in Eclipse allows the specification of handlers within the XML UI mark up as shown below:

 

<!-- activity_main.xml - XML layout with only important attributes --!>

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"

    tools:context=".MainActivity" >

   <TextView android:id="@+id/textView1" android:text="@string/hello_world" />

   <Button android:id="@+id/btnClickMe" android:onClick="btnClickMe_OnClick"/>

</RelativeLayout>

State changes of the widgets can be accomplished inside the Java code by explicitly acquiring references to the widgets by invoking Activity.findViewById() method as shown in the code below:

 

//MainActivity.java - event handling in Android

public class MainActivity extends Activity {

 private TextView txtView;

 private Button btnClickMe;

 public void btnClickMe_onClick(View v) {

    txtView.setText(“The button was clicked!");

};

@Override

 protected void onCreate(Bundle savedInstanceState) {

   super.onCreate(savedInstanceState);

   setContentView(R.layout.activity_main);

//acquire explicit references to widgets

   btnClickMe = (Button)findViewById(R.id.btnClickMe);

   txtView =(TextView)v.findViewById(R.id.txtView1);

}

 //code not relevant to event handling is removed for brevity

}

 

Visual Studio 2012 automatically generates references to the named widgets in to the code-behind files so that the event handlers and processing logic can directly reference the widgets in the format of this.<widget_name> (e.g. this.btnClickMe) as shown in the following code:

<!-- MainPage.xaml without all the attributes --!>

<Page x:Class="ShareFrom.MainPage"

    xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:local="using:ShareFrom">

 

    <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">

        <TextBox x:Name="tbShare" Text="Sharing Text" />

        <Button x:Name="btShare" Content="Share Now" Click="btnClickMe_Click"/>

    </Grid>

</Page>

 

//MainPage.xaml.cs – with only event handler shown

public sealed partial class MainPage : Page {

   private void btnClickMe_Click(object sender, RoutedEventArgs e){

      textBlock.Text = "The button was clicked!";

   }

   //code not relevant to event handling is removed for brevity

}

 

Screen Layout

Similar to Android screen designer in Eclipse, Visual Studio 2012 has a built-in screen designer that allows the layout of widgets in various patterns through the usage of appropriate layout panels based on the application’s display needs. For advanced screen designs that require timeline based animations, screen transitions and complex color schemes and shapes, designers and developers can use Blend for Visual Studio 2012.

Blend and Visual Studio share the same project format and as a result any changes to the project files will reflect in both the tools. Blend offers the designer centric experiences while the Visual Studio screen designer offers a developer centric experiences. As mentioned previously, Blend tool is included in the Visual Studio 2102 bits and gets installed automatically on the developer machine.

Figure 8 shows Android XML text for the screen shown in Figure 7 and similar screen design XAML for Windows 8 is shown in Figure 9. As one can see, the semantics of the mark up is more or less same with nuances which are listed here:

  • Android Activity Java code has a dependency on the XML content while in Windows, the mark up file has a dependency on the imperative component coded in either C#, Javascript, VB.NET or C++.
  • Each widget in Android development is identified by a unique integer which is used in acquiring reference to the widget in the imperative code. The names given to each widget follows a unique format which hints the code generator to place the generated integer literal in a particular static class. For instance the EditText has an id value “@+id/name” which indicates the generation of new unique integer with “name” as the integer’s name and place it in a static class called “id”. In programs this can be accessed with R.id.name to get references to the EditText object located in the object tree. This scheme by default requires all the activities share the same widget namespace thereby requiring unique names for all the widgets. This can be overcome by carefully selecting the widget namespace to reflect the activity name the widget belongs to. In Visual Studio, by default each page has a unique name space and hence the names of the widgets have only to be unique within each page.

 

Figure 7 - Contoso

Figure 7: Sample Mobile Data Entry Screen

 

 

Figure 8 - Android screen designFigure 8: Android Screen Design in XML

 

  • Both Android and Windows 8 development environments allows the resources like strings, images and animation assets to be externalized and referenced within the declarative and imperative parts of the visual element
  • In both the platforms, widgets can be added to the layout dynamically through code.

 

Figure 9 - Windows Screen Design in XAML

Figure 9: Windows 8 Screen Design in XAML

Storage

Most applications require some form of storage either located inside the device are hosted on a remote cloud service for saving the application state information. The application state includes the configuration, reference data and transactional data which typically be in the form of application settings as name-value pairs, private data files very specific to application, and well known end user files like downloads, pictures, videos, music and the similar.

Application Settings

Applications typically requires some form of configuration settings that will drive application’s look and feel and the behavior. Examples of the configuration settings include the name of the data file or the URL of an external service the application needs to access. The application settings are private to each application and will nicely fit into the name-value storage mode supported by both Android and Windows 8. Android names the application’s private storage as Internal Storage to differentiate it from the External Storage to denote the storage locations that can be accessed by multiple applications.

Android: application settings storage

The following code snippet shows the storage of a name-value pair inside Settings.txt file in Internal Storage:

//Android: name-value storage through SharedPreferences

SharedPreferences _appSettings = this.getSharedPreferences(“Settings.txt”, 0);

SharedPreferences.Editor editor = _appSettings.edit();

editor.putString(“datafilename”, “testdata.txt”);

editor.commit();

Windows 8: application settings storage

Windows 8 API for application storage is encapsulated into Windows.Storage.ApplicationData class that not only includes name-value pair storage but also application specific file management through WinRT objects LocalSettings and LocalFolder respectively. In addition to the application’s local private storage, Windows 8 offers similar classes for managing application specific remote storage if the end user logs into the system using Microsoft Account. Note that LocalSettings also allows the storage of composite data in addition to name-value primitives. Following is the code snippet for LocalSettings:

ApplicationDataContainer lc = ApplicationData.Current.LocalSettings;

lc["datafilename"] = "tesdata.txt";

ApplicationDataCompositeValue adcv = new ApplicationDataCompositeValue();

adcv["name"] = "John";

adcv["location"] = "Chicago";

lc.Values["userattributes"] = adcv;

 

RemoteSettings follows the similar usage pattern for storing of all or part of the application configuration in the cloud enabled by the Microsoft Account log in.

Application Files

Applications store private data files that are downloaded along with the application or progressively updated during the course of the application usage. These files include SQLite databases, XML files, application specific images, sound files, and the similar. Both Android and Windows 8 have APIs for doing file I/O into the private storage.

Android: application file storage

The following code snippet shows the storage of testdata.txt in an application’s private directory:

//Android: creates testdata.txt file in the application directory

String data = "<data>...</data";

FileOutputStream stream = openFileOutput("testdata.txt", Context.MODE_PRIVATE);

stream.write(data.getBytes());

stream.close();

If needed directories can be created using Activity.getDir() and File.createNewFile() APIs in Android.

Windows 8: application file storage

All WinRT I/O calls are asynchronous and require the usage of “await” language keyword for Windows Store applications programmed in .NET languages. The async WinRT API calls return a Task generic which when awaited, suspends the method’s progress and yields control back to the caller. This gives the benefits of asynchronous programming declaratively avoiding the complexity of callback handlers and the boiler plate code one has to write for transferring the state from the handlers to the main processing logic.

StorageFolder lf = ApplicationData.Current.LocalFolder;

String data = "<data>...</data";

StorageFile dataFile =

     await lf.CreateFileAsync("testdata.txt", CreateCollisionOption.ReplaceExisting);

if (dataFile!=null)

     await FileIO.WriteTextAsync(dataFile, data);

 

In Windows 8 the user’s Downloads folder is partitioned for each application by the package family (specified in the application manifest) while in Android the Downloads folder is a well-known folder which can be read or written by all the applications with a single WRITE_EXTERNAL_STORAGE permission.

Following is a code snippet for accessing downloads folder in Windows Store application:

StorageFile dataFile =

     await Windows.Storage.DownloadsFolder.CreateFileAsync("dataFile.txt");

   await FileIO.WriteTextAsync(dataFile, "sample data");

 

External Directory File IO

So far we have discussed the storage options for application specific private data. However, there may be cases where an application may have write to directories that can be accessed by other applications in the system. These directories include well-known folders like documents, music, pictures and videos.

Android: External Storage

External storage location for downloads, videos, music, and pictures can be obtained from Activity.getExternalFilesDir() call supplying the relevant string constant as an argument from the android.os.Enviroment class. For example, getExternalFilesDir(Environment.DIRECTORY_PICTURES) allows to acquire a reference to the pictures directory and work with files using java.io. As of this writing, all the directories in the external storage is accessible to all the applications for reading and writing once WRITE_EXTERNAL_STORAGE permission is specified in the application manifest.

Here is an example of how a file can be created in the external storage directory:

  String data = "<data>...</data“;

  String dir = getExternalFilesDir(null);

  File dataFile = new File(dir,"datafile.txt“);

  OutputStream stream = new FileOutputStream(dataFile);

  stream.write(data.getBytes());

  stream.close();

 

Here is an Android snippet for accessing Pictures directory:

String dir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);

File photo = new File(dir, “SeattleSkyLine.png”);

//do file I/O using java.io package

Windows 8: External Storage

Windows 8 allows the applications to do file I/O against the well-known folders -Documents Library, Music Library, Pictures Library, and Videos Library. Applications need to declare the folder access needs in the manifest for each of these well-known folders through the <capabilities/> node with one <capability/> entry for each of the folders. Windows Store applications can only access private directories discussed previously and these known folders on the device. All the known folders are accessed through the Windows.Storage.KnownFolders object that is integral part of the WinRT API. Windows 8 allows fine grained access to these known folders compared to single permission for the external storage access in Android. Also, all the known folders in Windows 8 are user specific while in Android there is no notion of a current user and hence all the known folders are shared across the system.

The following code snippet shows the creation of a document in the user’s Documents folder:

//DocumentLibrary

 StorageFolder storageFolder = Windows.Storage.KnownFolders.DocumentsLibrary;

 StorageFile file = await storageFolder.CreateFileAsync("testdata.txt",

                                            CreationCollisionOption.ReplaceExisting);

 await FileIO.WriteTextAsync(file, "test data");

 

The above code will only work if the application manifest specifies “Document Library” capability and “.txt” as the allowed file type. Here is the snipped of the manifest that shows the above definitions:

<?xml version="1.0" encoding="utf-8"?>

<Package xmlns="https://schemas.microsoft.com/appx/2010/manifest">

  <Applications>

    <Application Id="App" Executable="$targetnametoken$.exe"

                                EntryPoint="StorageDemo.App">

      <Extensions>

        <Extension Category="windows.fileTypeAssociation">

          <FileTypeAssociation Name="textfile">

            <SupportedFileTypes>

              <FileType>.txt</FileType>

            </SupportedFileTypes>

          </FileTypeAssociation>

        </Extension>

      </Extensions>

    </Application>

  </Applications>

  <Capabilities>

    <Capability Name="documentsLibrary" />

  </Capabilities>

</Package>

If using Visual Studio editor instead of XML text editor, the developer needs to use “Capabilities” tab for specifying “Document Library” capability and use “Declarations” tab for setting up FileTypeAssociation.

WinRT contains APIs for downloading and uploading of large amounts of data to external storage in Windows.Networking.BackgroundTransfer namespace. BackgroundDownloader and BackgroundUploader are couple classes among many that are designed network transfer of large files (e.g. videos, photos) over the internet. These objects run as a background tasks which the system can suspend and restart as needed in order to complete the download or upload task.

The following code snippet shows the usage of Windows.Networking.BackgroundTransfer.BackgroundDownloader to download an image file from internet.

//image download example

StorageFile faviconFile;

try {

  faviconFile = await KnownFolders.PicturesLibrary.CreateFileAsync(

                    "bing.ico", CreationCollisionOption.GenerateUniqueName);

}

catch {}

 

BackgroundDownloader downloader = new BackgroundDownloader();

DownloadOperation downloadOp =

    downloader.CreateDownload(new Uri(@"https://bing.com/favicon.ico"), faviconFile);

 

await downloadOp.StartAsync();

In order for the above code to work, the application manifest has to specify “Internet Client” and “Pictures Library” capabilities as shown below:

<Capability Name="internetClient" />

<Capability Name="picturesLibary" />

The other known folders like “Music Library” and “Videos Library” follows similar access patterns.

 

Conclusion

Both Android and Windows 8 platforms offer similar fundamental capabilities, development tools and SDKs to accomplish the necessary programming tasks for publishing the applications to the respective stores. In part 1 of this series, we have covered a few fundamental aspects of Android and Windows 8 platforms that includes the system architecture, UI concepts, widget maps, navigation and contracts and application storage and external storage.  In part 2, we will cover networking, web services, integrating with cloud services and push notifications.  Given the similarities between both the platforms, Android developers will feel right at home with Windows 8 development. Information for getting started on Windows 8 development can be obtained from https://dev.windows.com.

 

Technorati Tags: Android,Windows 8,Windows Store,architecture

Technorati Tags: Andrroid and Windows 8