/** * native-statusbar.service: 修复状态栏高度 * 提前提供 沉浸式 与 普通屏幕 两种场景; */ import {Injectable} from '@angular/core'; import {Platform} from '@ionic/angular'; import {StatusBar} from '@ionic-native/status-bar/ngx'; @Injectable({ providedIn: 'root' }) export class NativeStatusbarService { // 默认提供的场景; 沉浸式 Immersive,普通屏幕 Base sceneConfig = 'Immersive'; // 单位一般为px StatusBarHeight: string; devicePixelRatio; readyPromise; constructor(private platform: Platform, private statusBar: StatusBar) { // oa 项目需开启 this.init(); } init() { this.readyPromise = new Promise((resolve, reject) => { this.devicePixelRatio = window.devicePixelRatio; this.platform.ready().then(() => { if (this.platform.is('ios')) { this.creatHtmlDom(); } if (this.sceneConfig === 'Immersive') { setTimeout(() => { this.addImmersiveScreen().then(val => { resolve(true); }); }); } else if (this.sceneConfig === 'Base') { this.addBaseScreen(); resolve(true); } else { console.warn('未匹配到相应场景,请检查场景配置参数 sceneConfig'); } }); }); } ready(): Promise { return this.readyPromise; } addImmersiveScreen() { return new Promise((resolve, reject) => { this.getStatusBarHeight().then(val => { this.setRootStyle('--header-padding-top', this.StatusBarHeight); if (this.platform.is('ios')) { this.showStatusBar(); resolve(true); } else if (this.platform.is('android')) { // this.hideStatusBar(); resolve(true); } this.overlayStatusBar(); }); }); } addBaseScreen() { this.showStatusBar(); this.noOverlayStatusBar(); this.StatusBarHeight = '0px'; this.setRootStyle('--header-padding-top', this.StatusBarHeight); } ////////////////////////////////////////////////////////////////////////////////////////// // 基础方法 getStatusBarHeight(): Promise { return new Promise((resolve, reject) => { if (this.platform.is('ios')) { const htmlDom = document.querySelector('m2-ios-header'); this.StatusBarHeight = getComputedStyle(htmlDom).getPropertyValue('padding-top'); resolve(this.StatusBarHeight); } else if (this.platform.is('android')) { if (this.platform.is('cordova')) { // 真机 异步方法... (window as any).StatusBar.getStatusBarHeight('', res => { this.StatusBarHeight = (+res / this.devicePixelRatio) + 'px'; resolve(this.StatusBarHeight); }, err => { console.log('获取android高度错误:', err); reject(err); }); } else { // 浏览器环境 安卓环境 this.StatusBarHeight = '0px'; resolve(this.StatusBarHeight); } } }); } showStatusBar() { this.statusBar.show(); } hideStatusBar() { this.statusBar.hide(); } overlayStatusBar() { this.statusBar.overlaysWebView(true); } noOverlayStatusBar() { this.statusBar.overlaysWebView(false); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// setRootStyle(styleName, styleVal) { const htmlDom = document.querySelector('html'); htmlDom.style.setProperty(styleName, styleVal); } creatHtmlDom() { const m2IosHeader = document.createElement('m2-ios-header'); document.body.appendChild(m2IosHeader); } }