handle quit on electronjs application - electron

I've got an electron app that manages data on quit. now, I've one option for that like if electron app quits manually by the user it should manage the state of ongoing data like that till now has app recorded should be stored in a local database and then the app should quit but If app quit unexpectedly then it should also check if data is not uploaded into live DB then first update it in local and then sync it with live.
highlights of question:
it should save the data if the app quits unexpectedly.
it should sync the data to live if the user manually quits the app.
If anyone has any idea to do that in simple steps without and breakage it would be very helpful for me. thanks in advance.

it should sync the data to live if the user manually quits the app.
Yes. You can easily do lot of things thanks to app event like that :
app.on('window-all-closed', () => {
// put what you want here
app.quit()
})
You also have this event, perhaps help you:
process.on("uncaughtException", (err) => {
const messageBoxOptions = {
type: "error",
title: "Error in Main process",
message: "Something failed"
};
dialog.showMessageBox(messageBoxOptions);
throw err;
});

Related

Prevent electron app shutdown until cleanup complete

I'm trying to have my electron app do a bunch of cleanup when the app is quit (terminate a few processes, delete some temp files, etc). I am triggering the cleanUp function with the before-quit event. If my computer is running fast, these cleanup operations complete before the app is quit, but if the computer is running slow, the cleanUp function sometimes only executes partially.
Is there a way that I can prevent the app from fully quitting before my cleanUp function has been fully executed?
app.on('before-quit', async () => {
try {
await cleanUp();
} catch (err) {
console.error(err);
}
});
As you can read in the before-quit docs, you can use event.preventDefault() inside the before-quit event handler to prevent the app from terminating.
Your cleanup code can then run unimpeded. At the end of the cleanup, close the app programmatically.
To make sure that before-quit will not block app termination at that time, you probably want to keep track of the current state of the app. You may want to allow the app to terminate inside before-quit if the cleanup code has completed. That means: execute event.preventDefault() only if the cleanup has not been completed yet.
It's probably wise to inform the user about the state of the app: display "shutting down" or something similar, so that it is clear that the app is no longer functional.

Refresh app every time user opens it

I'm using Phonegap Cordova and have an iOS app and web app that sync information to each other, the problem I'm having though is that if the user has the iOS open on their device, but minimized, the data doesn't update realtime. So if they add something on the web app and look at the iOS app the changes wouldn't have been made on the iOS side so they'd have to close the app and relaunch. This isn't very user friendly.
Would anyone have any advice how to fix this? Perhaps refresh the app every time they open, or scroll up to refresh manually?
Any help would be great! Thank you.
use this plugin :
cordova-plugin-background
and in index use this code for refrech the app
document.addEventListener('deviceready', function () {
cordova.plugins.backgroundMode.enable();
cordova.plugins.backgroundMode.onactivate = function () {
setInterval(function () {
location.reload();
}, 10000);
}
}, false);
you app it' well refrech in backround every 10000 second you can change the time
You definitely have a few options here:
You can use Cordova's resume event which should fire when the user brings the app back to the foreground (at least I think that's what it does, I haven't used that event myself)
If it applies to your use case, you could use the push plugin to push data to your device and trigger updates
A manual slide down to refresh would also be good, maybe even on top of the options above

Electron recovery after crash on render process

I'm building an electron app that must reload the render process window if a crash happens.
Currently I can restart the app from the main process
app.relaunch();
app.quit();
But I cannot detect the window crashing.
I tried using the
win.on('unresponsive', () => { ... } );
But the event is not getting generated when I crash the process.
To crash the process I tried:
invoking the process.crash()
using all the available memory.
Both ways successfully crash the process but again, I cannot find a way to detect it.
I tried also using, from the render process, the window.onerror(...) and sending via IPC to the main process a message when the crash is detected, but this seems not to work as well.
You should be looking for the 'crashed' event in webContents. Check https://electronjs.org/docs/api/web-contents#event-crashed
For example put something like this in main process:
win.webContents.on('crashed', (e) => {
app.relaunch();
app.quit()
});
maybe look into "pm2-windows-service" which can install your app as windows service and watch if it crashes, to restart it
https://www.npmjs.com/package/pm2-windows-service
also electron has app.setLoginItemSettings({ openAtLogin: true }); but that does not guard for crash, only provide automatic app start at windows login

IONIC2 - app gets killed after some time even when using Background Geolocation

I have an IONIC2 app, which needs to wake up every morning at 8 AM for 20 minutes to send user reminders based on the user's geolocation.
I am using this plugin (which uses IOS significant changes API to monitor changes in user's location)
https://github.com/mauron85/cordova-plugin-background-geolocation
The problem:
The app doesn't get killed when I close the app and the background geolocation works for me fine for some time. I have tested upto an hour. But when I wake up next morning, I find the app was killed by IOS.
I know there is another plugin to keep the app running in the background https://github.com/katzer/cordova-plugin-background-mode, but I have read tons of complaints from people that it will cause your app to be rejected by the AppStore (In fact, the plugin has a disclaimer to the same effect too).
For waking up the app tomorrow, I simply set a setTimeout
setTimeout(function(){
console.log('waking up');
self.helper.scheduleLocalNotification('Hello World', 'Good Morning', 10, "");
self.ionViewDidEnter();
}, wakeupinMilliSeconds);
Here is my geolocation code:
setupBackGroundGeolocation(){
let config = {
desiredAccuracy: 100,
stationaryRadius: 50,
distanceFilter: 100,
interval: 5000,
pauseLocationUpdates: false,
debug: false, // enable this hear sounds for background-geolocation life-cycle.
stopOnTerminate: false, // enable this to clear background location settings when the app terminates
};
BackgroundGeolocation.configure((location) => {
console.log('[js] BackgroundGeolocation callback: ' + location.latitude + ',' + location.longitude);
this.currentLocation.lat = location.latitude;
this.currentLocation.lng = location.longitude;
Promise.all([
//I do some calculations here.
]).then(d => {
// IMPORTANT: You must execute the finish method here to inform the native plugin that you're finished,
// and the background-task may be completed. You must do this regardless if your HTTP request is successful or not.
// IF YOU DON'T, ios will CRASH YOUR APP for spending too much time in the background.
BackgroundGeolocation.finish(); // FOR IOS ONLY
});
}, (error) => {
console.log('BackgroundGeolocation error');
}, config);
// Turn ON the background-geolocation system. The user will be tracked whenever they suspend the app.
BackgroundGeolocation.start();
}
I don't use this plugin but had same symptons. I couldn't figure out what was wrong: no error messages, no clues but app kept closing after a few hours.
I guess there was something messed up after installing and uninstalling so many cordova plugins. Now the app is much more stable. I removed and added platform. That seemed to do the job.
I've been reading about ionic2 and performance. Among so many reasons, a possibility about low performance and crash is related not to unsubscribe from observables. Read about async pipe and .unsubscribe observables when component is destroyed ngOnDestroy
Another problem i found was a very basic mistake developing in angular. I loaded everything in the app module so this required lot of memory to load the entire app at once. I guess with slow terminals that can affect more. Anyway, basic angular concepts as .module files should be understood.

Some Apple Push Notifications from Azure Mobile Services not Arriving

I've been struggling with this for a few days and am stuck. I am using Azure Mobile Services and have two scheduler scripts defined. One is very simple and just sends all device tokens for User ID #1 a test push notification:
function SendTestNotification() {
sendPushNotification(1, 'SendTestNotification # ' + new Date());
function sendPushNotification(userId, body) {
var users = tables.getTable('NotificationTokens');
users.where({
User_Id: userId
}).read({
success: function(tokens) {
tokens.forEach(function(token) {
var alert = {
badge: 0,
alert: body,
sound: 'default'
};
push.apns.send(token.Token, alert,
{
error : function(err) {
console.error(err);
}
});
});
},
error: function(error) {
console.error(error)
return;
}
});
}
}
I have a second scheduler script which is much more elaborate and contains the actual push notification logic for my app. It contains the exact same sendPushNotification() function shown above. This 2nd script also contains an additional call to send me a "test" notification.
So all told, with these two scripts setup and scheduled, my iOS devices should get a total of 3 push notifications every 15 minutes. I have them timestamped as well so that they show when the notification was sent from the server.
However, when I run these scripts either manually or just let them run on their own every 15 minutes, I almost never get all of the notifications. Sometimes I get none. Sometimes I only get the first test notification. Sometimes I get the first test notification, the "real" notification, but not the 2nd test notification (which should have been sent by the exact same code that sent the "real" notification).
I have checked the logs on the portal and there are no errors coming back from APNS. I know the logging is working as I've seen errors for invalid device tokens in the past.
I should also state that I've sent these devices push notifications via APNS using a simple C# application with absolutely no problem.
Can anyone give any suggestions or see what I may be doing wrong? I have an app waiting to be reviewed and would love to get this issue taken care of.
Last time this happened to me I changed the scale from Free to Basic, and all notification were sent.
You said that there is no error, but just remember, if an error occurs you have to start over again from the point you stopped because the apns close the connection once an error occurs.

Resources