我是Ionic框架的新手. 我正在尝试在我的应用主页中显示网络连接和电池状态.截至目前我们已获得网络连接解决方案.但我们努力显示电池状态有人可以请我提供如何在Ionic 2应用程序
>我正在尝试在我的应用主页中显示网络连接和电池状态.截至目前我们已获得网络连接解决方案.但我们努力显示电池状态有人可以请我提供如何在Ionic 2应用程序中显示设备电池状态吗?我找到了cordovaBatteryStatus插件https://github.com/apache/cordova-plugin-battery-status.
>我已经安装了插件,
我的home.html: –
<h2>Battery status: {{batteryStatus}}</h2>
<ion-content class="home" padding>
<button ion-button color="primary" (click)="checkNetwork()" full>Get Nettwork Connection</button>
</ion-content>
我的家.: –
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { AlertController, Platform} from 'ionic-angular';
import { BatteryStatus } from 'ionic-native';
declare var batteryLevel: any;
declare var navigator: any;
declare var Connection: any;
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
hideTopTab:boolean=true;
x(){
console.log(this.hideTopTab);
this.hideTopTab = !this.hideTopTab;
}
// hideBottomTab:boolean=true;
// y(){
// console.log(this.hideBottomTab);
// this.hideBottomTab = !this.hideBottomTab;
// }
status:any;
constructor(public alert:AlertController , public navCtrl: NavController, public platform: Platform) {
this.platform.ready().then(()=>{
let subscription = BatteryStatus.onChange().subscribe( (status) => {
console.log(status.level, status.isPlugged);
this.status=status.level;
} );
} );
}
onBatteryStatus(info){
alert('battery status: '+info.level+' isPlugged: '+info.isPlugged);
batteryLevel = info.level;
}
checkNetwork() {
this.platform.ready().then(() => {
var networkState = navigator.connection.type;
var states = {};
states[Connection.UNKNOWN] = 'Unknown connection';
states[Connection.ETHERNET] = 'Ethernet connection';
states[Connection.WIFI] = 'WiFi connection';
states[Connection.CELL_2G] = 'Cell 2G connection';
states[Connection.CELL_3G] = 'Cell 3G connection';
states[Connection.CELL_4G] = 'Cell 4G connection';
states[Connection.CELL] = 'Cell generic connection';
states[Connection.NONE] = 'No network connection';
let alert = this.alert.create({
title: "Connection Status",
subTitle: states[networkState],
buttons: ["OK"]
});
alert.present();
});
}
}
>以上代码用于显示电池状态和设备网络连接.但网络连接正在完美地显示设备网络连接.
>我们几乎已经尝试显示设备电池状态和网络连接,截至目前我们已经获得了网络连接解决方案,但现在我们正在努力获得电池状态解决方案….
>那么请你检查我的代码并提供确切的解决方案,我们不知道我们在home.ts和home.html中的错误.先感谢您…
它所做的就是在每次点击按钮时替换事件监听器
有一个类变量状态
在构造函数中订阅platform.ready()并在回调中设置状态变量.
您可以在按钮单击时在警报中显示状态值.
status:any;
constructor(public alert:AlertController , public navCtrl: NavController, public platform: Platform) {
this.platform.ready().then(()=>{
let subscription = BatteryStatus.onChange().subscribe( (status) => {
console.log(status.level, status.isPlugged);
this.status=status.level;
} );
} );
}
根据您希望显示电池状态的方式,
<h2>Battery status: {{status?.level}}</h2>
<h2>Battery is plugged:{{status?.isPlugged}}</h2>
由于状态是异步设置使用?作为undefined的检查.一旦更改,将更新值.
