Ionic 5 Capacitor hardware back button ending the app - android

I have a problem testing my ionic app on my phone and android studio, when i press the hardware back button the application inmediatly exits, i've tried many solutions, but it simply won't work and won't listen to whatever i code into it.
Here is my attempt
import { Component, Renderer2, ViewChild } from '#angular/core';
import { IonRouterOutlet, Platform } from '#ionic/angular';
import { SplashScreen } from '#ionic-native/splash-screen/ngx';
import { StatusBar } from '#ionic-native/status-bar/ngx';
import { TranslateService } from '#ngx-translate/core';
import { Location } from '#angular/common';
#Component({
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.scss']
})
export class AppComponent {
#ViewChild(IonRouterOutlet, {static: true}) routerOutlet: IonRouterOutlet
constructor(
private platform: Platform,
private splashScreen: SplashScreen,
private statusBar: StatusBar,
private renderer: Renderer2,
private translate: TranslateService,
private location: Location
) {
this.initializeApp();
}
initializeApp() {
this.translate.setDefaultLang( localStorage.getItem('default-language') ? localStorage.getItem('default-language') : navigator.language.slice(0, 2) )
this.platform.ready().then(() => {
this.statusBar.styleDefault();
this.splashScreen.hide();
this.backButtonEvent();
if (localStorage.getItem('color-theme')) {
this.renderer.setAttribute(document.body, 'color-theme', localStorage.getItem('color-theme'))
} else {
if(window.matchMedia && window.matchMedia('(prefers-color-scheme: light)').matches === true)
this.renderer.setAttribute(document.body, 'color-theme', 'light')
else
this.renderer.setAttribute(document.body, 'color-theme', 'dark')
}
});
}
backButtonEvent() {
this.platform.backButton.subscribeWithPriority(0, async () => {
if(!this.routerOutlet.canGoBack())
navigator["app"].exitApp()
else
this.location.back()
});
}
}

Try it this way using the #capacitor/app package:
import { App } from '#capacitor/app';
App.addListener('backButton', ({ canGoBack }) => {
if(canGoBack){
window.history.back();
} else {
App.exitApp();
}
});

Related

Ionic-5 app is closing instead back to previous page on click of hardware back button

I am using angular 7 and ionic 5. When i want to redirect to previous page using hardware back button, ionic app is closing itself. I am using below code but its not working.
this.platform.backButton.subscribeWithPriority(9999, () => {
document.addEventListener('backbutton', function (event) {
event.preventDefault();
event.stopPropagation();
console.log('hello');
}, false);
});
If you are using ionic with Capacitor you need to use this code in the constructor of app.component.ts:
import { App } from '#capacitor/app';
import { Location } from '#angular/common';
constructor(private _location: Location)
{
App.addListener('backButton', () =>
{
if (this._location.isCurrentPathEqualTo('/home'))
{
navigator['app'].exitApp();
}
else
{
this._location.back();
}
});
}
I use the directive for this
import { Directive, HostListener } from '#angular/core';
import { PlatformService } from 'src/app/services/platform';
#Directive({
selector: '[disableBackButton]'
})
export class DisableBackButtonDirective {
constructor(
private platformService: PlatformService
) { }
#HostListener('document:ionBackButton', ['$event'])
overrideHardwareBackAction(event: any) {
if (this.platformService.isPlatform('android')) {
event.detail.register(100, async () => {
event.stopImmediatePropagation();
event.stopPropagation();
event.preventDefault();
});
}
}
}
in page.html
<ion-content disableBackButton>
....
</ion-content>
in page.ts
this.platform.backButton.subscribe(() => {
console.log('hello');
});
Try this,
this.platform.backButton.subscribeWithPriority(10, () => {
this.router.navigate(['']); // route to previous page or component
});

How to conditionally set root page in ionic 4?

I'm working on ionic 4 application. when the user signs In, I added a checkbox to asks for Remember me, so the next time the user open the app it doesn't show the login page and directly forward the user to Home page. I have google and found this. However, while using the accepted solution, I encountered an issue, which it shows the login page for 2 or 3 seconds, then open the Home page. How I can safely achieve it without delay?
app.component.ts
import { SmsVerificationService } from 'src/app/services/SMS/sms-verification.service';
import { Component } from '#angular/core';
import { Platform } from '#ionic/angular';
import { SplashScreen } from '#ionic-native/splash-screen/ngx';
import { StatusBar } from '#ionic-native/status-bar/ngx';
import { FCM } from '#ionic-native/fcm/ngx';
import { Plugins, Capacitor } from '#capacitor/core';
import { Router } from '#angular/router';
import { Storage } from '#ionic/storage';
#Component({
selector: 'app-root',
templateUrl: 'app.component.html'
})
export class AppComponent {
constructor(
private platform: Platform,
private splashScreen: SplashScreen,
private statusBar: StatusBar,
private fcm: FCM,
private route: Router,
private storage: Storage
) {
this.initializeApp();
}
initializeApp() {
this.platform.ready().then(() => {
this.fcm.getToken().then(token => {
console.log(' token is ', token);
});
this.fcm.onTokenRefresh().subscribe(token => {
console.log('on token refresh ', token);
});
this.fcm.onNotification().subscribe(data => {
console.log(data);
if (data.wasTapped) {
console.log('Received in background');
// this.router.navigate([data.landing_page, data.price]);
} else {
console.log('Received in foreground');
// this.router.navigate([data.landing_page, data.price]);
}
});
this.storage.get('isLogined').then(data => {
if (data)
this.route.navigateByUrl('/main-tab');
})
this.statusBar.styleDefault();
this.splashScreen.hide();
if (Capacitor.isPluginAvailable('SplashScreen')) {
Plugins.SplashScreen.hide();
}
});
}
}
The codes that are supposed to change the page
this.storage.get('isLogined').then(data => {
if (data)
this.route.navigateByUrl('/main-tab');
})
Do you have a separate login component? If so, you can create and add a guard to your login component to navigate to your main page when Remember me was checked.

ionic2 Streaming Media is not working

I'm using the streaming media plugin in my ionic2 application.
this is my code:
let option:StreamingAudioOptions = {
successCallback: () => { console.log('Audio played') },
errorCallback: (e) => { console.log(JSON.stringify(e,null,2)) }
}
this.streamingMedia.playAudio('http://sounddible.com/grab.php?id=2196&type=mp3',option);
the errorCallback return "Class not found"
Any help for explain the reason of this log
Thanks.
try below code :
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { StreamingMedia, StreamingAudioOptions } from '#ionic-native/streaming-media';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
constructor(public navCtrl: NavController,private streamingMedia: StreamingMedia) {}
startAudio(){
let options: StreamingAudioOptions = {
successCallback: () => { console.log('Video played') },
errorCallback: (e) => { console.log(JSON.stringify(e,null,2)) },
initFullscreen:false,
};
this.streamingMedia.playAudio('YOUR_URL', options);
}

Transparent status bar ionic2

I need transparent status bar ionic 2.
I installed npm install --save #ionic-native/status-bar.and also
refer this link https://ionicframework.com/docs/v2/native/status-bar/
I used this.statusBar.backgroundColorByHexString("#0e5591"); But It's not working.
Below my app component.
import { Component, ViewChild,Inject } from '#angular/core';
import { Nav,NavController,Platform ,AlertController,MenuController,App,IonicApp} from 'ionic-angular';
import { Splashscreen ,Network,Toast} from 'ionic-native';
import { StatusBar } from '#ionic-native/status-bar';
#Component({
templateUrl: 'app.html'
})
export class MyApp {
public app: App;
currentuser;
#ViewChild(Nav) nav1: Nav;
auth:any;
menu;
nav:NavController;
constructor(private statusBar: StatusBar,public appCtrl: App,public menu1: MenuController,public alertCtrl:AlertController,public platform: Platform,public authservice:Authservice) {
this.auth=localStorage.getItem("email");
console.log("Auth"+this.auth);
// this.rootPage = this.isUserLoggedIn ? LoginPage : MycomplaintsPage;
// console.log(this.rootPage);
if(this.auth != undefined && this.auth != null)
{
this.rootPage = DashboardPage;
}
this.showRoot = true;
this.initializeApp();
}
initializeApp() {
this.platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
this.statusBar.styleDefault();
this.statusBar.backgroundColorByHexString("#0e5591");
Splashscreen.hide();
if(Network.type === Connection.NONE)
{
console.log("success");
let alert = this.alertCtrl.create({
title: "Internet Connection",
subTitle:"Please Check Your Network connection",
buttons: [
{
text: 'Ok',
handler: () => {
this.platform.exitApp();
}
}
]
});
alert.present();
}
});
}
exit(){
let alert = this.alertCtrl.create({
title: 'Confirm',
message: 'Do you want to exit?',
buttons: [{
text: "exit?",
handler: () => { this.exitApp() }
}, {
text: "Cancel",
role: 'cancel'
}]
})
alert.present();
}
exitApp(){
this.platform.exitApp();
}
}
I am getting this err
ORIGINAL EXCEPTION: No provider for StatusBar!
Kindly advice me,
Thanks
It looks like you have two versions of ionic native from your imports.
import { Splashscreen ,Network,Toast} from 'ionic-native';
import { StatusBar } from '#ionic-native/status-bar';
Make sure you only have #ionic-native/core in your package.json.
Also according to the latest ionic-native docs,
you need to set the plugin as provider in ngModule:
#NgModule({
...
providers: [
...
Statusbar
...
]
...
})

Android physical back button error

When I tap physical Android Button I've got the next error:
Unhandled exception java.lang.IndexOutOfBoundsException: setSpan
(2..2) ends beyound length 0
Here is my app.routing.ts
import { LoginComponent } from "./pages/login/login.component";
import { CarwashComponent } from "./pages/carwash/carwash.component";
import { NewOrderComponent } from "./pages/new_order/new-order.component";
import { ProfileComponent } from "./pages/profile/profile.component";
import { OrderDetailComponent } from "./pages/order/order-detail/order-detail.component";
export const routes = [
{ path: "", component: LoginComponent },
{ path: "profile", component: ProfileComponent},
{ path: "carwash", component: CarwashComponent },
{ path: "order-detail/:order_id", component: OrderDetailComponent },
{ path: "new_order", component: NewOrderComponent}
];
export const navigatableComponents = [
LoginComponent,
CarwashComponent,
ProfileComponent,
OrderDetailComponent,
NewOrderComponent
];
Example of the page:
import { Component, ElementRef, OnInit, ViewChild, OnChanges } from "#angular/core";
import { CarwashService } from "../../../shared/carwash/carwash.service";
import { OrderService } from "../../../shared/order/order.service";
import { Page } from "ui/page";
import { Color } from "color";
import { Router, ActivatedRoute, Params } from "#angular/router";
import { TimePicker } from "ui/time-picker";
import { DatePicker } from "ui/date-picker";
import { StoredData } from "../../../shared/config"
import * as application from "application";
#Component({
selector: "order-detail",
providers: [CarwashService, OrderService],
templateUrl: "pages/order/order-detail/order-detail.html",
styleUrls: ["pages/order/order-detail/order-detail-common.css", "pages/order/order-detail/order-detail.css"]
})
export class OrderDetailComponent implements OnInit {
constructor(
private page: Page,
private router: Router,
private carwashService: CarwashService,
private orderService: OrderService,
private route: ActivatedRoute){}
ngOnInit() {... }
checkStatus(){...}
addOrderTotalName(){...}
changeStatus(status){...}
closeOrder(){...}
cancelOrder(){...}
}
What's wrong?enter image description here
Normally the physical back button will behave as going back to previous page, but I don't know why this happens to you. You can try to define again the function for the back button like this:
var application = require("application")
var topmost = require("ui/frame").topmost;
var activity = application.android.startActivity ||
application.android.foregroundActivity ||
frameModule.topmost().android.currentActivity ||
frameModule.topmost().android.activity;
var lastPress;
activity.onBackPressed = function() {
topmost().goBack;
}

Categories

Resources