Showing posts with label android. Show all posts
Showing posts with label android. Show all posts

Wednesday, 18 March 2015

Microsoft Band SDK + Xamarin

Band-fans were happy to see Microsoft release their Java Android SDK for Microsoft Band a few weeks ago, and their Objective-C iOS SDK this week. Xamarin was then able to almost immediately release the Microsoft Band SDK component for iOS and Android, giving you the same functionality but entirely in C# for all three mobile platforms...

I decided to give it a try, converting my "magic eight ball" apps for Xamarin.Forms and Apple Watch to the Band. The idea is: you shake your wrist and the "prediction" appears on the Band!


It works because there is an Android app running on the paired phone, using the Band SDK. The app is tracking the Band's accelerometer, and using the readings to decide when you've shaken your wrist a couple of times.

When the shake-detection is triggered, the app picks a random number, pushes a new Tile onto the Band (if it doesn't already exist), and then sends a message for the tile with a random "prediction".

The Android app is simple, it contains only a Connect button to connect to the Band, and a Vibrate button to test the connection (plus a label that displays the "prediction" text that is sent to the Band).


The code for this Android sample is available on github, hopefully I'll get the iOS version running soon.

If you want to get more info about developing for the Band, check out Matt's detailed blogpost with code.



Finally, Microsoft built a quite detailed Android app that demonstrates all aspects of their SDK, and Matt did an amazing job of porting it to Xamarin - check that out too!




Tuesday, 15 January 2013

Xamarin for Java Developers

Last night I was given the opportunity to present Xamarin's Mono for Android to the East Bay Google Developer Group. It was a lot of fun, with plenty of the audience asking a lot of great questions and generally being curious about how C# can be used to build Android apps. Here are the slides from the talk - please drop me a line with any feedback or questions!

One topical question was "what does using Xamarin and C# offer existing Android Java developers?". I have a couple of thoughts which are listed below (in no particular order):

Learn a new language!
The days of specializing in a single language throughout your career (or even throughout the year!) are over. Once upon a time it was COBOL all the way down, and you could argue that it's still enough to just know C/C++. But it's no longer the norm ~ developers want to grow and learn, and use the best tool for the job (whether it's Perl, PHP, Java, Ruby, C#, F#, Javascript, TypeScript, Go, or whatever).

It can be daunting though, to start from scratch and learn a new IDE, framework and syntax - which is why I think C# is a great progression for Java devs. The two languages are obviously related - there is a lot of common syntax and equivalent keywords that make it easy to get proficient quickly. They're both strongly typed, so the IDE and compiler can really help you learn. Then once you know the C# basics, a whole world of new APIs open up to you: LINQ, the .NET framework's serialization and web service features, Parallel Task Library and async support, reactive extensions, and more.

It also introduces you to another IDE (Visual Studio is a great tool, as is Xamarin's free MonoDevelop IDE), which in turn can encourage you to further explore other languages and platforms (suddenly it's a small leap to work on Windows Phone, or try F#). Using the free trial you can easily get productive in C# and Android development without any up-front cost: you can run your apps on the Android emulator, and choose to work on either Windows or Mac with MonoDevelop.

Cross-platform development!
There are a lot of Java developers who are already proficient with the Android SDK and have published successful apps to Google Play, or Amazon, or Samsung app stores; and there's another group of corporate/enterprise developers building apps for internal/extranet use that were designed for Android. When these developers ask "why Xamarin?", I never say "throw away everything you've done and re-write in C#!" -- that'd be crazy ;-)

But what happens when you want to take these apps cross-platform, either to make more money on the iOS and Mac App Stores or to better support a corporate BYOD policy which means your internal apps need to run on iOS and Windows? You can choose to learn Objective-C to write for iOS and C# for Windows... or take the opportunity provided by Xamarin to use C# for all the non-Java platforms and reduce the amount of code you have to support and re-write by half!

Following on from the first point, I think learning C# is a much smaller leap for a Java developer than Objective-C; and once you've done so you can work on either iOS apps using Xamarin's MonoTouch or Windows Phone, Windows 8 and Windows RT tablet apps! You might like C# so much that you do go back and re-write your Java, or at least start building a hybrid that shares some Java and C# code...

Xamarin does Android well too :)
If Java developers do fall in love with C# then they also find that Xamarin does Android just as well as anyone (probably better!). Our MonoDevelop IDE (and our integration with Visual Studio) means you get an awesome coding experience (autocomplete/intellisense/code completion, debugging, refactoring, source control integration, etc) as well as a drag-and-drop UI designer. You be the judge of whether it's a better experience than Eclipse :)

Fin
In summary, why not? As a Java developer you have a lot to gain and nothing to lose by giving C# a try. A whole world of new platforms, tools and frameworks become available with a very low barrier to entry. Try it - you just might like it ;-)

Thursday, 13 September 2012

Microsoft's Azure Mobile Services... and WP7... and Mac

So far, Azure Mobile Services have been added to MonoTouch and Mono for Android (as well as Microsoft's getting started sample for Windows 8).
To complete the 'set', I ported the MonoTouch code to MacOSX using the free, open-source MonoMac AND used @kenegozi's 'unofficial' client to munge Azure Mobile Services into our existing Tasky sample on WP7.

These aren't production-quality implementations, mind you, just a couple of quick hacks to illustrate the beauty and simplicity of having C# and the .NET framework available across all these platforms. Oh, and also show the beauty of Azure Mobile Services :-)
You can grab the code for all of these from TaskCloud/Azure on github. You'll need to sign up for the Azure trial and follow the instructions to set up the Todo list tutorial.
Screenshots
Here's how the WP7 and MonoMac versions look:

Saturday, 1 September 2012

Microsoft's Azure Mobile Services... and Mono-for-Android

Yesterday's post introduced a quick implementation of Microsoft's Azure Mobile Services using MonoTouch to build an iOS app.
The WebClient and Json handling was easily refactored into a single class - AzureWebService - which was then added to the existing Android version of the Tasky sample... and now we have the same Azure Mobile Service being access by three platform clients: Windows 8, iOS and Android all with C# (and the iOS and Android apps sharing the service client code).

Additional features have also been added to AzureWebService to allow deletion of tasks. The Android app source is on github and it looks like this (delete has been added to the iOS app too):

Here is a discussion of how the API was reverse-engineered with Fiddler. The REST endpoints that TaskyAzure accesses are:

GET /tables/TodoItem

GET /tables/TodoItem/?$filter=(id%20eq%20{0})

PATCH /tables/TodoItem/{id}
{"id":1,"text":"updated task text","complete":false}

POST /tables/TodoItem
{"text":"new task text","complete":false}

DELETE /tables/TodoItem/{id}

Finally, only a few small updates were required in the Windows 8 example prevent the completed tasks from disappearing and instead make use of the checkbox in a more natural way:

Now all three apps are reading and writing to the same Azure data store! Can't wait for the official cross-platform APIs :-)

Wednesday, 13 July 2011

"M"osetta Stone II: ViewController → Activity

After my recent posts I received a question asking for tips on porting a MonoTouch app to MonoDroid. I'm going to take a crack at that over a couple of days - with the warning that you probably shouldn't rush out and buy either tool but wait for Xamarin's future Mono-on-iOS and Mono-on-Android products.

The purpose of the original "M"osetta Stone post was to give cross-platform developers a 'head start' with some high-level concepts. This post will look a little closer at a screen from the Monospace11 app: the Speakers list.


This may be a massive oversimplification, but...
if you have
___ in iOS
then you want
___ in Android
to
UIViewControllerActivitysubclass to present a screen/form/page to the user
ViewDidLoad()OnCreate()setup the UI
Add() or AddSubview()SetContentView()use in ViewDidLoad/OnCreate to 'attach' UI to display
ViewWillAppear()OnResume()load/re-load data that might change and bind to UI
UITableViewListViewvisual control that presents a scrolling list
UITableViewSourceAdaptersubclass to broker the display of a data collection to the UI
GetCell()GetView()to build the layout(UI) for each cell/row, including re-using cells/views for performance
RowSelected()ItemClick EventHandlerperform an action when a row is touched
RowsInSectionCounttell the table/list how many rows to cater for

Here's how it looks in a Visual Studio Class Diagram*
* I've greyed out some of the methods not relevant to the discussion - the iOS implementation of the alphabetic index down the right edge doesn't have an Android equivalent, for example

Notes:
  • UITableViewSource has been implemented as an nested class to resemble the iOS pattern of implementing the equivalent Obj-C protocols on the ViewController - this pattern makes no sense in Android so the classes are separate.
  • The MonoTouch example code builds the UI in C# (eg. tableView=new UITableView();AddSubview (tableView);) whereas MonoDroid loads layout XML files SetContentView(Resource.Layout.Speakers);. This can happen in both ViewDidLoad/OnCreate and GetCell/GetView where UI controls must be created and presented to the user.
  • The 'touch event handler' is in a different class: in MonoTouch the TableViewSource handles a touch for a specific row (NSIndexPath); MonoDroid implements the ItemClick EventHandler<ItemEventArgs> on the ListView for a given GetRow(e.Position).
  • Both examples use the constructor (TableViewSource/SpeakersAdapter) of the 'broker' class to pass the actual business object collection for display. This pattern lets the data be filtered/sorted/whatever before being passed in for display.
  • Calling refreshSpeakers() from ViewDidLoad/OnResume is kinda redundant in this example since the list never changes - but in other spots (eg the Favorites screen) you would want to refresh the list each time because it may have changed.

The Code
You can have a look at the MonoTouch code SpeakersViewController.cs and the MonoDroid SpeakersActivity.cs, SpeakersAdapter.cs to see the actual implementation. For MonoDroid you'll also need to check out the layout XML files Speakers.axml and SpeakersItem.axml.

One more thing...
One final piece which takes some getting used to... in MonoTouch this screen is part of a UINavigationController stack and your RowSelected creates a new ViewController object (passing whatever parameters you need) and calls NavigationController.PushViewController(). The ViewController instances in the navigation stack are 'stateful' and it is really easy to pass business objects around as parameters.
In MonoDroid, the ever-present 'back-stack' does not require a specific 'navigation controller' BUT at it's simplest the mechanism is much more primative and involves passing simple type parameters (eg. strings) like this
var intent = new Intent();
intent.SetClass(this, typeof(SpeakerActivity));
intent.PutExtra("Name", speaker.Name);
StartActivity(intent);

There are more sophisticated approaches but it is probably best to keep your parameter-passing to a minimum - this way the Android hardware 'Back' button "just works".

HTH Slava ;-)

Monday, 11 July 2011

MonoDroid v MonoTouch : a comparison

The past few days I've posted MonoDroid and MonoTouch apps for Monospace - and while they aren't perfect examples of the sort of code-sharing and efficiency that's possible with Mono I thought it would be interesting to compare them as the functionality they offer is very similar.

First, these are the high-level code metrics (as calculated by Visual Studio):
Unfortunately I didn't align the namespaces very well. Here's the explanation:

Total lines of code (TLOC)
Mono-for-Android: 802 lines
MonoTouch: 1,420 lines (2,033 - 613 in SQLite)
At first glance, the MonoDroid app 'wins' with just half the code of the MonoTouch version. I've ignored the SQLite library and the MonoTouch.Dialog framework as they aren't "user code", and any non-.cs files (eg XML markup).

Common code
Although difficult to 'see' because I've rushed these codebases into the public domain, there is a bit of 'code re-use' in these apps (ie. it was only written once, and the c# shared across both platforms using the power of Mono :)
ConfXml == MIX10Xml == approx 200 lines of business objects (DTOs mainly) that match the serialized conf.xml format that is the shared data structure for both platforms.
The ConceptDevelopment.Kelvin code is also shared (different sizes in each aren't relevant for now).

Removing the common code from the comparison results in these totals:
Mono-for-Android: 575 lines (802-199-28)
MonoTouch: 1,145 lines (1,420-178-97)

"Re-used" code
Mono-for-Android's Main.cs::DeserializeConferenceFile, LoadWhatsOn and MonoTouch's AppDelegate.cs::FinishedLaunching both contain "very similar" code in the form of the conf.xml deserializer and parser. In MonoTouch it's 70 lines and in MonoDroid it's 307 lines. The MonoTouch version is heavily assisted by the Linq/MonoTouch.Dialog code in HomeController (another 150 lines or so) which explains part of the difference... but what is shared is the deserialization logic and a number of Linq statements that help parse it for display. These would be harded to shift into a common library due to the dependency on MonoTouch.Dialog - but there was definitely an efficiency gain by having the code already written and tested on one platform before porting to the other. I'll adjust both by the same 'average' LOC count to try and reflect the 'copy/paste but modify' efficiency gain.

Mono-for-Android: 375 lines (575-200)
MonoTouch: 945 lines (1,145-200)

Feature parity
Adjust the MonoTouch solution to allow for the fact that it implements the Map feature that is not available on MonoDroid - 118 lines of code across a few classes.
MonoTouch: 827 lines (945-118)

What's left?
Once we've removed the libraries, the shared data structure, common code and allowed for some "copy/paste re-use", what's left to differentiate the two codebases? Basically just the UI and the code that binds our DTOs to it.
Mono-for-AndroidMonoTouch (iOS)
Code375 lines827 lines
'markup'14 AXML1 XIB
Views7 Activities9 ViewControllers
DataSources6 Adapters5 TableViewSource
Some notes on the difference:
  • There are 350 lines of AXML to define the layouts used in MonoDroid - the equivalent task in MonoTouch is done mostly in C#, significantly contributing to the LOC difference. I could have implemented a lot of that MonoTouch layout in XIBs using InterfaceBuilder - I just don't like doing it that way.
  • The UITabBarController takes more code to setup than
    OnCreateOptionsMenu.
  • The iOS SQLite implementation of saving Favorites is more verbose than the XML-serialized-file solution used on Android.
  • The MonoTouch source is almost 2 years old, and in some places isn't as succinct as it could be.

Conclusion
So is MonoTouch instrinsically more verbose than MonoDroid? I don't think so - it depends greatly on your preference for constructing your Views (XIBs or in-code). The more important question: does building with Mono* make it easier to port your app to other mobile platforms... and the answer is YES! In future this code might get tidied up into a good example of a cross-platform app... in that case I'll re-examine the stats to make an even better case.

Look at it this way: the iOS app took 1,400 lines of code (it was written first). For an additional 375 LOC (plus some layout XML) we got an Android port - almost for free!

Thankfully it sounds like Xamarin Studio is coming along nicely.

Wednesday, 6 July 2011

MonoDroid for Monospace

Waay back in 2009 I threw together MonoTouch for Monospace as an early example of using C# on the iPhone using MonoTouch.

Fast-forward two years... to MonoDroid for Monospace:

The schedule for Monospace 2011 was just announced today, and since there didn't seem to be a mobile app announced along with it I've re-used some old code to get a basic Android app working using Mono for Android.

Download/try it out
You can install Monospace11 from the Android Market

OR

Download the Mono for Android code from Monospace11 on Github

and visit the 'homepage' at monospace11.confapp.com

Leave any comments or feedback below.

Tuesday, 31 May 2011

OzALT.NET MonoDroid Presentation

Slides from tonight's OzALT.NET '20 minute' presentation on Mono-for-Android. I didn't actually make it through all the slides, but we got through a few demos including this simple HelloWorldActivity.cs example and the Restaurant Guide demo.

Also enjoyed @thomasjo's pres on CoffeeScript and Joshua Roth talking about NBuilder.

Sunday, 27 February 2011

Random tip: wtf is"7 CDCs" and debugging on a Samsung Galaxy Tab

Just a quick note on some issues I had debugging a MonoDroid app I've been playing with (MonoDroid is very cool, BTW)... for some reason I couldn't get a Samsumg Galaxy Tab to be recognised as a USB device when connected to my 64-bit Windows 7 PC.

Googling turned up a few different 'ideas' like Samsung Galaxy S Problems, Samsung Kies Software and PC connectivity and Connect Samsung Galaxy S with Kies on your PC - The MTP Error. None of those suggestions worked for me, despite a lot of mucking about with driver installs.

It turned out a hint in this post on USB connection trouble fixed my problem... "somehow" the device's USB port was set to 'modem mode' and I had to type *#7284# on the phone keypad to re-set it! Un-in-tuitive!



The Kies Samsung software/drivers off the Samsung website were fine, once the device was in 'USB mode'.

Anyway, hope that helps someone else...