For the next four recipes, we will use Intents to build the application imagined by Vince Vaughn in the movie The Internship. This application is fairly simple and can be summarized as follows. If you send a text message to someone between 12 a.m. and 6 a.m., well, it is probably a bad idea as you might be quite influenced by alcohol. The solution? You have to solve an equation to prove that you're OK!
On a serious note, here's what we will have to do:
In this recipe, we start with the building of our application by getting the time of the day using a broadcast receiver.
We will do the time monitoring using the following steps:
[BroadcastReceiver] public class TimeReceiver : BroadcastReceiver { public override void OnReceive (Context context, Intent intent) { Console.WriteLine ("Time Received"); //If we are in the dangerous timeframe if (DateTime.Now.Hour >= 0 && DateTime.Now.Hour <= 6) { Console.WriteLine ("We are in the dangerous hours"); } } }
TimeReceiver
class as a TimeTick
broadcast receiver in the OnCreate()
method of your MainActivity
class:protected override void OnCreate (Bundle bundle) { base.OnCreate (bundle); //Register our broadcast receiver. It will be triggered when the time change, every minute. RegisterReceiver (new TimeReceiver (), new IntentFilter (Intent.ActionTimeTick)); }
Console.WriteLine ("Time Received"); Console.WriteLine ("We are in the dangerous hours");
The TimeReceiver
class extends the BroadcastReceiver
class. The BroadcastReceiver
class is a base class that can intercept intent broadcast calls. Android OS contains a huge number of intent broadcast calls, such as onBootCompleted
and onTimeChanged
, which we use in this recipe.
With the following statement, we check if the current time is between 12 a.m. and 6 a.m. and print a logging line to the console if this is the case.
if (DateTime.Now.Hour >= 0 && DateTime.Now.Hour <= 6) { Console.WriteLine ("We are in the dangerous hours"); }
This code takes place in the OnReceive()
method and is called every minute. Indeed, the ActionTimeTick
broadcast call also happens every minute. Nonetheless, for our BroadcastReceiver
class to actually receive broadcast calls, we have to register it. This is what we did in the MainActivity
class with the following statements:
RegisterReceiver (new TimeReceiver (), new IntentFilter (Intent.ActionTimeTick));
The RegisterReceiver()
method is responsible for registering a new receiver that can be set for broadcast calls or local calls. In our case, we register a new TimeReceiver
object, and we add an IntentFilter
argument specifying that our receiver is only interested in the ActionTimeTick
broadcast call.
3.149.214.32