Cordova中以Angular4式语法读取设备传感器数据
背景介绍
如果你零基础调研Cordova,可能直接出现的是Cordova中文官网以及ionic中文官网,Cordova中文官网没细看,Ionic中文官网用户体验良好,而且已经良心地封装好一个例子比较全、且可以用的apk包及源码。
下载apk包顺利安装后发现不是特别全,比如陀螺仪传感器就没有,再搜Cordova英文官网和Ionic中文官网指向的Cordova插件英文官网,无论全不全,都存在一个致命的问题——全平台都是使用的AngularJS语法,与我们项目使用的Angular4语法是不兼容起码是不统一的。
好在从Cordova插件英文官网上顶部发现连接:
New! Check out Ionic Native. It's like ngCordova but for ES6 and TypeScript.
良心组织。
里面介绍了使用Angular4语法来写Ionic应用(Ionic默认下面就是Cordova)
找到适应的插件仓库,分别找到:
代码介绍
app.module.ts
import { Gyroscope } from '@ionic-native/gyroscope';
import { DeviceMotion } from '@ionic-native/device-motion';
import { DeviceOrientation } from '@ionic-native/device-orientation';
...
providers: [
Gyroscope,
DeviceMotion,
DeviceOrientation
]
car.ts
import { Gyroscope, GyroscopeOrientation, GyroscopeOptions } from '@ionic-native/gyroscope';
import { DeviceMotion, DeviceMotionAccelerationData } from '@ionic-native/device-motion';
import { DeviceOrientation, DeviceOrientationCompassHeading } from '@ionic-native/device-orientation';
...
constructor(public navCtrl: NavController, private platform: Platform, private gyroscope: Gyroscope, private deviceMotion: DeviceMotion, private deviceOrientation: DeviceOrientation) {
let options: GyroscopeOptions = {
frequency: 1
};
setInterval(() => {
this.gyroscope.getCurrent(options)
.then((orientation: GyroscopeOrientation) => {
this.xx = "orien-x:" + orientation.x;
this.yy = "orien-y:" + orientation.y;
this.zz = "orien-z:" + orientation.z;
this.tt = "orien-tstmp:" + orientation.timestamp;
// console.log(orientation.x, orientation.y, orientation.z, orientation.timestamp);
})
.catch();
this.deviceMotion.getCurrentAcceleration().then(
(acceleration: DeviceMotionAccelerationData) => {
this.aa = "acc-x:" + acceleration.x;
this.bb = "acc-y:" + acceleration.y;
this.cc = "acc-z:" + acceleration.z;
this.dd = "acc-tstmp:" + acceleration.timestamp
},
(error: any) => console.log(error)
);
this.deviceOrientation.getCurrentHeading().then(
(data: DeviceOrientationCompassHeading) => {
this.mm = "trueH:" + data.trueHeading;
this.nn = "magH:" + data.magneticHeading;
this.pp = "HA:" + data.headingAccuracy;
this.qq = "tsmp:" + data.timestamp
},
(error: any) => console.log(error)
);
this.gyroscope.watch()
.subscribe((orientation: GyroscopeOrientation) => {
console.log(orientation.x, orientation.y, orientation.z, orientation.timestamp);
});
this.deviceMotion.watchAcceleration().subscribe((acceleration: DeviceMotionAccelerationData) => {
console.log(acceleration);
});
}, 200);
}
网友评论