ionic - back button exit app not working in Ionic 5 - ionic-framework

I am using Ionic version 5.4.16 and i am trying to close the app by hardware back button with a alert message for confirm to exit. I have checked a lot of tutorials for the same and everywhere i saw 2 ways to achieve that --
this.platform.exitApp();
and
navigator.app.exitapp()
and
navigator.["app"].exitapp();
But none of these option are working in Ionic 5, its not recognizing the function exitApp().
So how to achieve the same if anyone has faced the same issue do suggest, thank you.

To close the app, you must configure the following:
import { Plugins } from '#capacitor/core';
const { App } = Plugins;
App.exitApp();

Try to paste this code.
public unsubscribeBackEvent: any;
ionViewDidEnter() {
this.initializeBackButtonCustomHandler();
}
initializeBackButtonCustomHandler(): void {
this.unsubscribeBackEvent = this.platform.backButton.subscribeWithPriority(999999, () => {
if(window.confirm('Do you want to exit the app?'))
{
navigator['app'].exitApp();
}
});
}
ionViewWillLeave() {
this.unsubscribeBackEvent.unsubscribe();
}
I hope it's done.

Related

Click the device back button closes the app instead of going back to previous page in android 9

In ionic framework,clicking back button to close app instead of going back to previous page.It is only happen in android 9.Work fine in other android version.
I already wrote these code in app.component.ts
this.platform.backButton.subscribe(() => {
if (this.router.isActive('/home', true) && this.router.url === '/home') {
navigator['app'].exitApp();
}
});
Here is the solution : in homepage.ts May be work
ionViewDidEnter(){
this.subscription = this.platform.backButton.subscribe(()=>{
navigator['app'].exitApp(); });
}
ionViewWillLeave(){
this.subscription.unsubscribe();
}

Having issue with Battery status in Ionic 4

I'm using Ionic4 and I'm trying to get the device battery level. But I get an error:
ERROR TypeError: Invalid event target
and for the battery level, I get undefined.
Has anyone run into the same problem
There is an open bug report at ionic: https://github.com/ionic-team/ionic-native/issues/2972
Unfortunately no solution yet, however there is a workaround to bypass the ionic typescript wrapper and just listen directly on the window events.
fromEvent(window, 'batterystatus').subscribe((status) => {
console.log(status)
});
This is how I managed to get the battery status in Ionic 4:
window.addEventListener('batterystatus', this.onBatteryStatus, false);
onBatteryStatus(status) {
console.log('Level: ' + status.level + ' isPlugged: ' + status.isPlugged);
}
An easy way could be like this:
$ ionic cordova plugin add cordova-plugin-battery-status
$ npm install --save #ionic-native/battery-status#4
Then in your code:
import { Platform } from 'ionic-angular';
import { BatteryStatus } from '#ionic-native/battery-status';
batterylevel = 0;
constructor(...
private batteryStatus: BatteryStatus,
private plt: Platform ) {}
ionViewDidEnter()
{
// Cordova check
if(this.plt.is('core') || this.plt.is('mobileweb'))
{
// NO. It's a browser.
// don't call the batery.
}
else
{
const batterysubscription = this.batteryStatus.onChange().subscribe(status => {
this.batterylevel = status.level;
});
}
}
yourfunction()
{
console.log(this.batterylevel);
}
You'll also need to add it to your provider list too.
Of course, this will only work in emulation or a device.

Can I call Ionic 4 / Capacitor Electron code from the Ionic part of the application?

I am investigating using Ionic 4/ Capacitor to target Windows via the Electron option, for an application where I want to use SQLite.
Using the Ionic Native SQLite plugin, which wraps this Cordova plugin, out of the box, as far as I can see, the Windows support is for UWP, and not Desktop, which runs using Electron in Ionic Capacitor wrapper.
My plan, was to see if I could use Electron SQLite package, and then call this from my Ionic application by making a wrapper class for the Ionic native similar to what I used to get browser support by following this tutoral
If I can call the Electron code from my Ionic app, then I can't see why this wouldn't work.
So, my question here is, can I call code (I will add functions to use the SQlite) I add to the hosting Electron application from within the Ionic (web) code? And if so, how?
Thanks in advance for any help
[UPDATE1]
Tried the following...
From an Ionic page, I have a button click handler where I raise an event..
export class HomePage {
public devtools() : void {
let emit = new EventEmitter(true);
emit.emit('myEvent');
var evt = new CustomEvent('myEvent');
window.dispatchEvent(evt);
}
Then within the Electron projects index.js, I tried..
mainWindow.webContents.on('myEvent', () => {
mainWindow.openDevTools();
});
const ipc = require('electron').ipcMain
ipc.on('myEvent', (ev, arg) => {
mainWindow.openDevTools();
});
But neither worked.
I should mention I know very little about Electron. This is my first exposure to it (via Capacitor)
In case someone is interested, this is how I solved this.
Im am using Ionic 4 / Capacitor + Vue 3.
In my entry file (app.ts) I have declared a global interface called Window as follows:
// app.ts
declare global { interface Window { require: any; } }
Then, I have written the following class:
// electron.ts
import { isPlatform } from '#ionic/core';
export class Electron
{
public static isElectron = isPlatform(window, 'electron');
public static getElectron()
{
if (this.isElectron)
{
return window.require('electron');
}
else
{
return null;
}
}
public static getIpcRenderer()
{
if (this.isElectron)
{
return window.require('electron').ipcRenderer;
}
else
{
return null;
}
}
public static getOs()
{
if (this.isElectron)
{
return window.require('os');
}
else
{
return null;
}
}
}
And I use it like this:
//electronabout.ts
import { IAbout } from './iabout';
import { Plugins } from '#capacitor/core';
import { Electron } from '../utils/electron';
export class ElectronAbout implements IAbout
{
constructor() { }
public async getDeviceInfo()
{
let os = Electron.getOs();
let devInfo =
{
arch: os.arch(),
platform: os.platform(),
type: os.type(),
userInfo: os.userInfo()
};
return devInfo;
}
public async showDeviceInfo()
{
const devInfo = await this.getDeviceInfo();
await Plugins.Modals.alert({ title: 'Info from Electron', message: JSON.stringify(devInfo) });
}
}
This is working but, of course, I still need to refactor the Electron class (electron.ts). Probably using the singleton pattern is a better idea.
I hope this helps.
Update
You can communicate from the render process with your main process (index.js) like this:
//somefile.ts
if (Electron.isElectron)
{
let ipc = Electron.getIpcRenderer();
ipc.once('hide-menu-button', (event) => { this.isMenuButtonVisible = false; });
}
//index.js
let newWindow = new BrowserWindow(windowOptions);
newWindow.loadURL(`file://${__dirname}/app/index.html`);
newWindow.webContents.on('dom-ready', () => {
newWindow.webContents.send('hide-menu-button');
newWindow.show();
});
I dug into this yesterday and have an example for you using angular(this should apply to ionic too).
in your service declare require so we can use it
//Below your imports
declare function require(name:string);
Then in whatever function you want to use it in:
// Require the ipcRenderer so we can emit to the ipc to call a function
// Use ts-ignore or else angular wont compile
// #ts-ignore
const ipc = window.require('electron').ipcRenderer;
// Send a message to the ipc
// #ts-ignore
ipc.send('test', 'google');
Then in the created index.js within the electron folder
// Listening for the emitted event
ipc.addListener('test', (ev, arg) => {
// console.log('ev', ev);
console.log('arg', arg);
});
Its probably not the correct way to access it but its the best way i could find. From my understanding the ipcRenderer is used for when you have multiple browsers talking to each other within electron. so in our situation it enables our web layer to communicate with the electron stuff

How to integrate Anyline OCR SDK made for Cordova into Ionic2

I´m new to Ionic2, but experienced in web development. Just learning new platform at the moment.
So I have tried to integrate the Anyline OCR SDK
https://github.com/Anyline/anyline-ocr-cordova-module
but I am failing, it seems to me that the plugin is written in Javascript and not compatible with TS but I´m not sure...
Is there anyone out there that could help?
Thanks,
Ben
Not sure if you still need help with that, but for those out there who are looking for a working solution, here is mine:
1 - Add the Anyline Plugin to your project cordova plugin add io-anyline-cordova
2 - Create a new file ionic g provider anyline
3 - add this code to your anyline.ts file:
export class OCR {
constructor() {
if (anylineScan === undefined) {
var anylineScan = {};
}
}
anylineScan = {
onResult: function (result) {
console.log("MRZ result: " + JSON.stringify(result));
//do what you want here with the result
},
onError: function (error) {
console.log("scanning error");
},
scan: function () {
var licenseKey = "enterYourLicenceKeyHere";
try {
(<any>window).cordova.exec(this.onResult, this.onError, "AnylineSDK", "OCR", [licenseKey, {
"captureResolution":"1080p",
//your other config setting here
}]);
}
catch (e){
console.log("Cannot open scan view: ERROR occurred");
}
}
}
4 - Add the file references to your app.module.ts file
import { OCR } from '../yourFolderName/anyline';
...
providers: [Storage, OCR]
5 - In your page.ts file add the following call:
this.anyline.anylineScan.scan();
Important! It will not work in the browser, make sure you run ionic platform add ios (or android) and run the app on a device.
This should work!
Good luck and happy coding :-)

SmartFace show sliderdrawer

I trying to learn SmartFace App Development Platform. I added a SliderDrawer in Page then after I added codes as follows. But this codes not working in OnShow() event. How can I do this? Maybe I can do with write a lot of code. But I want to do without writing a lot of code.
function Page1_Self_OnShow() {
Pages.Page1.SliderDrawer1.show();
}
This is a known issue for Android, it will be fixed.But you can solve the problem until the bug is fixed as follows:
function Page1_Self_OnShow() {
var timeoutID = setTimeout(function () {
setHello();
}, 200);
function setHello() {
Pages.Page1.SliderDrawer1.show();
}
function cancelHello() {
clearTimeout(timeoutID);
}
}