Scheduled Notifications in Android using Alarm Manager


Few months ago, I wrote an article for DNC Magazine titled “Hello Xamarin.Forms!” which was later republished online on 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.

public void Remind (DateTime dateTime, string title, string message)

	Intent alarmIntent = new Intent(Forms.Context, typeof(AlarmReceiver));
	alarmIntent.PutExtra ("message", message);
	alarmIntent.PutExtra ("title", title);

	PendingIntent pendingIntent = PendingIntent.GetBroadcast(Forms.Context, 0, alarmIntent, PendingIntentFlags.UpdateCurrent);
	AlarmManager alarmManager = (AlarmManager) Forms.Context.GetSystemService(Context.AlarmService);

	//TODO: For demo set after 5 seconds.
	alarmManager.Set(AlarmType.ElapsedRealtime, SystemClock.ElapsedRealtime () + 5 * 1000, pendingIntent);


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.

public class AlarmReceiver : BroadcastReceiver
	public override void OnReceive (Context context, Intent intent)

		var message = intent.GetStringExtra ("message");
		var title = intent.GetStringExtra ("title");

		var notIntent = new Intent (context, typeof(MainActivity));
		var contentIntent = PendingIntent.GetActivity (context, 0, notIntent, PendingIntentFlags.CancelCurrent);
		var manager = NotificationManagerCompat.From (context);

					var style = new NotificationCompat.BigTextStyle();

					int resourceId;
					if (App.SelectedModel.VehicleType == "Car")
						resourceId = Resource.Drawable.Car;
					else if (App.SelectedModel.VehicleType == "Bike")
						resourceId = Resource.Drawable.Bike;
						resourceId = Resource.Drawable.Other;

					var wearableExtender = new NotificationCompat.WearableExtender()
			.SetBackground(BitmapFactory.DecodeResource(context.Resources, resourceId))

					//Generate a notification with just short text and small icon
		var builder = new NotificationCompat.Builder (context)
						.SetContentIntent (contentIntent)
						.SetSmallIcon (Resource.Drawable.ic_launcher)

					var notification = builder.Build();
					manager.Notify(0, notification);

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.

You can download the full source from my GitHub repo.

YouTube Android Player for Xamarin.Android

Xamarin-YouTube-Android-Player 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.

[Update:] See how @xakpc adds async-await feature to his YouTube Thumbnail sample and unleashes the full potential of C#.

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!

Before you start

Get a developer key from Google and register your application. Add your key to the DeveloperKey.cs file

public static class DeveloperKey
 public static string Key = "";

Simple PlayerView

This sample shows how to use a YouTubePlayerView to play a video.

Resource file (PlayerView.axml)

First add the player to your resource file –


In the onCreate() method, instantiate your YouTubePlayerView and initialize it with your DeveloperKey.

YouTubePlayerView youTubeView = FindViewById(Resource.Id.youtube_view);
youTubeView.Initialize(DeveloperKey.Key, this);

To start playing your video cue the video to the player’s playlist.

public override void OnInitializationSuccess (IYouTubePlayerProvider provider, IYouTubePlayer player, bool wasRestored)
if (!wasRestored) {
player.CueVideo("wKJ9KzGQq0w"); }

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.


Hope this helps you!


Say Hello to Nokia X in C# and Visual Studio


Nokia recently introduced the Nokia X family of smartphones, which provides users access to the world of Android. The good news for C# developers is that using Xamarin you can start writing apps for this platform from day 1. If you’re new to building Android apps in C#, do check out my blog post on “How I built an Android app in C# & Visual Studio in less than 24hrs” that I wrote few months back.


Setting things up

The core Nokia X platform is built on Android Open Source Project v4.1.2, which supports API level 16. That means you’ll be targeting API 16(4.1.2) for your app development. You’ll also need to install Nokia X specific packages in the Android SDK Manager.

Configure Nokia X specific packages

Start Android SDK Manager from Visual Studio.

  1. Select Tools > Manage Add-on Sites
  2. Open User Defined Sites tab and click the New… button
  3. Enter the following URL to the Add Add-on Site URL dialog:
  4. Click OK


Install Nokia X specific packages and API level 16

Be sure to install Nokia X System Image under Android 4.1.2(API 16)


You’ll also need to install the following extras:

  • Nokia X Device Definitions
  • Nokia X services
  • Nokia X USB Driver
  • Intel x86 Emulator Accelerator(HAXM) (optional)


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

Nokia-X-Start Nokia-X_running

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.

Nokia X Components

Nokia has shipped Xamarin components for their Nokia X SDK. Don’t forget to check them out at the component store.

Mike Bluestein has a nice post on Nokia HERE Maps component – Use Nokia X HERE Maps with Xamarin.Android.


– Cheers!

How I built an Android app in C# & Visual Studio in less than 24hrs

Yes you read that right! – I built an android app with the tools that I know – Visual Studio and in my favorite language C#. Well that’s possible because of Xamarin. In case you didn’t know – Xamarin was founded by nice engineers(Nat Friedman & Miguel de Icaza of Mono fame) who built MonoTouch and Mono for Android which are cross-platform implementations of Common Language Infrastructure (CLI) and Common Language Specifications.

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.


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.


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.


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.

Here’s an example of a layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
        android:text="@string/Hello" />


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.

namespace HelloXamarin.Android
    [Activity(Label = "HelloXamarin.Android", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
        protected override void OnCreate(Bundle bundle)

           // Set our view from the "main" layout resource

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.

[Activity(Label = "HelloXamarin.Android", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
        private int count = 0;
        protected override void OnCreate(Bundle bundle)

           // Set our view from the "main" layout resource
            // Get our button from the layout resource,
            // and attach an event to it
            Button button = FindViewById<Button>(Resource.Id.MyButton);

            button.Click += delegate { button.Text = string.Format("{0} clicks!", count++); };

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.

          button.Click += (s, e) =>
                    var intent = new Intent(this, typeof(DetailActivity));
                    intent.PutExtra("userCount", count++);

Finally to receive the extra information that was passed from the previous screen you can use Intent.GetStringExtra or other type based methods. Here’s the full code:

    [Activity(Label = "DetailActivity")]
    public class DetailActivity : Activity
        protected override void OnCreate(Bundle bundle)


            var t = FindViewById<TextView>(Resource.Id.textView1);
            t.Text = string.Format("{0}:{1}","You clicked ",Intent.GetIntExtra("userCount", 0));

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

TripXpense – built using Xamarin!


TripXpense has 4 screens

  1. Home Screen – that shows list of trips and you can add more
  2. Trip Edit Screen – add and edit trips
  3. Trip Details Screen – displays trip summary and Expenses
  4. 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!

Have any questions? Find me on twitter – @nishanil

Android WIFI Problem – Obtaining Address…

Ever since I changed my broadband modem, I have been facing issues with my HTC Wildfire connecting to my WIFI router. Every time it connects to my WIFI, it gives a message “Obtaining address..” and its stuck with this message for sometime. Having just a fair knowledge on networking, it took me some steps to reach to a solution. And here it is…

For some of you it may work by simply restarting your WIFI or by restarting your Android device. If it doesn’t, read on to find out if your problem is similar to mine.

Before I jump into the solution, it is important that you understand my network and my devices. My internet broadband modem and WIFI router are two different entities – meaning my modem does not support WIFI routing, so I had to have a WIFI router separately.

  1. Modem – Binatone DT815 ADSL2+ router (supplied by Airtel India)
  2. WIFI Router – Netgear WGR614
  3. From here on for better understanding I will use the term “Modem” to represent my broadband device and “WIFI Router” to represent my WIFI device. Since both the devices are capable of DHCP, I had to disable one to avoid conflicts. I wanted the default gateway to be the modem’s, so I enabled DHCP only on my modem and disabled the other. Modem detects the WIFI router as just another device in its network and not as a router.

    My IP addresses are configured like this:

  1. Modem –
  2. WIFI Router – (Set from router’s LAN Settings)
  3. Other devices which connect, get IPs assigned by the Modem with default gateway as

Whenever I tried connecting my android device to WIFI, it gets stuck at “Obtaining address..”. I knew the problem lies in address resolution, so it was either my device not accepting the IP issued or the modem not recognizing the android.

I logged into Modem’s configuration and checked the LAN Connection pool summary(this setting displays the connected devices and its MAC addresses). To my surprise I found that my android device was issued an IP which was same as my router ( and thus the conflict.

There were two ways I could resolve this conflict:

  1. Change the WIFI router’s IP (from it’s LAN Settings – by logging into WIFI configuration)
  2. Use a Static IP Address in your android device.
    For some reason point 2 never worked for me; but point 1 did. Hope this helps someone.