Firefox OS alarm to wake up closed app - javascript

Looking at documentation it looks like the alarm api can be used to restart an app at a certain time
I changed the code from boilerplate example in this way
// Alarm API
var alarmDate = new Date("Jul 8, 2014 19:35:00"),
addAlarm = document.querySelector("#add-alarm"),
alarmDisplay = document.querySelector("#alarm-display");
if (addAlarm) {
addAlarm.onclick = function () {
var alarm = navigator.mozAlarms.add(alarmDate, "honorTimezone", {
"optionalData" : "I am data"
});
alarm.onsuccess = function () {
var request = window.navigator.mozApps.getSelf();
request.onsuccess = function() {
navigator.mozSetMessageHandler("alarm", function (mozAlarm) {
request.result.launch();
alert("alarm fired: " + JSON.stringify(mozAlarm.data));
});
};
request.onerror = function() {
alert("Error: " + request.error.name);
};
};
The code seems to bring up the app only if the app is running (even in background) BUT not if the app is closed.
Is this the intended behaviour? Any way to restart a closed app?
Also is it possible to bring up the app in foreground and make it unlock the screen?
Thanks
UPDATE
Just as a clarification, the issue appears when the system memory load requires killing an app. Android provides a way to schedule restart of an app (while iOS, afaik, does not...).
It would be useful if an app could be restarted at the moment in which it's required.
That's also saving a lot of battery...

Your code is wrong: the setMessageHandler is created in the onsuccess handler of mozAlarms.add. That code will not be executed when the alarm fires. You need to always add the listener on app startup.
Here's some simple code that adds and responds to an alarm (from app-days-dhaka).
var request = navigator.mozAlarms.add(new Date((+new Date()) + 30000), 'ignoreTimezone', {
type: 'yolo'
});
console.log('setting to', new Date((+new Date()) + 30000) + '')
request.onsuccess = function() {
console.log('success');
}
request.onerror = function() {
console.error('err');
}
navigator.mozSetMessageHandler('alarm', function() {
console.log('alarm');
launchSelf();
});
function launchSelf() {
var request = window.navigator.mozApps.getSelf();
request.onsuccess = function() {
if (request.result) {
request.result.launch();
}
};
}
Open the app (this will set the alarm), then close the app immediately (via long press on home). After 30 seconds the app will open again automatically.

Related

Why Websocket connection is disconneting after sending message on iOS 15 devices?

I am building a website based on web socket communication. Its is working fine until iOS 14 but started breaking from iOS 15. Web socket java script client is able to open connection to server, but upon trying to send a message, the connection is getting closed. Following is my html and JS code.
function start_websocket() {
connection = new WebSocket("wss://localhost/wss/");
connection.onopen = function () {
console.log('Connection Opened');
};
connection.onerror = function (error) {
console.log('WebSocket Error ' + error);
};
connection.onclose = function(){
console.log("Closed");
};
connection.onmessage = function (e) {
console.log("Message Received :" + e.data);
};
}
function myFunction() {
var testText = document.getElementById("testText");
if (testText.value != "" && connection.readyState === connection.OPEN) {
connection.send("Test");
}
}
start_websocket();
myFunction() is an on-click event of a button.
A Java Websocket server is used, which will decode and send the messages based on the Data framing in https://datatracker.ietf.org/doc/html/rfc6455#section-5.
Saw different articles on the Web, but didn't found a solution to this issue. Any suggestions are much appreciated. Looking forward for your answers
Thanks in advance.

Microsoft Azure Text to Speech - Stop Recording On Button Press - StopRecognitionOnceAsync() Not Working?

Apologies in advance for any terminology mistakes, I'm a student and trying my hardest to be as clear as possible! and thanks in advance for any help!
I'm trying to use Azure Speech-To-Text services. I'd like the user to be able to press a start and stop button to record themselves and print out the transcription. My app will eventually be a React Frontend and Rails backend, but right now I am just trying to understand and work through the demo.
I'm confused by the documentation but was able to get things half working. However, right now it just continuously listens to the speaker and never stops.
I want to use stopContinuousRecognitionAsync() or recognizer.close() once a button is pressed, but I cannot seem to get it working. The farthest I've gotten is the result is logged only once the stop button is pressed, but it continues to listen and print out results. I've also tried using recognizer.close() -> recognizer = undefined but to no avail. I am guessing that due to the asynchronous behavior, it closes out the recognizer before logging a result.
The latest code I've tried is below. This result starts listening on start click and prints speech on stop, but continues to listen and log results.
// subscription key and region for speech services.
var subscriptionKey, serviceRegion;
var authorizationToken;
var SpeechSDK;
var recognizer;
document.addEventListener("DOMContentLoaded", function () {
startRecognizeOnceAsyncButton = document.getElementById("startRecognizeOnceAsyncButton");
subscriptionKey = document.getElementById("subscriptionKey");
serviceRegion = document.getElementById("serviceRegion");
phraseDiv = document.getElementById("phraseDiv");
startRecognizeOnceAsyncButton.addEventListener("click", function () {
startRecognizeOnceAsyncButton.disabled = true;
phraseDiv.innerHTML = "";
// if we got an authorization token, use the token. Otherwise use the provided subscription key
var speechConfig;
if (authorizationToken) {
speechConfig = SpeechSDK.SpeechConfig.fromAuthorizationToken(authorizationToken, serviceRegion.value);
} else {
speechConfig = SpeechSDK.SpeechConfig.fromSubscription(“API_KEY”, serviceRegion.value);
}
speechConfig.speechRecognitionLanguage = "en-US";
var audioConfig = SpeechSDK.AudioConfig.fromDefaultMicrophoneInput();
recognizer = new SpeechSDK.SpeechRecognizer(speechConfig, audioConfig);
recognizer.startContinuousRecognitionAsync(function () {}, function (err) {
console.trace("err - " + err);});
stopButton = document.querySelector(".stopButton")
stopButton.addEventListener("click", () =>{
console.log("clicked")
recognizer.recognized = function(s,e) {
console.log("recognized text", e.result.text)
}
})
});
Assuming the recognizer is conjured correctly outside of the code, there's a few things to change to get the result you want.
The events should be hooked to the recognizer before calling startContinuousRecognition().
In the stop button handler, call stop. I'd also hook the stop event outside of the start button click handler.
Quick typed changes, didn't compile. :-)
startRecognizeOnceAsyncButton.addEventListener("click", function () {
startRecognizeOnceAsyncButton.disabled = true;
//div where text is being shown
phraseDiv.innerHTML = "";
// The event recognized signals that a final recognition result is received.
recognizer.recognized = function(s,e) {
console.log("recognized text", e.result.text)
}
//start listening to speaker
recognizer.startContinuousRecognitionAsync(function () {}, function (err) {
console.trace("err - " + err);});
});
stopButton = document.querySelector(".stopButton")
stopButton.addEventListener("click", () =>{
console.log("clicked");
recognizer.stopContinuousRecongition();
};

How to add back button event in Universal Windows App without using WinjS Library?

This is my main.js
(function () {
"use strict";
//No need of WinJS
var activation = Windows.ApplicationModel.Activation;
var roaming = Windows.Storage.ApplicationData.current.roamingSettings;
// For App Start Up
Windows.UI.WebUI.WebUIApplication.addEventListener("activated", function (args) {
if (args.detail[0].kind === activation.ActivationKind.launch) {
if (roaming.values["currentUri"]) {
if (roaming.values["UserName"])
{
localStorage.setItem("UserName", roaming.values["UserName"]);
window.location.href = roaming.values["currentUri"];
}
}
}
});
// For App Suspension
Windows.UI.WebUI.WebUIApplication.addEventListener("suspending", function (args) {
roaming.values["currentUri"] = window.location.href;
roaming.values["UserName"] = localStorage.getItem("UserName");
});
// For Resuming App
Windows.UI.WebUI.WebUIApplication.addEventListener("resuming", function (args) {
var roam = Windows.Storage.ApplicationData.current.roamingSettings;
if (roam) {
if (roam.values["currentUri"]) {
localStorage.setItem("UserName", roam.values["UserName"]);
window.location.href = roam.values["currentUri"];
}
}
}, false);
// not working backpressed event
Windows.UI.WebUI.WebUIApplication.addEventListener("backpressed", function (args) {
// to do
}, false);})();
I need to add back key press event for windows phone without using winjs library?
Can anyone suggest me?
I am using ms-appx-web context in my app. I dont want to use winjs library.
I need to add back key press event for windows phone without using winjs library?
The backpressed event should be attached to Windows.Phone.UI.Input.HardwareButtons but not Windows.UI.WebUI.WebUIApplication.
If you refer to HardwareButtons.BackPressed and HardwareButtons, you will find the backpressed event is used like this:
var hardwareButtons = Windows.Phone.UI.Input.HardwareButtons;
function onBackPressed(eventArgs) { /* Your code */ }
// addEventListener syntax
hardwareButtons.addEventListener("backpressed", onBackPressed);
hardwareButtons.removeEventListener("backpressed", onBackPressed);
And since you are not making a Single Page Application. This event should be attached on every new page's JS codes.
Update: If you want to know your current device programmatically, you can use the following if-statement:
if (deviceInfo.operatingSystem.toLowerCase() == "windowsphone")
{
//do your windows phone logic
} else if (deviceInfo.operatingSystem.toLowerCase() == "windows")
{
//do your windows logic
}
I used this-
var flag = Windows.Foundation.Metadata.ApiInformation.isTypePresent("Windows.Phone.UI.Input.HardwareButtons");
if (flag) {
var hardwareButtons = Windows.Phone.UI.Input.HardwareButtons;
hardwareButtons.addEventListener("backpressed", onBackPressed);
}
It worked for me well!

Windows 10 universal app not resuming from previous session

I have developed a windows 10 universal app using Html,css and JS. For allowing inline scripts i am using ms-appx-web context and has set ms-appx-web:///login.html as start page in manifest.
Whenever I open my app in windows 10 mobile it works fine but if I switch to another app and then go to app again by selecting it from windows app list. Then it instead of resuming app from saved state it restarts it.
(function () {
"use strict";
var app = WinJS.Application;
var activation = Windows.ApplicationModel.Activation;
app.onactivated = function (args) {
if (args.detail.kind === activation.ActivationKind.launch) {
if (args.detail.previousExecutionState === activation.ApplicationExecutionState.terminated) {
}
if (WinJS.Application.sessionState.url) {
localStorage.setItem("UserName", WinJS.Application.sessionState.name);
window.location = WinJS.Application.sessionState.url;
}
args.setPromise(WinJS.UI.processAll().then(function () {
}));
}
};
app.oncheckpoint = function (args) {
var location = window.location.href;
var name = localStorage.getItem("UserName");
WinJS.Application.sessionState.name = name;
WinJS.Application.sessionState.url = location;
};
Windows.UI.WebUI.WebUIApplication.addEventListener("resuming", function (args) {
if (WinJS.Application.sessionState) {
window.location = WinJS.Application.sessionState.url;
localStorage.setItem("UserName", WinJS.Application.sessionState.name);
}
}, false);
Windows.UI.WebUI.WebUIApplication.addEventListener("suspending", function (args) {
var location = window.location.href;
var name = localStorage.getItem("UserName");
WinJS.Application.sessionState.name = name;
WinJS.Application.sessionState.url = location;
}, false);
app.start();
})();
Can anyone suggest me what am I doing wrong?
I changed my app.onactivated event in main.js
app.onactivated = function (args) {
if (args.detail.kind === activation.ActivationKind.launch) {
if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
} else {
}
args.setPromise(WinJS.UI.processAll());
var name = Windows.Storage.ApplicationData.current.roamingSettings.values["name"];
var url = Windows.Storage.ApplicationData.current.roamingSettings.values["url"];
if (name) {
localStorage.setItem("UserName", name);
}
if (url) {
window.location.href = url;
}
}
};
But it stops running on window.location.href = url; line.
What i am trying to do is store username and current url on suspending event and want to restore it on resume event (when user opens app from app list which is already running.)
but if I switch to another app and then go to app again by selecting it from windows app list. Then it instead of resuming app from saved state it restarts it.
I think you are not using Single-Page Navigation for your app.
Please refer to Single-page navigation: the recommended model:
The script context is destroyed and must be initialized again. The app might receive system events but not handle them because the script context is being destroyed and reinitialized.
So the script context is already destroyed after you navigated to other page.
To fix the problem, the best solution is to make your app a single paged application. And navigate pages using PageControl. You can refer to Quickstart: Using single-page navigation to get started.
Update:
but when I use window.location.href for redirecting in main.js it closes app.
It's because you are using it in WinJS script. When you are leaving the page WinJS script context will be destroyed and thus executing the codes inside crash the app. To fix this you can use windows lifecycle API instead:
var roaming=Windows.Storage.ApplicationData.current.roamingSettings;
Windows.UI.WebUI.WebUIApplication.addEventListener("activated", function (args) {
if (args.detail[0].kind === activation.ActivationKind.launch) {
if (roaming.values["currentUri"]) {
window.location.href = roaming.values["currentUri"];
}
}
});
Windows.UI.WebUI.WebUIApplication.addEventListener("suspending", function (args) {
roaming.values["currentUri"] = window.location.href;
roaming.values["UserName"] = evt.srcElement.value;
//save the other information of the page here
});
Windows.UI.WebUI.WebUIApplication.addEventListener("resuming", function (args) {
var roam = Windows.Storage.ApplicationData.current.roamingSettings;
if (roam) {
if (roam["currentUri"])
{
window.location.href = roam["currentUri"];
}
}
}, false);
You can also refer to my demo.
Notes: If you don't use WinJS at all, just remove the reference. Loading WinJS library on every page is not efficient.
I have changed my main.js as :
(function () {
"use strict";
//No need of WinJS
var activation = Windows.ApplicationModel.Activation;
var roaming = Windows.Storage.ApplicationData.current.roamingSettings;
// For App Start Up
Windows.UI.WebUI.WebUIApplication.addEventListener("activated", function (args) {
if (args.detail[0].kind === activation.ActivationKind.launch) {
if (roaming.values["currentUri"]) {
if (roaming.values["UserName"])
{
localStorage.setItem("UserName", roaming.values["UserName"]);
window.location.href = roaming.values["currentUri"];
}
}
}
});
// For App Suspension
Windows.UI.WebUI.WebUIApplication.addEventListener("suspending", function (args) {
roaming.values["currentUri"] = window.location.href;
roaming.values["UserName"] = localStorage.getItem("UserName");
});
// For Resuming App
Windows.UI.WebUI.WebUIApplication.addEventListener("resuming", function (args) {
var roam = Windows.Storage.ApplicationData.current.roamingSettings;
if (roam) {
if (roam.values["currentUri"]) {
localStorage.setItem("UserName", roam.values["UserName"]);
window.location.href = roam.values["currentUri"];
}
}
}, false);
// not working backpressed event
Windows.UI.WebUI.WebUIApplication.addEventListener("backpressed", function (args) {
// to do
}, false);})();
Everything is working fine. But I dont know how to add back key press event without using winjs.
Can anyone suggest me?
How to add back key press event without winjs?

Chrome Extension Alarms go off when Chrome is reopened after time runs out?

When using Google Chrome extension alarms, the alarm will go off if it was set and Chrome is closed and reopened after the time expires for the alarm.
How can I stop this?
Here is a small code sample to explain what I mean.
/*
If we perform Browser Action to create alarm, then
close the browser, wait about 2 minutes for the alarm to expire
and then reopen the browser, the alarm will go off and the DoSomething
function will get called twice, once by the onStartup event and once
by the onAlarm event.
*/
chrome.browserAction.onClicked.addListener(function (tab) {
chrome.alarms.create('myAlarm', {
delayInMinutes : 2.0
});
});
chrome.alarms.onAlarm.addListener(function (alarm) {
console.log('Fired alarm!');
if (alarm.name == 'myAlarm') {
createListener();
}
});
chrome.runtime.onStartup.addListener(function () {
console.log('Extension started up...');
DoSomething();
});
function DoSomething() {
alert('Function executed!');
}
So if you will read the comment at the top of my code sample you will see what happens.
What I want though, is for the alarm to get cleared if the browser is closed as I want the DoSomething function to get executed only by the onStartup event if the browser is just started, and let the alarm execute the DoSomething function only after the browser is started and my code creates a new alarm.
I never want an alarm to stay around after the browser is closed and then execute onAlarm when the browser is reopened.
How can achieve this?
It's not possible for a Chrome extension to reliably run some code when the browser closes.
Instead of cleaning up on shutdown, just make sure that old alarms are not run on startup. This can be achieved by generating an unique (to the session) identifier.
If you're using event pages, store the identifier in chrome.storage.local (don't forget to set the storage permission in the manifest file). Otherwise, store it in the global scope.
// ID generation:
chrome.runtime.onStartup.addListener(function () {
console.log('Extension started up...');
chrome.storage.local.set({
alarm_suffix: Date.now()
}, function() {
// Initialize your extension, e.g. create browser action handler
// and bind alarm listener
doSomething();
});
});
// Alarm setter:
chrome.storage.local.get('alarm_suffix', function(items) {
chrome.alarms.create('myAlarm' + items.alarm_suffix, {
delayInMinutes : 2.0
});
});
// Bind alarm listener. Note: this must happen *after* the unique ID has been set
chrome.alarms.onAlarm.addListener(function(alarm) {
var parsedName = alarm.name.match(/^([\S\s]*?)(\d+)$/);
if (parsedName) {
alarm.name = parsedName[0];
alarm.suffix = +parsedName[1];
}
if (alarm.name == 'myAlarm') {
chrome.storage.local.get('alarm_suffix', function(data) {
if (data.alarm_suffix === alarm.suffix) {
doSomething();
}
});
}
});
If you're not using event pages, but normal background pages, just store the variable globally (advantage: id reading/writing becomes synchronous, which requires less code):
chrome.runtime.onStartup.addListener(function () {
window.alarm_suffix = Date.now();
});
chrome.alarms.create('myAlarm' + window.alarm_suffix, {
delayInMinutes : 2.0
});
chrome.alarms.onAlarm.addListener(function(alarm) {
var parsedName = alarm.name.match(/^([\S\s]*?)(\d+)$/);
if (parsedName) {
alarm.name = parsedName[0];
alarm.suffix = +parsedName[1];
}
if (alarm.name == 'myAlarm') {
if (alarm.suffix === window.alarm_suffix) {
doSomething();
}
}
});
Or just use the good old setTimeout to achieve the same goal without side effects.
setTimeout(function() {
doSomething();
}, 2*60*1000); // 2 minutes

Categories