mozilla

Revision 453221 of Api de Alarma

  • Revision slug: WebAPI/Alarm
  • Revision title: Api de Alarma
  • Revision id: 453221
  • Created:
  • Creator: ccarruitero
  • Is current revision? No
  • Comment

Revision Content

{{ SeeCompatTable() }}

Resumen

La API de Alarma provee acceso a la configuración de alarmas del dispositivo, con la cual se puede programar una notificación o una aplicación para que se inicie en un momento específico. Por ejemplo, algunas aplicaciones, como el despertador, calendario o actualizaciones automáticas necesitan utilizar la API de alarma para activar comportamientos particulares del dispositivo en los tiempos especificados.

Por si mismo, la API de alarmas solo permite programar alarmas. Una alarma es enviada a las aplicaciones a través de la API de mensaje del sistema, entonces las aplicaciones que desean reaccionar a las alarmas tienen que registrarse en los mensajes de alarma.

Las alarmas son establecidas usando el objeto {{domxref("window.navigator.mozAlarms")}}, el cual es una instancia de {{domxref("MozAlarmsManager")}}.

Cronograma alarmas

Lo primero ha hacer cuando usas alarmas

The first things to do when using alarm is to schedule alarms. There are two kind of alarms based on the respect of the time zone. In both case it's done using the {{domxref("MozAlarmsManager.add")}} method.

Note: If an alarm is not targeted at a specific application, the system will dispatch all the alarms to all the applications listening for alarms.

Alarms ignoring time zones

Those kind of alarms is dispatched based on the local time of the device. If the user of the device changes its time zone, the alarm will be dispatched based on the new time zone. For example, if a user is in Paris and sets an alarm that should be dispatched at 12 PM CET (Central European Time) and that user travels to San Francisco, the alarm will be dispatched at 12 PM PDT (Pacific Daylight Time).

// This the date to schedule the alarm
var myDate  = new Date("May 15, 2012 16:20:00");

// This is arbitrary data pass to the alarm
var data    = {
  foo: "bar"
}

// The "ignoreTimezone" string is what make the alarm ignoring it
var request = navigator.mozAlarms.add(myDate, "ignoreTimezone", data);

request.onsuccess = function () {
  console.log("The alarm has been scheduled");
};

request.onerror = function () { 
  console.log("An error occurred: " + this.error.name);
};

Alarms honoring time zones

Those kind of alarms are dispatched based on the time in the time zone that defines when the alarm has been scheduled. If for some reason, the user of the device changes its time zone the alarm will be dispatched based on the original time zone. For example, if a user is in Paris and set an alarm that should be dispatched at 12pm CET (Central European Time) and if that user travel to San Francisco, the alarm will be dispatched at 3 AM PDT (Pacific Daylight Time).

// This the date to schedule the alarm
var myDate  = new Date("May 15, 2012 16:20:00");

// This is arbitrary data pass to the alarm
var data    = {
  foo: "bar"
}

// The "honorTimezone" string is what make the alarm honoring it
var request = navigator.mozAlarms.add(myDate, "honorTimezone", data);

request.onsuccess = function () {
  console.log("The alarm has been scheduled");
};

request.onerror = function () { 
  console.log("An error occurred: " + this.error.name);
};

Managing alarms

Once an alarm is scheduled, it's still possible to manage it.

The {{domxref("MozAlarmsManager.getAll")}} method will return the complete list of alarms currently scheduled by the application. This list is an Array of {{Anch("mozAlarm")}} objects.

mozAlarm

{{page("/en-US/docs/Web/API/MozAlarmsManager.getAll","mozAlarm")}}

var request = navigator.mozAlarms.getAll();

request.onsuccess = function () {
  this.result.forEach(function (alarm) {
    console.log('Id: ' + alarm.id);
    console.log('date: ' + alarm.date);
    console.log('respectTimezone: ' + alarm.respectTimezone);
    console.log('data: ' + JSON.stringify(alarm.data));
  });
};

request.onerror = function () { 
  console.log("An error occurred: " + this.error.name);
};

The {{domxref("MozAlarmsManager.remove")}} method is used to unschedule an existing alarm.

var alarmId;

// Set an alarm and store it's id
var request = navigator.mozAlarms.add(new Date("May 15, 2012 16:20:00"), "honorTimezone");

request.onsuccess = function () {
  alarmId = this.result.id;
}

// ...

// Later on, removing the alarm if it exists
if (alarmId) {
  navigator.mozAlarms.remove(alarmId);
}

Handling alarms

Any application can react when an alarm is dispatched by the system. In order to be able to handle any alarms, an application must register itself as an alarm handler. This is done through the System Messaging API in two steps:

First, the applications must include alarm to the messages property of its application manifest with the URL to the document which registers the callback function to be used when an alarm is dispatched.

"messages": [
  { "alarm": "/index.html" }
]

Second, the application must bind a callback function with the alarm message. This is done using the {{domxref("window.navigator.mozSetMessageHandler","navigator.mozSetMessageHandler")}} method. This callback function will receive a {{Anch("mozAlarm")}} object containing the data attached to the alarm.

navigator.mozSetMessageHandler("alarm", function (mozAlarm) { 
  alert("alarm fired: " + JSON.stringify(mozAlarm.data)); 
});

If an application wants to know if there is a pending alarm at the system level, it's possible to use the {{domxref("window.navigator.mozHasPendingMessage","navigator.mozHasPendingMessage")}} method with the value alarm.

navigator.mozHasPendingMessage("alarm"); 

Specifications

Specification Status Comment
{{SpecName('Alarm API')}} {{Spec2('Alarm API')}} Initial specification.

Browser compatibility

{{ CompatibilityTable() }}

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support {{ CompatUnknown()}} {{CompatGeckoDesktop("16")}} {{ property_prefix("moz") }} {{ CompatNo() }} {{ CompatNo() }} {{ CompatNo() }}
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support {{ CompatUnknown() }} {{ CompatNo() }} {{CompatGeckoMobile("10")}} {{ property_prefix("moz") }} {{ CompatNo() }} {{ CompatNo() }} {{ CompatNo() }}

See also

  • {{domxref("window.navigator.mozAlarms","navigator.mozAlarms")}}
  • {{domxref("MozAlarmsManager")}}
  • {{domxref("window.navigator.mozSetMessageHandler")}}

Revision Source

<p>{{ SeeCompatTable() }}</p>
<h2 id="Resumen">Resumen</h2>
<p>La <span class="external">API</span> de Alarma provee acceso a la configuración de alarmas del dispositivo, con la cual se puede programar una notificación o una aplicación para que se inicie en un momento específico. Por ejemplo, algunas aplicaciones, como el despertador, calendario o actualizaciones automáticas necesitan utilizar la API de alarma para activar comportamientos particulares del dispositivo en los tiempos especificados.</p>
<p>Por si mismo, la API de alarmas solo permite programar alarmas. Una alarma es enviada a las aplicaciones a través de la API de mensaje del sistema, entonces las aplicaciones que desean reaccionar a las alarmas tienen que registrarse en los mensajes de alarma.</p>
<p>Las alarmas son establecidas usando el objeto {{domxref("window.navigator.mozAlarms")}}, el cual es una instancia de {{domxref("MozAlarmsManager")}}.</p>
<h2 id="example" name="example">Cronograma alarmas</h2>
<p>Lo primero ha hacer cuando usas alarmas</p>
<p>The first things to do when using alarm is to schedule alarms. There are two kind of alarms based on the respect of the time zone. In both case it's done using the {{domxref("MozAlarmsManager.add")}} method.</p>
<div class="note">
  <p><strong>Note:</strong> If an alarm is not targeted at a specific application, the system will dispatch all the alarms to all the applications listening for alarms.</p>
</div>
<h3 id="Alarms_ignoring_time_zones">Alarms ignoring time zones</h3>
<p>Those kind of alarms is dispatched based on the local time of the device. If the user of the device changes its time zone, the alarm will be dispatched based on the new time zone. For example, if a user is in Paris and sets an alarm that should be dispatched at 12 PM CET (<em>Central European Time</em>) and that user travels to San Francisco, the alarm will be dispatched at 12 PM PDT (<em>Pacific Daylight Time</em>).</p>
<pre class="brush: js">
// This the date to schedule the alarm
var myDate  = new Date("May 15, 2012 16:20:00");

// This is arbitrary data pass to the alarm
var data    = {
  foo: "bar"
}

// The "ignoreTimezone" string is what make the alarm ignoring it
var request = navigator.mozAlarms.add(myDate, "ignoreTimezone", data);

request.onsuccess = function () {
  console.log("The alarm has been scheduled");
};

request.onerror = function () { 
  console.log("An error occurred: " + this.error.name);
};
</pre>
<h3 id="Alarms_honoring_time_zones">Alarms honoring time zones</h3>
<p>Those kind of alarms are dispatched based on the time in the time zone that defines when the alarm has been scheduled. If for some reason, the user of the device changes its time zone the alarm will be dispatched based on the original time zone. For example, if a user is in Paris and set an alarm that should be dispatched at 12pm CET (<em>Central European Time</em>) and if that user travel to San Francisco, the alarm will be dispatched at 3 AM PDT (<em>Pacific Daylight Time</em>).</p>
<pre class="brush: js">
// This the date to schedule the alarm
var myDate  = new Date("May 15, 2012 16:20:00");

// This is arbitrary data pass to the alarm
var data    = {
  foo: "bar"
}

// The "honorTimezone" string is what make the alarm honoring it
var request = navigator.mozAlarms.add(myDate, "honorTimezone", data);

request.onsuccess = function () {
  console.log("The alarm has been scheduled");
};

request.onerror = function () { 
  console.log("An error occurred: " + this.error.name);
};
</pre>
<h2 id="Managing_alarms">Managing alarms</h2>
<p>Once an alarm is scheduled, it's still possible to manage it.</p>
<p>The {{domxref("MozAlarmsManager.getAll")}} method will return the complete list of alarms currently scheduled by the application. This list is an <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" title="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array">Array</a></code> of {{Anch("mozAlarm")}} objects.</p>
<h3 id="mozAlarm">mozAlarm</h3>
<p>{{page("/en-US/docs/Web/API/MozAlarmsManager.getAll","mozAlarm")}}</p>
<pre class="brush: js">
var request = navigator.mozAlarms.getAll();

request.onsuccess = function () {
  this.result.forEach(function (alarm) {
    console.log('Id: ' + alarm.id);
    console.log('date: ' + alarm.date);
    console.log('respectTimezone: ' + alarm.respectTimezone);
    console.log('data: ' + JSON.stringify(alarm.data));
  });
};

request.onerror = function () { 
  console.log("An error occurred: " + this.error.name);
};
</pre>
<p>The {{domxref("MozAlarmsManager.remove")}} method is used to unschedule an existing alarm.</p>
<pre class="brush: js">
var alarmId;

// Set an alarm and store it's id
var request = navigator.mozAlarms.add(new Date("May 15, 2012 16:20:00"), "honorTimezone");

request.onsuccess = function () {
  alarmId = this.result.id;
}

// ...

// Later on, removing the alarm if it exists
if (alarmId) {
  navigator.mozAlarms.remove(alarmId);
}
</pre>
<h2 id="Handling_alarms">Handling alarms</h2>
<p>Any application can react when an alarm is dispatched by the system. In order to be able to handle any alarms, an application must register itself as an alarm handler. This is done through the System Messaging API in two steps:</p>
<p>First, the applications must include <code>alarm</code> to the <a href="/en-US/docs/Apps/Manifest#messages" title="/en-US/docs/Apps/Manifest#messages">messages property of its application manifest</a> with the URL to the document which registers the callback function to be used when an alarm is dispatched.</p>
<pre class="brush: js">
"messages": [
  { "alarm": "/index.html" }
]</pre>
<p>Second, the application must bind a callback function with the <code>alarm</code> message. This is done using the {{domxref("window.navigator.mozSetMessageHandler","navigator.mozSetMessageHandler")}} method. This callback function will receive a {{Anch("mozAlarm")}} object containing the data attached to the alarm.</p>
<pre class="brush: js">
navigator.mozSetMessageHandler("alarm", function (mozAlarm) { 
  alert("alarm fired: " + JSON.stringify(mozAlarm.data)); 
});
</pre>
<p>If an application wants to know if there is a pending alarm at the system level, it's possible to use the {{domxref("window.navigator.mozHasPendingMessage","navigator.mozHasPendingMessage")}} method with the value <code>alarm</code>.</p>
<pre class="brush: js">
navigator.mozHasPendingMessage("alarm"); 
</pre>
<h2 id="Specifications">Specifications</h2>
<table class="standard-table">
  <thead>
    <tr>
      <th scope="col">Specification</th>
      <th scope="col">Status</th>
      <th scope="col">Comment</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>{{SpecName('Alarm API')}}</td>
      <td>{{Spec2('Alarm API')}}</td>
      <td>Initial specification.</td>
    </tr>
  </tbody>
</table>
<h2 id="Browser_compatibility">Browser compatibility</h2>
<p>{{ CompatibilityTable() }}</p>
<div id="compat-desktop">
  <table class="compat-table">
    <tbody>
      <tr>
        <th>Feature</th>
        <th>Chrome</th>
        <th>Firefox (Gecko)</th>
        <th>Internet Explorer</th>
        <th>Opera</th>
        <th>Safari</th>
      </tr>
      <tr>
        <td>Basic support</td>
        <td>{{ CompatUnknown()}}</td>
        <td>{{CompatGeckoDesktop("16")}} {{ property_prefix("moz") }}</td>
        <td>{{ CompatNo() }}</td>
        <td>{{ CompatNo() }}</td>
        <td>{{ CompatNo() }}</td>
      </tr>
    </tbody>
  </table>
</div>
<div id="compat-mobile">
  <table class="compat-table">
    <tbody>
      <tr>
        <th>Feature</th>
        <th>Android</th>
        <th>Chrome for Android</th>
        <th>Firefox Mobile (Gecko)</th>
        <th>IE Mobile</th>
        <th>Opera Mobile</th>
        <th>Safari Mobile</th>
      </tr>
      <tr>
        <td>Basic support</td>
        <td>{{ CompatUnknown() }}</td>
        <td>{{ CompatNo() }}</td>
        <td>{{CompatGeckoMobile("10")}} {{ property_prefix("moz") }}</td>
        <td>{{ CompatNo() }}</td>
        <td>{{ CompatNo() }}</td>
        <td>{{ CompatNo() }}</td>
      </tr>
    </tbody>
  </table>
</div>
<h2 id="See_also">See also</h2>
<ul>
  <li>{{domxref("window.navigator.mozAlarms","navigator.mozAlarms")}}</li>
  <li>{{domxref("MozAlarmsManager")}}</li>
  <li>{{domxref("window.navigator.mozSetMessageHandler")}}</li>
</ul>
Revert to this revision