Few months ago, I wrote an article for DNC Magazine titled “Hello Xamarin.Forms!” which was later republished online on DotnetCurry.com. This article demoed all awesomeness of Xamarin.Forms with a simple Vehicle Service Reminder app as an example. One of the aspects of the app is to remind users when their vehicle was due for service. While I showed how to go about doing that in iOS and Windows Phone, I left the Android part as an action item for the readers. While some of you may have got it already, if you haven’t, here’s how you do it –

In Android, unlike in iOS, local notifications does not take the fireDate as a parameter while configuring Notifications. So we have to split this task into two –

Use system alarm services to wake your app up at a specified time (Using Alarm Manager)

Write the code to notify users in the “OnReceive()” method of the Broadcast Receiver

Using Alarm Manager

AlarmManager class is used to schedule your application to be run at some point in the future. Create an Alarm Intent, specify the broadcast receiver and finally set the time when you intend to wake your app up.

Notifying Users

Now that the AlarmManager will ensure that your app is run at a specified time, you will have to write the code to notify users in the “OnReceive()” method of the Broadcast Receiver. In this case the broadcast receiver is the AlarmReceiver – a custom class subclassed from BroadcastRecevier.

The code above uses NotificationCompat.Builder and sets the WearableExtender which will ensure the notifications are also sent to the connected Android Wear device. To know more about wearable programming using Xamarin, don’t forget to check out the post on Tips for your First Wear App.

Have you tried embedding a YouTube video into your android app? May be you tried using the HTML to embed the YouTube player in a WebView. From a developer perspective they aren’t programmable – meaning if you wish to interact with the player like play, pause, forward, go full screen, change video quality etc from your app, there isn’t a straight way to do it. From a user perspective the experience isn’t nice and you definitely want to work a better way out. Fortunately, Google provides a slick native YouTube Player on Android platform and a player API written in Java. The player API is a set of client libraries that interacts with a service that is distributed as a part of the YouTube Android app itself. That said, you need to ensure that the YouTube App is installed in the user’s device beforehand. The advantage is – your app size does not bloat up and you can upgrade the client libraries to incorporate new changes to the YouTube app anytime. And, upgrading is not necessary if you do not care about new features or bug fixes.

Bringing this beauty to Xamarin in C#

Lot of developers out there haven’t unleashed the full potential of the Xamarin platform yet. One of the big wins for Xamarin over any other cross-platform solutions is the power to reuse the existing Java and Obj-C (in case of iOS) libraries in C#. Apps built-in Xamarin are fully native and anything that you can do with Java in Android or Objective-C/Swift in iOS can be done in C# using Xamarin. Java ecosystem is large and it is likely that a functionality that you want in Xamarin.Android may have already been written in Java just like the YouTube Android player in this case. Technically, you will use Bindings to bring any reusable Java library to Xamarin.Android. Alternatively, you can use JNI framework or port the entire Java code to C# using an automated tools like Sharpen. In this case, I downloaded the YouTubePlayer API jar file and bound this using the Java Bindings Library project which is part of my solution. This project generates C# dll of your jar file and they are referenced into my Android project just like any other C# dll. I have plans of writing a dedicated post on bindings and you can expect that soon. For now, I suggest, you read the official documentation.

Using the YouTubeAndroid player in C#

The bindings project dll that is referenced into your main Android app has the full Java API in C# along with the beautiful features of C# that you can utilize – like anonymous methods, lambdas, Linq etc. The solution also includes a samples project that helps you understand each of the API features in detail. So, you can copy and paste the entire code “as is” to make it work with your app.

Source Code

If all that you care is the binding library or you are aware of how to get started with it – Head straight to my github for download. Please note: You can execute theses samples only on a physical device that has YouTube App installed. If you have an emulator that has the Google Play Services installed then it may work there too – I haven’t tested this so can’t guarantee!

CueVideo method takes the YouTube video id that you want to play and loads them to your playlist. When user clicks play, well, they get played 🙂 Noticed the OnInitializationSuccess method that is overriden? I use a helper activity called YouTubeFailureRecoveryActivity as the base class for all the samples. This class handles all the failure and recovery mechanism in the Android player.

That’s it!

Don’t forget to take a look at the PlayerControlsActivity.cs file if you want to know how to interact with the player – like play, pause, seek to position, change player style etc.

Configure Nokia X emulator

Open Android Emulator Manager from Visual Studio and create a new emulator with the following configuration:

Give your emulator a name say Nokia-X

Select the Device Nokia X (480 x 800; hdpi)

Select Intel Atom (x86), if you have HAXM installed and Intel VT-X enabled (gives you a faster emulator)

Be sure to select Nokia X Services under Target

Have an SD card with a desired size

Select Use Host GPU as emulation options

Kick Start the Emulator

Hello World

Writing your first app on Nokia X using Xamarin is as simple as creating a regular Android app in Visual Studio.

File > New Project > Visual C# > Android > Android Application

In your project properties, be sure to compile your Android app with Version 16 or lower.

That’s it. Go Run your first app!

I had a simple code to Toast Notify with a custom message on a button click. When I ran it, I saw the message appearing on the top left corner instead of the usual Android toast. Looks like few things have changed here. Refer Nokia X Design Guidelines for changes that you must be aware of.

What if you needed some extra keys for text input in your iOS app? Say for e.g. if you needed text based emoticons on top of the standard keyboard for a chat application. Thankfully UIKit allows apps to have an accessory view above the system keyboard. The area above the keyboard is an extra UIView known as Input Accessory View which you can customize to add your extra keyboard buttons. To add an accessory view, all you gotta do is, set the InputAccessoryView property of the UITextView or UITextField to an appropriate custom view.

Here’s how the extra keys on top of your standard keyboard looks like:

Following code sets the text based emoticons to the InputAccessoryView:

In the above code, we create a UIToolBar with UIBarButtonItems of text based emoticons and set it to the InputAccesoryView property of the SampleText. AddBarButtonText method then handles the key input events.

Playing Input Clicks

You can play standard system keyboard clicks when a user taps in your keyboard accessory views. If you had gone through the apple documentation on Custom Views for Data Input referred earlier, then you would have noticed Objective-C code to do so. Here’s how we can do it elegantly in C#:

Create a custom class called MyUIToolBar that inherits from UIToolbar (since we’re using UIToolbar as the custom view for InputAccessoryView)

Override the property EnableInputClicksWhenVisible and return true from it

Replace the entire keyboard (custom keyboard)?

At times you just want the textbox to input only the keys that you had set. It’s possible to replace the entire keyboard to a custom one. In this case, I just set our emoticon toolbar to InputView property instead of the InputAccessoryView . And this is what it outputs:

I love C# and it has been the language that I have been associated with all my developer life. So when I thought of developing an app for mobile, I wanted to use the tools that I know rather than go learn something new! Being a C# developer it is quite obvious for me to choose Windows Phone or Windows 8 as the mobile platform to launch my app. But wait a minute, I want them to be built on other shiny platforms too – Who’s gonna build the same app for the famous Android and iOS ? Well I want my app to be used by a million users, if not more! HTML5 based hybrid apps are an option but arguably they aren’t the best fit when it comes to User Experience – at least at the time of writing this post.

Forget all that! – I don’t even want to write HTML5 and JavaScript, I want C#. Yeah!!

Xamarin – Why I love it!

Xamarin let’s you create apps in C# for iOS, Android & Mac. Period.

I had a compelling reason (which I am gonna share with you later) to go write a native android app. So I decided to give Xamarin a try – downloaded the trial version and gave it a shot. And the result – a simple app called TripXpense built in less than 24hrs with no knowledge on Android platform or the way it works! Though it’s a simple app, it would have taken me weeks if I had to build it on Java. Most importantly Xamarin let’s me write in Visual Studio with my favorite plugin resharper running on it. What more can I ask?

Xamarin’s Android API exposes almost 100% of the Andriod’s – that said you can build a complete android app in C#. I must mention this – Xamarin documentation is a piece of great work from their talented team! They are brilliant!! Honestly, I haven’t even visited the Android SDK Documentation for help.

So what’s the app?

Well it’s TripXpense – a simple app that let’s you add Trips and Expenses. There are only 4 screens and there’s nothing shiny in this app yet because you know it – It’s been just 24hours of the code. If you think you can do better – go fork it from GitHub.

Disclaimer: I am just sharing my experience of an Android Development on this new amazing platform that I love. That said this is no expert material. Refer Xamarin & Android documentation for patterns and right way of doing things. The code works on my PC & comes with no warranty.

Few Android related stuff that you should know!

Project Structure:

This is how a project structure of an Android app will look. When you create a new Android application in Visual Studio, Xamarin set’s it up for you by default.

Few things to make a note of – only a few for now.

AndroidManifest.xml

Every Android project must contain this file. The manifest lets you define the metadata of your application like Application Name, Package Name, Required Permissions, Activities etc. This is similar to a App.config or Web.Config files but differs in certain ways. In Xamarin you can easily edit manifest information by going to the properties of the project. Please note that there are other values that are auto generated by Xamarin from the attributes that you define in classes. You can learn more about it from the documentation.

Resources

It’s a good practice to keep non-code resources like images, icons, and constants external to your code. Android expects you to store them in a specific sub folders within the resources folder. Notice 6 different Drawable folders which are kept separated based on the DPI displays. These folder will include respective sized bitmaps & PNG images. Perhaps the most powerful Resource to be noted is the Layouts.

Layouts

Layout is the User Interface – Yes that’s right! Whatever user sees is what is designed inside layout files. These are xml based and have the extension .axml . It decouples the presentation layer – much similar to XAML in Windows Phone.

Activity

Activity is the class responsible for setting the UI content for the users to interact! You can consider this as a code-behind for the Layout written in the resources. So the activity class will contain the presentation logic of your view. It is the class that is referenced by the Android system to do the user interaction. Activities are created or destroyed by the Android system. It’s important to understand the Activity Life Cycle to effectively handle user data in the changing states such as Running, Paused, Backgrounded & Stopped. For the TripXpense app, I am yet to implement this feature. Here’s an example of an Activity.

All your Activity classes should derive from Activity base class. Notice the MainLauncher = true set in custom attribute – this is to set the starting screen of your app!
OnCreate() is called when the activity is created. It’s always overridden to perform startup initializations such as

Creating Views

Initializing variables

Binding static data to lists

Notice the SetContentView() – It places your layout on the screen. Layouts can be accessed using the static variable Resources.Layout.<yourLayoutName>.

Now let’s add a Click event handler to the button placed in the Layout. Shall we?

To get the reference of the button placed in the layout use the helper method FindByViewId<T>() and pass the Id of the button you set in the resource. Once you get the handle – just add the event to the Click handler.

To navigate to another screen and pass some extra information along, use StartActivity() with an intent that contains the extra information. Extra information is nothing but the data that you want to pass between your screens.

Now let’s look at the TripXpense app and few fundamentals of the Xamarin app Development.

TripXpense – built using Xamarin!

TripXpense has 4 screens

Home Screen – that shows list of trips and you can add more

Trip Edit Screen – add and edit trips

Trip Details Screen – displays trip summary and Expenses

Expenses edit screen – add and edit expenses

Cross-Platform development

Xamarin supports cross-platform development in C# but it is not just a write once and run everywhere platform. Because one of its strengths is the ability to implement native user interfaces specifically for each platform. So when you architect your apps make sure you separate the code that is shareable across platforms. Refer Building Cross Platform applications.

Separate reusable code into a core library:

For this app I decided to have my database as xml and created all my classes related to business logic, repository and data access in the core library called TripXpense.Core. In case I decide to build a Windows Phone, Windows 8 or an iOS app in future, these files don’t have to be duplicated. And they can be unit tested too! Here’s how it looks:

Please note – You cannot reference this library directly as it is not targeted to Android. And you don’t want to do so because you want them to be accessed by other platforms. Instead you need to use Project Linker extension for Visual Studio which will ensure you have the same code in your Android project. Refer Visual Studio Project Setup Walkthrough

Create an Android Project in the same solution and link the Core project using Project linker. Here’s how your Android project will look with a small blue icon below :

Finally I created the Screens and necessary layouts in Resources and made my app come alive.

Code on Github

You can download this app from my GitHub repository. Go play around with it and let me know what you think!