Xamarin, Android and starting a service at device boot

In my previous post called Xamarin: how to Start an Application at Device Boot in Android, I explained how you can change your Android Xamarin's project to launch your app at the device boot.

It is a good start but my problem was a bit more complex. I want to create a background service to track the geolocation of a device. I googled a lot to find a solution without a great success. Then I started to implement my code with some tests. Finally, I found a good way and I'm sharing with you it.

Create a Broadcast Receiver

What is a Broadcast Receiver

A broadcast receiver is a component that responds to system-wide broadcast announcements. Many broadcasts originate from the system—for example, a broadcast announcing that the screen has turned off, the battery is low, or a picture was captured. Applications can also initiate broadcasts—for example, to let other applications know that some data has been downloaded to the device and is available for them to use. Although broadcast receivers don't display a user interface, they may create a status bar notification to alert the user when a broadcast event occurs. More commonly, though, a broadcast receiver is just a "gateway" to other components and is intended to do a very minimal amount of work.

How to implement a Broadcast Receiver

I show you now two implementations of it:

  • BootReceiver: this receiver is responsible to do something when a device starts. For that, we have to allow the app to read this event. In your AndroidManifest.xml you must add a permission called RECEIVE_BOOT_COMPLETED.
  • AirplaneModeReceiver: this receiver filters only the broadcast for ActionAirplaneModeChanged.

I start to show you the second one because it is more simple.

	[BroadcastReceiver]
    [IntentFilter(new[] { Android.Content.Intent.ActionAirplaneModeChanged })]
	public class AirplaneModeReceiver : BroadcastReceiver
	{
		private static readonly string TAG = typeof(AirplaneModeReceiver).FullName;

		public override void OnReceive(Context context, Intent intent)
		{
			Log.WriteLine(LogPriority.Debug, TAG, "AirplaneModeReceiver OnReceive Mode " + 
                          isAirplaneModeOn(context));
		}

		private static bool isAirplaneModeOn(Context context)
		{
			var airplane = Android.Provider.Settings.Global.GetInt(context.ContentResolver, 
                           Android.Provider.Settings.Global.AirplaneModeOn);
			return airplane != 0;
		}
	}

Although you can find a lot of posts where people said that you have to declare your broadcast in the AndroidManifest, I discover if I add the broadcast in the AndroidManifest, the broadcast won't work.

This is the first broadcast. Basically when a user taps on AirPlaneMode, this broadcast receives the status with isAirplaneModeOn function and writes this change in the logs.

BootReceiver is more interesting. When a device is booting, this broadcast starts a service to track the position. Also, in my code you find TimeService: I use this service to check if the service is starting properly and the notification is working and updating.

    [BroadcastReceiver]
    [IntentFilter(new[] { Android.Content.Intent.ActionBootCompleted })]
    public class BootReceiver : BroadcastReceiver
    {
        private static readonly string TAG = typeof(BootReceiver).FullName;

        public override void OnReceive(Context context, Intent intent)
        {
            Log.WriteLine(LogPriority.Debug, TAG, "BootReceiver OnReceive");

            Intent i = new Intent(context, typeof(GPSService));
            i.AddFlags(ActivityFlags.NewTask);
            context.StartService(i);
            Log.WriteLine(LogPriority.Debug, TAG, 
                          "BootReceiver OnReceive LocationService started");

			i = new Intent(context, typeof(TimerService));
			i.AddFlags(ActivityFlags.NewTask);
			context.StartService(i);
			Log.WriteLine(LogPriority.Debug, TAG, 
                          "BootReceiver OnReceive TimerService started");
		}
    }

The interesting part of this code is when I start a service. Basically, I define a new Intent with the type of service I want to call, then I start the service with the context.

Although you find a lot of posts on line, the right way to define a service in your AndroidManifest is the following:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="pro.wordbank.app.locationtest">
	<uses-sdk android:minSdkVersion="15" />
	<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
	<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
	<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
	<uses-permission android:name="android.permission.INTERNET" />
	<application android:label="LocationTest">
		<service android:name=".TimerService" />
        <service android:name=".LocationService" />
	</application>
</manifest>

I have publish a complete solution of that on GitHub. Happy coding!

Xamarin: how to Start an Application at Device Bootup in Android

This tutorial will explain to stat an application while the Android device boot-up. For this, we need to  listen to the BOOT_COMPLETED action and react to it.

BOOT_COMPLETED is a Broadcast Action that is broadcast once, after the system has finished booting. You can listen to this action by creating a BroadcastReceiver that then starts your launch Activity when it receives an intent with the BOOT_COMPLETED action.

Add this permission to your manifest

In your Android.Manifest you must add thi permission:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

 

BackgroundTest-AndroidManifest

Then open this file and add the following rows under Application:

    <receiver android:name=".BootReceiver" android:enabled="true" 
              android:permission="android.permission.RECEIVE_BOOT_COMPLETED" >
      <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
        <category android:name="android.intent.category.DEFAULT" />
      </intent-filter>
    </receiver>

In this example, we will create a new BroadcastReceiver called BootReceiver.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;

namespace BackgroundTest.Droid.BackgroundServices
{
    public class BootReceiver : BroadcastReceiver
    {
        public override void OnReceive(Context context, Intent intent)
        {
            Intent i = new Intent(context, typeof(MainActivity));
            i.AddFlags(ActivityFlags.NewTask);
            context.StartActivity(i);
        }
    }
}

Install the application, and then restart the device. You can see the application will start after the device restarts. An implementation of background services starting with Activity, it explains here.

Source code on GitHub.

Happy coding!

Eat Cookies!

What are Cookies?

Cookies are data, stored in small text files, on your computer.

When a web server has sent a web page to a browser, the connection is shut down, and the server forgets everything about the user.

Cookies were invented to solve the problem "how to remember information about the user":

  • When a user visits a web page, his name can be stored in a cookie.
  • Next time the user visits the page, the cookie "remembers" his name.

Cookies are saved in name-value pairs like:

username = John Doe

When a browser requests a web page from a server, cookies belonging to the page is added to the request. This way the server gets the necessary data to "remember" information about users.

Function

function deleteCookie(cname) {
    setCookie(name, '', 1);
    document.cookie = name + '=; Expires=Thu, 01 Jan 1970 " + 
                      "00:00:01 GMT; path=/;';
}

function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) === ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) === 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
    var expires = "expires=" + d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires + 
                      "; path=/;";
}

Happy coding!

Bill Gates made these 15 predictions in 1999 — and it's scary how accurate he was

Bill-Gates

After reading ’Business @ the Speed of Thought’, my respect for Bill Gates has increased exponentially. That isn’t to say that I wasn’t a fan of his before. I’ve always been impressed by the strategies that Microsoft carried out in its early days, but that doesn’t come close to how impressed I am now. In this book, published in 1999, Gates outlined how information systems, the Internet, and technology in general would change the way that businesses function. Along the way, he made some incredibly accurate predictions, most of which have since become huge industries: smart phones, smart homes, social networks, and an array of other uses for the Internet-a few of which have yet to be developed.

Gates presents a few key elements for a good information system. While we have to keep in mind that the book was written in the late 90’s, many of these questions are still hardly answered by today’s technology, and present opportunities for new businesses.

Predictions

  1. Automated price comparison services will be developed, allowing people to see prices across multiple websites, making it effortless to find the cheapest product for all industries.
  2. People will carry around small devices that allow them to constantly stay in touch and do electronic business from wherever they are. They will be able to check the news, see flights they have booked, get information from financial markets, and do just about anything else on these devices.
  3. People will pay their bills, take care of their finances, and communicate with their doctors over the Internet.
  4. “Personal companions” will be developed. They will connect and sync all your devices in a smart way, whether they are at home or in the office, and allow them to exchange data. The device will check your email or notifications, and present the information that you need. When you go to the store, you can tell it what recipes you want to prepare, and it will generate a list of ingredients that you need to pick up. It will inform all the devices that you use of your purchases and schedule, allowing them to automatically adjust to what you’re doing.
  5. Constant video feeds of your house will become common, which inform you when somebody visits while you are not home.
  6. Private websites for your friends and family will be common, allowing you to chat and plan for events.
  7. Software that knows when you’ve booked a trip and uses that information to suggest activities at the local destination. It suggests activities, discounts, offers, and cheaper prices for all the things that you want to take part in.
  8. While watching a sports competition on television, services will allow you to discuss what is going on live, and enter contest where you vote on who you think will win.
  9. Devices will have smart advertising. They will know your purchasing trends, and will display advertisements that are tailored toward your preferences.
  10. Television broadcast will include links to relevant websites and content that complement what you are watching.
  11. Residents of cities and countries will be able to have Internet-based discussions concerning issues that affect them, such as local politics, city planning or safety.
  12. Online communities will not be influenced by your location, but rather, your interest.
  13. Project managers looking to put a team together will be able to go online, describe the project, and receive recommendations for available people who would fit their requirements.
  14. Similarly, people looking for work will be able to find employment opportunities online by declaring their interest, needs, and specialized skills.
  15. Companies will be able to bid on jobs, whether they are looking for a construction project, a movie production, or an advertising campaign. This will be efficient for both big companies that want to outsource work that they don’t usually face, businesses looking for new clients, and corporations that don’t have a go-to provider for the said service.

The original post is here.

Advertsing

125X125_06

Planet Xamarin

Planet Xamarin

Calendar

<<  November 2017  >>
MonTueWedThuFriSatSun
303112345
6789101112
13141516171819
20212223242526
27282930123
45678910

View posts in large calendar

Month List