James Montemagno: Access the Current Android Activity from Anywhere!

In the world of Android one of my biggest pain points over the years is that often you need access to the apps current Activity when writing libraries or abstracting out common functionality. For years I have been hacking around the issue by setting special Intent flags or more than likely creating a BaseActivity with a static “CurrentActivity” that is set when the page is started up. While this works short term for MY app, it completely falls down when you want to create Plugins or abstract an API into an interface of some sort. 

 When it comes down to it you just need that Activity, and it should be easy! This is why I have solve the issue once and for all with a secret hidden API that Google snuck in during the release of Ice Cream Sandwich (API 14) called ActivityLifecycleCallbacks. This is super undocumented, but from what Jérémie and I can gather Google introduced this so you can at any time figure out what the current activity. It must be implemented on your apps “Application” class and call RegisterActivityLifecycleCallbacks. After this though, you are all done. 

So, let me introduce to you my latest Plugin for Xamarin.Android called “CurrentActivity“. 

You guessed it, this plugin does 1 thing, lets you get access to the current activity. In fact the entire API is just 1 property:


/// The Current Activity
Activity Activity { get; set; }

The magic of this NuGet package and Plugin is that when you install it or if you are using it as a dependency in your own Plugin is that it lays down a “MainApplication.cs” file that ties into and implements the ActivityLifecycleCallbacks. BOOM! Done! Here is what that looks like:


using System;
using Android.App;
using Android.OS;
using Android.Runtime;
using Plugin.CurrentActivity;

namespace $rootnamespace$
{
	//You can specify additional application information in this attribute
    [Application]
    public class MainApplication : Application, Application.IActivityLifecycleCallbacks
    {
        public MainApplication(IntPtr handle, JniHandleOwnership transer)
          :base(handle, transer)
        {
        }

        public override void OnCreate()
        {
            base.OnCreate();
            RegisterActivityLifecycleCallbacks(this);
            //A great place to initialize Xamarin.Insights and Dependency Services!
        }

        public override void OnTerminate()
        {
            base.OnTerminate();
            UnregisterActivityLifecycleCallbacks(this);
        }

        public void OnActivityCreated(Activity activity, Bundle savedInstanceState)
        {
            CrossCurrentActivity.Current.Activity = activity;
        }

        public void OnActivityDestroyed(Activity activity)
        {
        }

        public void OnActivityPaused(Activity activity)
        {
        }

        public void OnActivityResumed(Activity activity)
        {
            CrossCurrentActivity.Current.Activity = activity;
        }

        public void OnActivitySaveInstanceState(Activity activity, Bundle outState)
        {
        }

        public void OnActivityStarted(Activity activity)
        {
            CrossCurrentActivity.Current.Activity = activity;
        }

        public void OnActivityStopped(Activity activity)
        {
        }
    }
}

Then if you want to access the current activity anywhere in your Android application, library, or plugin simply call: CrossCurrentActivity.Current.Activity and you will have the current activity.

If you already have subclassed Application, don’t worry as you can just copy and paste some code that I put in a readme text file in the project, or head over to my GitHub and learn more!

Details

Xamarin: Contest: Show Us Your Favorite Xamarin 4 Feature!

In case you missed it, earlier this week we announced a major release – Xamarin 4. Xamarin 4 is all about empowering you with everything you need to create great mobile apps. We have made major enhancements to the way you build apps with the Xamarin Platform in Xamarin 4, such as Xamarin.Forms 2.0, rebuilt […]

The post Contest: Show Us Your Favorite Xamarin 4 Feature! appeared first on Xamarin Blog.

Details

Greg Shackles: Easily Instrument HTTP Calls in Your Apps

Lately I’ve been doing a lot of work around adding instrumentation to basically all the things, which naturally includes my apps. It’s common practice to instrument things on the server-side of the API using awesome tools like NewRelic, but that’s only part of the equation. Obviously we need the server to respond as quickly as possible so being aware of that metric is essential, but on top of that the user also has to wait for that request to get to the server and back over networks that are often pretty slow. How long are you making users watch a loading spinner for when they’re trying to get something done?

Depending on what your apps are doing it probably makes sense to instrument more than just HTTP calls to be able to get some visibility into this, but I’ll just start with HTTP here. When I was spiking some ideas on how to implement this I went down a few different paths before I realized I was overlooking the most obvious/simple solution that we’ll go through here.

HttpClient and HttpMessageHandler

If you’re using HttpClient to make your HTTP calls (if you’re not, you probably should be!), you may or may not know that it has a constructor that takes in a HttpMessageHandler instance. The awesome part about that is that it means we can create a simple class that will be inserted into the pipeline of every HTTP call being made from that HttpClient instance.

Here’s what that a simple implementation might look like:

class InstrumentedHttpClientHandler : HttpClientHandler  
{
  protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
  {
    var successful = false;
    var stopwatch = Stopwatch.StartNew();

    try
    {
      var result = await base.SendAsync(request, cancellationToken);
      successful = result.IsSuccessStatusCode;

      return result;
    }
    finally
    {
      stopwatch.Stop();

      // TODO: publish metric
    }
  }
}

This implementation simply wraps the base implementation of SendAsync with a stopwatch so the behavior will be the same except that now you’ll get access to how long the call took via stopwatch.ElapsedMilliseconds, and whether or not it was successful. One thing to be careful of when adding instrumentation is that you don’t want to slow things down any more than necessary in order to measure it. In this case there’s minimal overhead, especially when dealing with network calls that will reliably take a decent chunk of time anyway.

With this data you can now publish your metrics in whatever way makes sense for your application, be it to the device logs, an API, etc. Not only is it useful to know how you’re performing right now, it’s even more important to know how you’re trending over time? Did your last release make things better or worse? Without tracking it you’ll never know.

ModernHttpClient

If you’re using ModernHttpClient (again, if you’re not, you should be!) you may have noticed that this is the same approach used by that library to intercept requests happening in HttpClient. You can still take advantage of this instrumentation approach if you’re using ModernHttpClient. In fact, all you need to do is change the base class of InstrumentedHttpClientHandler to ModernHttpClient’s NativeMessageHandler and you’re all set!

Details

Adam J Wolf: Weekly Xamarin Newsletter Issue #67

Get Started with Xamarin 4 Today Bryan Costanich, from Xamarin Inc., invites you to get up to speed on Xamarin 4.0. Introducing Xamarin 4: Everything You Need to Build Great Apps Nat Friedman, from Xamarin Inc., announces Xamarin 4. Sort ListView Alphabetically in Xamarin Android Val Okafor shows his LINQ powers in this ListView demo. […]

The post Weekly Xamarin Newsletter Issue #67 appeared first on Syntax is my UI.

Details

Xamarin: Get Started with Xamarin 4 Today

Xamarin 4 is a fantastic release, designed to make building apps with Xamarin faster, easier, and more delightful than ever before, and the Xamarin Education team has worked incredibly hard to deliver the resources you need to get up and running with it. In both the documentation and Xamarin University teams, we have created a […]

The post Get Started with Xamarin 4 Today appeared first on Xamarin Blog.

Details

Greg Shackles: Pluralsight: Beginning Automated Testing of Xamarin Applications

Recently I had the pleasure of working with my friend Jesse Liberty on a new Pluralsight course focused on helping you get started building Xamarin apps in a test-driven fashion. In under an hour he walks you through building out a real app using tests right from the start, running those tests on both iOS and Android, and also getting into writing UI tests to run locally as well as in Test Cloud.

If you’re looking for a good way to see testing in action with mobile development, please check it out!

Beginning Automated Testing of Xamarin Applications

Details