链接:
ionic3 教程(一)安装和配置
ionic3 教程(二)登录页制作
ionic3 教程(三)设置页制作
ionic3 教程(四)安卓硬件返回键处理
ionic3 教程(五)基本的网络请求
前几天测出了一个问题,就是在根目录点击安卓的硬件返回键,会直接导致程序退出。在网上找到了 小军617
写的这篇ionic2实战-完美处理安卓硬件返回按钮。
这篇文章解决了一部分问题,可以让我们在 Tabs 下点击返回按钮弹出一个 toast 提示“再按一次退出应用”,然后如果用户在2秒内再按一次就会真的退出。不过Demo 在登录页点击返回按钮没有任何反应,而且点击退出登录后,点击硬件返回按钮会回到主界面。
所以我打算对这个方法进行一下优化,包括以下几点。
- 将方法从 app.component.ts 中抽出做成一个公共方法,便于其他页面使用
- 修复退出登录后,点击硬件返回按钮会回到主界面
- 在 tabs 页,如果不在首页标签,点击硬件返回按钮,先跳转到首页。之后再按两次退出
1.在 src 目录下,新建文件夹 services 和文件 backButton.service.ts
输入以下代码,我已经写了很全的注释,仔细看
import { Injectable } from '@angular/core';
import { Platform, ToastController, App, NavController, Tabs } from 'ionic-angular';
@Injectable()
export class BackButtonService {
//控制硬件返回按钮是否触发,默认false
backButtonPressed: boolean = false;
//构造函数 依赖注入
constructor(public platform: Platform,
public appCtrl: App,
public toastCtrl: ToastController) { }
//注册方法
registerBackButtonAction(tabRef: Tabs): void {
//registerBackButtonAction是系统自带的方法
this.platform.registerBackButtonAction(() => {
//获取NavController
let activeNav: NavController = this.appCtrl.getActiveNavs()[0];
//如果可以返回上一页,则执行pop
if (activeNav.canGoBack()) {
activeNav.pop();
} else {
if (tabRef == null || tabRef._selectHistory[tabRef._selectHistory.length - 1] === tabRef.getByIndex(0).id) {
//执行退出
this.showExit();
} else {
//选择首页第一个的标签
tabRef.select(0);
}
}
});
}
//退出应用方法
private showExit(): void {
//如果为true,退出
if (this.backButtonPressed) {
this.platform.exitApp();
} else {
//第一次按,弹出Toast
this.toastCtrl.create({
message: '再按一次退出应用',
duration: 2000,
position: 'top'
}).present();
//标记为true
this.backButtonPressed = true;
//两秒后标记为false,如果退出的话,就不会执行了
setTimeout(() => this.backButtonPressed = false, 2000);
}
}
}
注意:
之前我写的是
let activeNav: NavController = this.appCtrl.getActiveNav();
但是在新版中,getActiveNav()
这个方法被移除了,所以需要改为以下方法
let activeNav: NavController = this.appCtrl.getActiveNavs()[0];
2.修改 app.module.ts
导入 BackButtonService,并添加到 providers 里
3.修改 Tabs
Tabs.html
把<ion-tabs>修改为<ion-tabs #myTabs>
Tabs.ts
这是修改了的部分,可以看看都改动了哪些
引入ViewChild、Platform、Tabs、BackButtonService
@ViewChild('myTabs') tabRef: Tabs;
this.platform.ready().then(() => {
this.backButtonService.registerBackButtonAction(this.tabRef);
});
完整版
import { Component, ViewChild } from '@angular/core';
import { Platform, Tabs } from 'ionic-angular';
import { HomePage } from '../home/home';
import { SettingPage } from "../setting/setting";
import { BackButtonService } from "../../services/backButton.service";
@Component({
templateUrl: 'tabs.html'
})
export class TabsPage {
tabRoots: Object[];
@ViewChild('myTabs') tabRef: Tabs;
constructor(public backButtonService: BackButtonService,
private platform: Platform) {
this.tabRoots = [
{
root: HomePage,
tabTitle: 'Home',
tabIcon: 'home'
},
{
root: SettingPage,
tabTitle: '设置',
tabIcon: 'person'
}
];
this.platform.ready().then(() => {
this.backButtonService.registerBackButtonAction(this.tabRef);
});
}
}
platform.ready().then 主要是为了保证能注册上,因为如果不是 ready 状态有可能会失败
4.Login
Login.ts
这是修改了的部分,可以看看都改动了哪些
引入Platform、BackButtonService
this.platform.ready().then(() => {
this.backButtonService.registerBackButtonAction(null);
});
完整版
import { Component } from '@angular/core';
import { IonicPage, ModalController} from 'ionic-angular';
import { TabsPage } from "../tabs/tabs";
import { Platform } from 'ionic-angular';
import { BackButtonService } from "../../services/backButton.service";
@IonicPage()
@Component({
selector: 'page-login',
templateUrl: 'login.html',
})
export class LoginPage {
constructor(public modalCtrl: ModalController,
private backButtonService: BackButtonService,
private platform: Platform) {
this.platform.ready().then(() => {
this.backButtonService.registerBackButtonAction(null);
});
}
ionViewDidLoad() {
console.log('ionViewDidLoad LoginPage');
}
logIn(username: HTMLInputElement, password: HTMLInputElement) {
if (username.value.length == 0) {
alert("请输入账号");
} else if (password.value.length == 0) {
alert("请输入密码");
} else {
let userinfo: string = '用户名:' + username.value + '密码:' + password.value;
alert(userinfo);
let modal = this.modalCtrl.create(TabsPage);
modal.present();
}
}
}
这里的 registerBackButtonAction 传了一个 null 进去,回去看看 backButton.service.ts 的判断,我们就可以知道,这里是为了让他能执行双击退出操作
5.使用安卓手机测试
//执行这两句
$ ionic cordova platform add android
$ ionic cordova build android
接下来就可以运行了,我这边是直接打开 Android Studio 装到手机运行的,亲测有效。试一试吧
Demo下载地址
网友评论
[14:27:00] copy finished in 6.14 s
[14:27:07] webpack finished in 7.94 s
[14:27:07] sass started ...
Without `from` option PostCSS could generate wrong source map and will not find Browserslist config. Set it to CSS file path o
r to `undefined` to prevent this warning.
[14:27:09] sass finished in 1.09 s
[14:27:09] postprocess started ...
[14:27:09] postprocess finished in 22 ms
[14:27:09] lint started ...
[14:27:09] build dev finished in 15.09 s
> cordova build android
(node:14044) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): No platforms added to this proje
ct. Please use `cordova platform add <platform>`.
[14:27:12] tslint: D:/ionic/ionic3Demo/src/pages/login/login.ts, line: 24
Property 'platform' is declared but never used.
L23: private backButtonService: BackButtonService,
L24: private platform: Platform) {
L25: platform.ready().then(() => {
[14:27:12] tslint: D:/ionic/ionic3Demo/src/pages/tabs/tabs.ts, line: 21
Property 'platform' is declared but never used.
L20: constructor(public backButtonService: BackButtonService,
L21: private platform: Platform) {
L22: this.tabRoots = [
[14:27:12] tslint: D:/ionic/ionic3Demo/src/app/app.component.ts, line: 6
All imports are unused.
L6: import { TabsPage } from '../pages/tabs/tabs';
L7: import { LoginPage } from '../pages/login/login';
[14:27:12] lint finished in 3.81 s
D:\ionic\ionic3Demo>
您帮我看下,我这是build成功了吗?
ionic cordova build android 会将你写的代码 build 进安卓项目
build 成功后可以在 platforms/android/build/outputs/apk 下看到 apk
if (activeNav.canGoBack()) {
activeNav.pop();
}
就是如果能返回就返回,你可以处理一下退出登录页面并修改这个判断条件,或者改用 modal.present() 进行返回。
$ ionic cordova plugin add ionic-plugin-keyboard
$ npm install --save @ionic-native/keyboard
修改app.module.ts
添加import { Keyboard } from '@ionic-native/keyboard';
把Keyboard加入到providers里面
然后修改一下backButton.service.ts
import { Keyboard } from '@ionic-native/keyboard';
flag:number=2;
//构造函数 依赖注入
constructor(public platform: Platform,
public appCtrl: App,
public toastCtrl: ToastController,private keyboard: Keyboard) {
var me=this;
window.addEventListener('native.keyboardshow', function (e) {
// todo 进行键盘可用时操作
//e.keyboardHeight 表示软件盘显示的时候的高度
me.flag=1;
});
}
//退出应用方法
private showExit(): void {
//如果为true,退出
if (this.backButtonPressed) {
this.platform.exitApp();
} else {
if(this.flag==1){
this.keyboard.close();
this.flag=2;
return
}
//this.clossKey()
//第一次按,弹出Toast
this.toastCtrl.create({
message: '再按一次退出应用',
duration: 2000,
position: 'top'
}).present();
//标记为true
this.backButtonPressed = true;
//两秒后标记为false,如果退出的话,就不会执行了
setTimeout(() => this.backButtonPressed = false, 2000);
}
}
}
providers: [
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler},
BackButtonService
]
https://github.com/ionic-team/ionic/blob/master/CHANGELOG.md