All posts by Gerry High

Disclaimer: this article isn’t about the why but more about the how and what.

Introduction

Earlier this year I was fortunate to be able to attend Google IO once again. One of the big announcements was that Kotlin was now fully supported by Google for use in Android. At IO17 I attended a few of the sessions on Kotlin and also did a few of the Code Labs and came away thinking this is a neat language. I started to think that it would be worthwhile to convert one of my applications over to Kotlin. This article details my experience in this process.

My Mobile Background

I started building native mobile applications in 2009, first on iOS in Objective C. In late 2010 I started looking at Xamarin as a cross-platform way to write mobile apps using C# as the language. I ported one of my apps from Objective C to Xamarin iOS. At that point I also needed to create an Android version of this application and rather than writing in Java I chose to use Xamarin Android (XA). Although I have some experience in Java/JNI (dating back to 1995ish) in the WORA (write once, run anywhere) era I’ve never done a lot with Java. Since 2010 I’ve written many applications for clients using the Xamarin toolset.

One thing to point out in Xamarin development is that there are two major approaches to application development

For various reasons I have always written to the native APIs for both iOS and Android. This point is key as you will see it was a factor that made my migration easier.

The Project

The application I chose (a sports application) is only about 11k lines of C# code (this excludes the 7k line Resource.designer.cs file). Although many of you might consider this to be trivially sized, I believe this to be an good size for a first migration. Additionally this application also exercises various features including a local SQLite database, REST services, push notifications, administrative login and score input.

Getting Started

After I got back from IO17 I downloaded the alpha build of Android Studio 3 and created a test project and did the basic “Hello World” Android app. In order to learn Kotlin (besides googling and the Kotlin language website) I used these resources

After the Hello World project I played around with a few of the templates in Android Studio and settled upon one that mimicked my application (drawer navigation). One key point:

Don’t try to get everything right initially—just go and start writing code initially so you can learn.

In other words during the early stages I suggest you write to learn, but plan on throwing it away. Don’t worry if it is good code. I used this approach for about 2 months (on a very part-time basis) while I tried out various things and extended the Android test app, Finally in July I created a new project that would eventually be the foundation of my production app

Porting

First off with the bad news:

You can’t be half pregnant

If you have an Android app written in Java you can start learning Kotlin by adding in new features in Kotlin. Conversely, in Xamarin this is an all or nothing endeavor. You’ll want to carefully weigh the number of lines of code and consider what third party components, libraries, etc. you are using and what you will replace them with.

The good news in porting from XA is that if you’ve written to the native APIs your resource files will work with no modifications. In addition, all of your Fragment and Activity lifecycle methods will match and so structurally your code will be very similar.

Note: If you’re wanting to port an application written in Xamarin Forms you will have a lot more work ahead of you. All of your layout files (XAML) will need to be redone using Android layout files. Additionally all of your C# MVVM code will need to be rewritten.

I chose to create the resources manually in Android Studio and then copy/paste the XML from XA into each resource file. I did this so that as I worked through the app I could look at the XML to make sure there were no parsing errors, etc. I did find a few cases where I used attributes that were deprecated or just bad.

In most cases porting from C# to Kotlin is pretty straightforward. Although there is no copy/paste converter for C# to Kotlin, I don’t find this to be a big loss. I do not recommend using a converter as you will learn more by converting your code manually. I did find one occasion to use the Java to Kotlin converter when I needed to convert a Separated List adapter. Many years ago I ported it from Android to C#. I found it easier to go back to the original Java source code and use the Java to Kotlin converter and then modify it as appropriate.

One challenge I found was figuring out constants/enums, etc. as it seems like the Xamarin guys took some liberty in naming values and putting them in completely different namespaces from the Java/Kotlin namespaces. For example:

1

2

3

4

5

6

C#

DescendantFocusability.BlockDescendants

Kotlin/Java

ViewGroup.FOCUS_BLOCK_DESCENDANTS

Another challenge I ran into was with asynchronous programming. If you’ve adopted C#’s async/await you’ll need to think about what approach you wish to use in Android. After attending the Kotlin Conference and watching Roman Elizarov’s sessions on coroutines I opted to use coroutines even though they are marked experimental. Note: Jetbrains is encouraging people to use coroutines in production; experimental is a misnomer in my opinion.

The following snippet is what I came up with–this example is one of the few cases where the Kotlin code was slightly more verbose than the C#.

Coroutines

1

2

3

4

5

6

7

8

9

10

C#

games=await service.Load(id,field.Id);

renderResults()

Kotlin

launch(UI){

games=service.Load(id,field.Id).await()

renderResults()

}

Some of the components I used are listed below along with their Kotlin/Android equivalents.

Xamarin

Kotlin

AndHUD

Anko Indeterminate Progress Dialog

SQLite.net

Anko SQLite

ServiceStack C#

ServiceStack Android

Redth GCM.Client

Firebase Cloud Messaging

Crypto Obfuscator

Proguard

Azure Mobile Center

Firebase Crashlytics

Technical Debt

Rather than port an outdated technology or piece of code I chose to address a few areas of technical debt by updating them to the latest technology.

Added Google Analytics (perhaps not considered technical debt but rather a feature)

Converted Icons to Android O Adaptive Icons

Are We There Yet?

Even after finally getting to feature complete I was reminded of this:

Hofstadter’s Law: It always takes longer than you expect, even when you take into account Hofstadter’s Law.

Some issues I ran into included dealing with

back stack and fragment crashes

manifest merge issues related to FCM and permissions. I had to use a setting to remove the merged attributes

crashes related to proguard

crashes related to errors in porting code (usually due to carelessness on my part)

A lot of hours were spent in testing and debugging code during the final phase.

Takeaways

As I write this now the Kotlin version of the application has been released to the Google Play store. Time will tell how well the port stands up with regards to maintenance, time to add new features, stability, etc.

This project took a total of 6 months. However, there were many weeks where nothing was done as this was a low priority project.

The Kotlin application is significantly smaller in both APK size and lines of code (LOC).

Xamarin

Kotlin

11k LOC

4.4k LOC

APK 22MB

APK 2.3MB

Some of you will look at that and wonder why the Kotlin LOC was so much smaller than the C#. Some of this was due to elimination of dead or commented out code. Another portion of code was in a shared library between iOS & Android and some of that shared code wasn’t being used in Android and so it wasn’t ported. C# POCO classes are a lot more verbose than Kotlin’s data classes (that amounted to about a 1K difference). I’ll have to do further analysis to figure out where the other differences were.

As for the APK size difference, the Kotlin APK was generated using Proguard while the Xamarin version did not. However, the Proguard optimizations only reduced the APK size by around 1MB in size. I believe the main size differences were to the number of DLLs that Xamarin includes in the APK. When you’re designing for the next billion every megabyte counts and this was a big win for Kotlin.

One other surprising benefit of the migration is performance–the Kotlin version is notably faster and I was not expecting that. The Xamarin version has never felt slow but next to the Kotlin version I found myself waiting longer for screens to load, etc.

All in all I’m pretty happy with how the application turned out. The Android Studio environment is also top notch. If you’re considering a similar migration I hope this article will be of help in making the decision to port or not to.

As a side note, one thing I like about conferences in Denver is that the travel for me is pretty easy. From where I live (Kansas City) I can get a cheap non-stop flight and be here in an hour and a half. Additionally now that the airport has the train I can easily get from the airport to downtown for only $9 in about 30 minutes. From the train stop at Union Station you can then catch a free bus (or walk) the several blocks to the hotel.

360AnDev was a 2 day event (Thursday/Friday, July 13/14 2017). This was just the second year of the event and the attendance was a little less than 200 attendees and 40+ speakers. Of the speakers almost 1/3 were women speakers (well done John, Chiu-Ki and Dave). There were 3 tracks with sessions running from 9-6 the first day and 9-5 the second day. I thought all of the speakers were very good.

Having attended #IO17 this year and seeing the Kotlin sessions there it was nice to see that 360AnDev had 2 sessions on Kotlin. I attended both in part because I’m working on porting an app to Kotlin. It’s great to see the passion that the various speakers have for the language. Perhaps I’ll see a few of you at the Kotlin Conference in November.

I’ve posted links below to various slide decks and notes that people shared. If you have other links that I missed shout out to me on twitter @gerryhigh and I’ll update this post.

If you’re a Android developer put this event on your calendar for next year and follow @360andev for updates (videos will be posted in the next few weeks is my understanding).

When Urban Airship (UA) announced back in June that they would be canceling their free tier for push notifications I started looking at other free & paid alternatives (e.g. Parse, Azure and others). However, ultimately I decided to host the push notifications myself using PushSharp.

If you’re not familiar with PushSharp, it is a server side library for sending push notifications to various platforms.

The migration was really pretty easy and involved these steps:

Update server software that sends out push notifications to use the PushSharp libraries.

Update mobile apps (in my case this was just for the iOS and Android platforms)

Implement a mitigation strategy to handle users on old versions of the Android application

If you look at the sample in the GitHub repository you’ll see there is some setup of the Push Broker that needs to be done prior to sending any messages. If you are hosting your server code in a windows service you could put that in your main program. In my case I’m hosting the Push Broker inside of IIS and thus have put all of that code into my Application_Startup method.

Note: you can update and deploy the server software prior to updating your apps.

A Note about Urban Airship notifications for Android

My sample code above includes a case for Urban Airship Android messages. The reason for this is that the device token you get from their APIs is not actually a Google Cloud Messaging (GCM) device token but rather an Urban Airship generated token. This is unfortunate as it means you’ll need to continue sending some push notifications via the Urban Airship REST API until all of your users are transitioned over to your new app.

Updating Mobile Applications

Updating my iOS application was pretty trivial as I just had to remove the code that registered my device with Urban Airship. Nothing else needed to be changed as the device token you deal with is a standard APNS device token and not an Urban Airship token. Additionally, as the messages that are sent by PushSharp on the server are identical to the messages sent via Urban Airship I didn’t have to change my code that parsed the notification.

Updating my Android app was a little more involved.

1. Remove the Urban Airship binding library as well as any calls to Urban Airship.

4. Remove the BroadcastReceiver service and replace it with a service as shown in the GCM.Client sample. Migrate any code from the OnReceive handler in the BroadcastReceiver class to the OnMessage handler in GcmService.

One extra piece of work that I had to do was because I was using a Urban Airship specific class for displaying notifications (CustomPushNotificationBuilder). I replaced that with Notification.Builder.

Mitigation Strategy

To handle the fact that Urban Airship uses their own device tokens on Android, my approach was to treat device registrations using GCM.Client as a new device type on my backend (and thus leave in place Urban Airship GCM device registrations). Thus until the end of the year my server software will continue to send push notifications to any users that are still on an older version of the Android app via the Urban Airship REST API. Users that install the new application and subscribe for push notifications will receive their notifications via PushSharp. I’ll continue to monitor how many devices are still on Urban Airship as I approach the year end and may choose to send a broadcast notification to those devices to tell them to upgrade. After 12/31 I will update the server software to quit handling Urban Airship GCM tokens.

Final Thoughts

If you’re thinking about adding push notifications to your app but weren’t sure what to do take a look at PushSharp. Jon Dick has done a great job with the software and continues to support and enhance it (he tells me he is working on a new and improved version that will be out before too long!)

Why

I’m writing this a week or so after the release of the iPhone 6/6+. I hold in my hands the 6+. Let me backup.

As the information came out on the new iPhones at the Apple press event on September 9th I wasn’t all that excited about either phone. I’ve had larger phones, having used various Android phones as my second phone, most recently a Nexus 5. So a larger iphone in and of itself isn’t something I’ve been waiting for.

However, coinciding with the announcment also came the GM release of iOS 8. I updated my devices to the GM and downloaded the dev tools and started testing my apps on the simulator. Up to this point I had been running my apps on the various iOS 8 betas but these were apps that had been built using the iOS 7 SDK. With the apps built now for iOS 8 I started seeing more sizing bugs (due to changes in MainScreen.Bounds), etc. That’s when I decided I should get a 6/6+.

I decided initially to get the 6+ and not the 6. My reasoning was that the 6+ would be the harder device to design for since it supports landscape orientation, reachability, and larger layout changes.

How

So I got up at 3AM CST on Friday the 12th (yes, I overslept my alarm by an hour 🙁 ). I logged into my AT&T business account only to find out that AT&T hadn’t enabled the option for purchasing phones (event though a person at the AT&T store had told me the day before that it would be available). I wasted about 30 minutes trying various things until I realized it wasn’t going to happen and went back to bed.

The next day my twitter timeline was filled with reports of failures for the most part–Apple store down, timeouts, etc. I also saw that order times for the 6+ were already into October. I knew then that my only option would be to go stand in line at an AT&T store if I hoped to get one on launch day.

On 9/19 I got up at 5am, showered and headed to a nearby AT&T store. I went to the same one I had gone to last year for the 5s as they didn’t have a big line and I was hoping the same this year. I got there at 5:45am and was rewarded with being around 9th in line.

At 7:45AM AT&T employees came out and started taking down who wanted what. When they got to me I told them I wanted the 6+ Space Gray 64GB. They told me that was the last one available. I heard later that they only got in a total of 6 iPhone 6+s. At 8AM AT&T let us into the store and I rolled out of there by 8:15 with my new iPhone 6+.

Impressions

I’ve now had the 6+ for 9 days and have been pleasantly surprised. First off, the battery life is nothing short of amazing. For years we all have been upgrading our phones and getting basically the same old battery life. Not so this year. I can now use my phone from 6AM to late into the evening on a typical day (almost midnight on some days) without recharging. In comparison to my 5s for the same usage I would often need to be charging my phone by 5pm (or earlier). With my 5s (or 5, or 4s, etc.) I always had to make sure that I had my phone charged sufficiently before going to any event. Woe to you if you got in your car without a car charger!

The second major upgrade that I’ve enjoyed is the camera. The pictures I’ve taken have been noticeably better than my 5s or Nexus 5. The picture below compares the 6+, 5, and Nexus 5. The pictures were done very quickly and there were no retakes, etc. and that is perhaps why the iPhone 5 picture is poorly focused.

iPhone 6+, 5, and Nexus 5 Left to Right

Developer Thoughts

There is no substitute for having an actual device so you can test usability (reach) as well as readability, etc. From a developer’s perspective, one benefit of having the 6/6+ is that they support display zoom. With Display Zoom turned on, my 6+ behaves like an iPhone 6, with a rendered width of 375 points. See this article by PaintCode for more information: http://www.paintcodeapp.com/news/ultimate-guide-to-iphone-resolutions

When my app runs on the 6+ with Display Zoom turned on it will exercise the iPhone 6 sized assets in my app. This was an unexpected benefit that I’m quite happy about–it’s almost like having 2 phones (but not).

However, as I said before there is still no substitute for having a device to determine usability and readability of your application. I may still need to get an iPhone 6 for designing for the 4.7″ screen. But for now the 6+ was a great choice.

If you develop native mobile apps using Xamarin you quite likely have used BTProgressHUD for iOS or AndHUD for Android. These are great components for displaying work-in-progress dialogs or toast messages.

While the components have similar APIs nevertheless they are different and in different namespaces and thus create an issue if you”re trying to code share between the two platforms. I hit up Nic and Jon on twitter this week and Jon suggested writing a class that wraps both.

I wrote XHUD.HUD as a result. It”s quite simple as it mimics the underlying APIs and unifies the slight differences between the 2 APIs. However, I didn”t map every variation of the APIs and thus it will need to be extended.

Longer Term

Longer term it would be nice to see Xamarin.Mobile encompass more things like this. Having said that it doesn”t seem like it is actively being developed. So for now we have XHUD.HUD but I”m not crazy about the namespace XHUD as it seems redundant and too narrowly focused. Perhaps XPlat as the namespace and it contains HUD, AlertDialog, etc? We”ll see.

I”ve decided to wait for the 5s. This may mean old-school standing in line somewhere or perhaps risking walkup at a retail store on the 20th.

Why the 5s? I haven”t done a lot of analysis on this but for own personal use I typically buy the fastest (5s) and midrange storage (32GB) . Since I spend the majority of my time developing mobile apps for iOS and Android I pretty much buy the latest and greatest from Apple each year. With the fingerprint scanner and the camera enhancements I figure the 5s will have more of a potential developer impact vs the 5c. Perhaps I”m wrong?

Craig Hockenberry makes a case for the 5c:

If you”re a developer, it”s easy to fall into the 5s group (we love tech!) But the most important customers are in the 5c group…

To borrow from and paraphrase Merlin Mann hopefully accurately, you are what you actually do, not what you think or wish that you did. So far, in 2013, I’m really a writer and podcaster and, to an embarrassing degree, a Twitter user with a programming hobby.

I’ve been a long time Windows Media Center user, going back to the days when Charlie Kindel was working in that group (before his time as a Windows Phone PM). I was also one of the early beta testers of Media Center and was actually seeded hardware from the group at MSFT.

Although in the past I’ve used the full monte of features that Media Center provides, in recent years I’ve found that my main use of the Media Center has been for streaming videos and other content from sporting websites or Youtube, etc. Last year the media center PC I had died due to a hard drive issue and so I’ve done without a media center pc since then.

Fast forward to 2013 when I blogged in March about deciding to sell my Surface RT (primarily due to getting a Surface Pro). After putting it up for sale I had a situation where I wanted to watch a sporting event that was only available via streaming. I decided what the heck, why not try the RT to do this. So I went out to the Microsoft Store and picked up an adapter to connect the RT to the home theater system.

I”ve listed the cost breakdown below:

Surface RT ($500)

micro-USB to HDMI adapter: $10 (I bought the $40 from the MSFT store but since found you can buy others much more cheaply)

Logitech Easy Switch Bluetooth Keyboard: $60 (this wasn”t really an added cost since I was already using the keyboard hooked to an Apple TV)

Microsoft Bluetooth Notebook Mouse 5000 (Free, as I had it in a drawer)

Total outlay is around $600.

The Surface RT is hooked into a relatively cheap Home theater receiver (Pioneer VSX-820) via one of the HDMI ports. One HDMI output then goes to a Sharp 52″ TV that is mounted on the wall above the fireplace.

Front View – 52″ Sharp

The TV can be pulled out from the wall as shown below. You can see the mess of wires, etc. The Surface RT is sitting in there but hard to see since the display is not turned on since it is running on the TV.

TV pulled out from wall

I use a Harmony One remote to control everything. I created an activity called “Surface PC” which just switches the HTMI input on the receiver to the Surface RT. It also controls the volume via the Pioneer receiver.

Showing activity “Surface PC”

The keyboard I use is a Logitech Easy Switch Bluetooth keyboard. The thing I like about this keyboard is that I can pair it up to 3 bluetooth devices. I have an Apple TV paired to F1 and the Surface is on F2.

Logitech K810 & Microsoft Notebook Mouse 5000

The mouse is nothing special as it was laying around the house. However, it is bluetooth which is nice (no extra adapters) and it also has an on/off switch (as does the keyboard).

I”ve been using this setup now for 3 months now and like it quite a bit. I primarily use it when there is some event on that I want to stream from the browser. I”ve used it a lot to stream MLS soccer games via a MLS Live subscription. I”ve also used it with vdio.com (e.g. rdio.com video cousin) and youtube.

While I”ve played around a little bit with using some of the Windows “metro” applications so far I haven”t found what I”d call great 10″ UI apps. If you have some great 10″ UI apps please let me know.

As mentioned in my 2012 Post I bought a Surface RT back in November when they launched. While I like the device I haven”t had much time to use the device as I”ve been heads down doing iOS development and so it hasn”t gotten a lot of usage.

In January/February of this year I started doing Windows Phone 8 development on my MacBook Pro via a VM. When the Surface Pro came out in February I picked one up the week after they came out–the Microsoft store sold out but put me on a wait list and then got a call about a week later. The biggest thing about the Surface Pro over the RT is the ability to run Visual Studio (and thus do Windows Phone development). As an added bonus I”ve really liked using the stylus with OneNote for note taking in meetings.

Thus my Surface RT is going up for sale. I will be posting it for sale in the forums over at Surface Geeks (http://surfacegeeks.net). The unit comes with 32GB, a touch cover, and a brand new Incipio Surface sleeve ($40 retail).

First off let me say that I don”t like to make new year”s resolutions. I also don”t usually look back and analyze or review. However, this year I”m capturing some of the past partly because my memory seems to gets worse each year. By putting this down on paper I have something to remember this year by as well as to compare to next year.

I”ve listed some things I did, worked with, saw, used, etc. (not necessarily in order of importance)

Devices Galore

Given the nature of the work that I do, I end up buying devices as they come out, if I feel that I will need or want them. Only after making a list do I realize how many significant devices launched this past year and how many I used or felt were important.

iPad 3 Verzion LTE (Mar)

Retina MBP (Jul)

Nexus 7 8GB (Jul)

iPhone 5 AT&T LTE (Sept)

Mac Mini (for blog, Sept)

iPad Mini Verizon LTE (Nov)

Surface RT (Nov)

Nokia Lumia 920 AT&T (Dec)

Apple TV – Gen 3, (Dec)

Of these devices I used the retina MBP tons every day. I used the iPad 3 a lot from Mar-June but then as I shifted focus to iPhone app development I used it very little. Once the iPad Mini came out in November I found myself very rarely using the iPad 3 (perhaps I should sell it?).

The Surface RT is a great device but suffers from a lack of good apps. The Nokia Lumia 920 replaced an android phone (Samsung Galaxy S2 Skyrocket) and really is a beautiful phone on a nice OS/UI. In 2013 I expect to be doing some x-plat development for Android and so I expect that the Nexus 7 will see quite a bit of use.

Sharpening The Saw

2012 was the year I decided to focus on “sharpening the saw” by attending a few events.