Xamarin Insights for Older Androids

Recently, Xamarin announced a real-time crash reporting and analytics solution for mobile apps, Xamarin Insights.

This is an awesome tool with many great features. They support all the major platforms, iOS Android Windows Phone, Windows RT and traditional desktop applications. Support for Xamarin.Mac is coming soon.

Some of the major features:

  • Report details about the device statistics such as operating system and screen resolution
  • Gather and report any uncaught native or managed exceptions
  • Report any caught exception, along with any additional data
  • Track both past and active sessions
  • Track any event that occurs in your application, including the time it takes to execute
  • Cross-platform across almost all devices, including support for PCL libraries

Old Androids

Recently they added support for Android versions below API level 14 (Android Version 4.0 – Ice Cream Sandwich). To use Xamarin Insights in an Android app below API level 14, such as API Level 8 (Android Version 2.3 – Gingerbread), there are a few things that need to happen:

  1. Set your ‘Compile using Android version’ or ‘Target framework’ value to be API level 14 or higher, such as API level 19
  2. Set the ‘Minimum Android to target’ or ‘Minimum Android version’ to be the value you are wanting to support, such as API level 8.

This will result in your app building against the higher API level, but can run on earlier devices.

However, even after all this, there is still a limitation, namely the inability to record sessions. This may not be a deal breaker for you, but for some, this is. The reason for this is that Xamarin Insights is using the IActivityLifecycleCallbacks interface. This is a relatively new addition to the Android API and is very useful in that it allows you to hook into the Activity lifecycle without having to use the Activity itself. As this interface is not available for the older versions, they simple can’t record the Activity sessions.

The Code

I am here to give you that solution that you always wanted: Manually starting and stopping sessions from within the activity. To do this I have created a simple class InsightsCompat:

    public static class InsightsCompat
    {
        public static void Initialize(string apiKey)
        {
            Insights.Initialize(apiKey, Application.Context);
        }

        public static void StartSession()
        {
            EmitBackgroundChange(false);
        }

        public static void StopSession()
        {
            EmitBackgroundChange(true);
        }

        private static void EmitBackgroundChange(bool backgroundState)
        {
            try
            {
                var status = backgroundState ? "Background" : "Resumed";
                var table = new Dictionary<string, string> {{"Status", status}};
                Insights.Track("X-App-State", table);
            }
            catch (Exception ex)
            {
                Insights.Report(ex);
            }
        }
    }

The Usage

This simple class can do all the work that is needed, plus there is an additional method, Initialize, that allows you to start up Xamarin Insights without having to find the context:

    // from anywhere in your code
    InsightsCompat.Initialize("your API key");

To start and stop sessions, you can override the OnResume and OnPause methods:

    protected override void OnPause()
    {
        InsightsCompat.StopSession();
        base.OnPause();
    }

    protected override void OnResume()
    {
        base.OnResume();        
        InsightsCompat.StartSession();
    }

We only have to override these two methods as android will always call these methods, no matter where the Activity came from or where it is going.

There’s More

Even though Xamarin Insights has many features, it is still in preview and there can still be many more features. If you have any feature requests or ideas, be sure to drop a message on the Xamarin Insights User Voice.

There is a small docs page for Xamarin Insights here. So head over to the dashboard and get started creating and supporting awesome cross-platform apps now.

Flurry Analytics Portable

We all know about Flurry Analytics, and we know how we can use this with Xamarin in iOS and Android, as well as on Windows Phone.

Well, now there is a portable version that allows the analytics to be implemented in portable class libraries! The portable API abstracts away all the platform differences, but keeps all the power of the Flurry!

This can be found on NuGet and on GitHub.

Features

The features of the portable API are the same as the native API’s, as the portable is more of an abstraction than anything else. So along with all the native features, there are a few nice new once that make the API easier to use.

This is the primary advantage of this library, it allows the analytics to be implemented in portable projects. This is especially useful if you are using a cross-platform framework, such as MvvmCross. There is a sample that you can check out that makes use of all the features.

Starting Sessions

Although the library is portable, each platform needs to start the analytics session natively/differently:

For iOS, it is very simple call StartSession from the AppDelegate:

    AnalyticsApi.StartSession("[API KEY]");

For Android, there are two ways to do this. Either by overriding the OnStart and OnStop methods from each Activity:

    // in OnStart
    AnalyticsApi.StartSession(this, "[API KEY]");

    // in OnStop
    Analytics.EndSession(this);

Or, by using the IActivityLifecycleCallbacks for the Application. This way allows you to start and end the session without having to implement the logic in each Activity. However it is only available from API Level 14 / Android 4.0 / Ice Cream Sandwich.

For Windows Phone, starting the session is done by attaching the StartSession method call to the Launching and Activated events:

    PhoneApplicationService.Current.Launching += (sender, args) => AnalyticsApi.StartSession();
    PhoneApplicationService.Current.Activated += (sender, args) => AnalyticsApi.StartSession();

For each of the platforms, there is also a way to pass the key in to the API, but only start the session later:

    // somewhere in the code
    AnalyticsApi.ApiKey = "[API KEY]";

    // and then a little later
    AnalyticsApi.StartSession();

There is also a boolean property, IsSupported, that will return true if the platform supports Flurry Analytics:

    if (!Analytics.IsSupported)
        Debug.WriteLine("PLatform does not support Flurry, nothing will be tracked.");

Setting Up Analytics

There are a few methods that hide the platform differences. Some examples of this are in the setting of user details, such as SetAppVersion, SetUserId, SetLocation, SetAge and SetGender.

Not only that, there are a few methods that specify how Flurry should communicate, such as SetSessionContinueTimeout and EnableSecureTransport.

Usually these methods should be called before starting the session.

Logging Events & Errors

Along with tracking basic analytics, events and errors can be tracked. There are a few methods that support this: LogPageView, LogEvent, LogTimedEvent, EndTimedEvent and LogError.

Logging timed events has been made much easier by implementing a new pattern for doing this. By calling LogTimedEvent in a using block, you can end the event in case of any exceptions as well as removing an extra call:

    using (AnalyticsApi.LogTimedEvent("EventId"))
    { 
        // perform a long running task
    } 

Before, you would have to ensure that you called EndTimedEvent to avoid any problems:

    try
    {
        AnalyticsApi.LogTimedEvent("EventId");
        // perform the long running task
    }
    finally
    {
        AnalyticsApi.LogTimedEvent("EventId");
    }

Parameters can also be passed with the events using a simple Dictionary:

    var parameters = new Dictionary<string, string> 
    {
        {"ParameterKey", "ParameterValue"}
        {"AnotherParameterKey", "AnotherParameterValue"}
    };
    AnalyticsApi.LogEvent("EventId", parameters);

Flurry.Analytics for Xamarin

The Flurry Analytics Agent allows you to track the usage and behavior of your Android, iOS or Windows Phone application on users’ phones for viewing in the Flurry Analytics system. It is designed to be as easy as possible with a basic setup complete in few minutes.

Features

There are many features available in the Flurry Analytics API, such as:

  • Session tracking
  • Event logging, with optional parameters
  • Page View tracking
  • Demographics tracking, such as age, gender and user id
  • Location tracking
  • App version tracking
  • And much more…

Getting Started

The setup for all the platforms is very easy with only a few steps:

Android

  1. Add the INTERNET permission to AndroidManifest.xml.
  2. Add FlurryAgent.OnStartSession(this, "YOUR_API_KEY"); to the OnStart method of the Activity or Service.
  3. Add FlurryAgent.OnEndSession(this); to the OnStop method of the Activity or Service.

iOS

  1. Add FlurryAgent.StartSession("YOUR_API_KEY"); to the FinishedLaunching method of the Application Delegate

Windows Phone

  1. Add ID_CAP_NETWORKING and ID_CAP_IDENTITY_DEVICE capabilities to WMAppManifest.xml.
  2. Add FlurryWP8SDK.Api.StartSession("YOUR_API_KEY"); to Launching and Activated events of the Application.

And that’s it, your mobile app will start sending activity usage statistics to the Flurry servers!

Advanced

Flurry Analytics SDK supported versions:

  • SDK for iOS supports Xcode tools 4.5 and above
  • SDK for Android supports Android API level 10 (Gingerbread) and above
  • SDK for Windows Phone supports Windows Phone 8 and above

Downloading

The Flurry.Analytics API is available on NuGet.org (Flurry.Analytics) and on GitHub (mattleibow/Flurry.Analytics).

It is released under the same license as the native libraries.

The Making Of

You can read up on how the binding was created in my blog:

  1. Introduction and Pre-requisites
  2. Xamarin.iOS binding
  3. Xamarin.Android binding
  4. Flurry.Analytics in the wild