David Chao

所有文章

Ionic 5 偵測 Android 實體按鈕的方式

因為 Android 的手機多了實體按鈕,所以在規劃流程的時候必須把這點考慮進去,ios 只要把 back button 拿掉,就不能回上頁了,但 android 可以靠實體按鈕回到上一頁,邏輯方面就要小心處理。

另外就是登入後假設進入到 dashboard,再按實體按鈕又會退回燈入頁,這樣就不合理了,因該是直接詢問是否關閉 App 會考一些,下面就來時做看看。

編輯 app.component.ts

javascript
import {Component, ElementRef, ViewChild} from '@angular/core';
import {AlertController, IonRouterOutlet, Platform} from '@ionic/angular';
import {Router} from '@angular/router';

@Component({
    selector: 'app-root',
    templateUrl: 'app.component.html'
})
export class AppComponent {
    @ViewChild(IonRouterOutlet, {static: false}) routerOutlet: IonRouterOutlet;

    constructor(
        private router: Router,
        private platform: Platform,
        public alertController: AlertController,
    ) {
        this.initializeApp();
    }

    initializeApp() {
        this.platform.ready().then(() => {

            // 針對 android 再執行
            if (this.platform.is('android')) {
                this.platform.backButton.subscribeWithPriority(0, () => {

                    // 這是 tab 的頁面,只要是在這幾頁按回上頁就提示是否關閉
                    if (
                        this.router.url === '/tabs/dashboard' ||
                        this.router.url === '/tabs/chat' ||
                        this.router.url === '/tabs/account' ||
                        this.router.url === '/tabs/notify' ||
                        this.router.url === '/tabs/match'
                    ) {
                        this.confirmLeaveApp();
                        return;
                    }

                    // 如果是內頁的話就回上頁
                    if (this.routerOutlet && this.routerOutlet.canGoBack()) {
                        this.routerOutlet.pop();
                    } else {
                        console.log('will close app A');
                    }
                });
            }
        });
    }

    // 關閉 app 的 alert
    async confirmLeaveApp() {
        const message = '點選確定關閉 App,返回取消.';
        const buttons = [
            {
                text: '確定!',
                role: 'cancel',
                cssClass: 'medium',
                handler: (blah) => {
                    navigator['app'].exitApp();
                }
            }, {
                text: '返回',
                handler: () => {
                    console.log('go back');
                }
            }
        ];

        const alert = await this.alertController.create({
            header: '確定關閉 App 嗎?!',
            message,
            buttons,
        });

        await alert.present();
    }
}

這樣就完成了,想要不同的流程就在修改對應的邏輯囉。