文章的目的为了记录使用Arkts 进行Harmony app 开发学习的经历。本职为嵌入式软件开发,公司安排开发app,临时学习,完成app的开发。开发流程和要点有些记忆模糊,赶紧记录,防止忘记。
相关链接:
开源 Arkts 鸿蒙应用 开发(一)工程文件分析-CSDN博客
开源 Arkts 鸿蒙应用 开发(二)封装库.har制作和应用-CSDN博客
开源 Arkts 鸿蒙应用 开发(三)Arkts的介绍-CSDN博客
开源 Arkts 鸿蒙应用 开发(四)布局和常用控件-CSDN博客
开源 Arkts 鸿蒙应用 开发(五)控件组成和复杂控件-CSDN博客
开源 Arkts 鸿蒙应用 开发(六)数据持久--文件和首选项存储-CSDN博客
开源 Arkts 鸿蒙应用 开发(七)数据持久--sqlite关系数据库-CSDN博客
开源 Arkts 鸿蒙应用 开发(八)多媒体--相册和相机-CSDN博客
开源 Arkts 鸿蒙应用 开发(九)通讯--tcp客户端-CSDN博客
开源 Arkts 鸿蒙应用 开发(十)通讯--Http-CSDN博客
开源 Arkts 鸿蒙应用 开发(十一)证书和包名修改-CSDN博客
开源 Arkts 鸿蒙应用 开发(十二)传感器的使用-CSDN博客
开源 Arkts 鸿蒙应用 开发(十三)音频--MP3播放-CSDN博客
推荐链接:
开源 java android app 开发(一)开发环境的搭建-CSDN博客
开源 java android app 开发(二)工程文件结构-CSDN博客
开源 java android app 开发(三)GUI界面布局和常用组件-CSDN博客
开源 java android app 开发(四)GUI界面重要组件-CSDN博客
开源 java android app 开发(五)文件和数据库存储-CSDN博客
开源 java android app 开发(六)多媒体使用-CSDN博客
开源 java android app 开发(七)通讯之Tcp和Http-CSDN博客
开源 java android app 开发(八)通讯之Mqtt和Ble-CSDN博客
开源 java android app 开发(九)后台之线程和服务-CSDN博客
开源 java android app 开发(十)广播机制-CSDN博客
开源 java android app 开发(十一)调试、发布-CSDN博客
开源 java android app 开发(十二)封库.aar-CSDN博客
推荐链接:
开源C# .net mvc 开发(一)WEB搭建_c#部署web程序-CSDN博客
开源 C# .net mvc 开发(二)网站快速搭建_c#网站开发-CSDN博客
开源 C# .net mvc 开发(三)WEB内外网访问(VS发布、IIS配置网站、花生壳外网穿刺访问)_c# mvc 域名下不可訪問內網,內網下可以訪問域名-CSDN博客
开源 C# .net mvc 开发(四)工程结构、页面提交以及显示_c#工程结构-CSDN博客
开源 Arkts 鸿蒙应用 开发(十)通讯--Http数据传输-CSDN博客开源 C# .net mvc 开发(五)常用代码快速开发_c# mvc开发-CSDN博客
本章内容主HarmonyOS next 系统上的传感器如何使用,获取传感器列表,然后建立监测,就可以获得传感器的实时数据。
工程中,只需修改module.json5和Index.ets的代码就可以完成APP。
1.传感器怎么用
2.设置权限
3.所有代码
4.显示效果
一、获取传感器列表
当设备需要获取传感器数据时,可以使用sensor模块。比较常用的是,加速度计,陀螺仪等。
首先获取所有传感器,其次获得传感器参数,最后建立监测。
1.1 首先将所有可用的传感器打印出来
以下为代码
sensor.getSensorList((error: BusinessError, data: Array<sensor.Sensor>) => {
if (error) {
console.error('getSensorList failed');
} else {
console.info('getSensorList success');
for (let i = 0; i < data.length; i++) {
console.info(JSON.stringify(data[i]));
}
}
});
打印效果,需要记住打印的传感器名称和Id方便后面使用
1.2 查询设备支持的所有传感器的参数。
sensor.getSensorList((error: BusinessError, data: Array<sensor.Sensor>) => {
if (error) {
console.error('getSensorList failed');
} else {
console.info('getSensorList success');
for (let i = 0; i < data.length; i++) {
console.info(JSON.stringify(data[i]));
}
}
});
1.3 注册监听。可以通过on()和once()两种接口监听传感器的调用结果。通过interval设置为100000000纳秒
import { sensor } from '@kit.SensorServiceKit';
import { BusinessError } from '@kit.BasicServicesKit';
try {
sensor.on(sensor.SensorId.ACCELEROMETER, (data: sensor.AccelerometerResponse) => {
console.info("Succeeded in obtaining data. x: " + data.x + " y: " + data.y + " z: " + data.z);
}, { interval: 100000000 });
} catch (error) {
let e: BusinessError = error as BusinessError;
console.error(`Failed to get sensorList. Code: ${e.code}, message: ${e.message}`);
}
二、传感器权限
鸿蒙权限查询网址为文档中心
这里就使用了加速度计,地磁的权限,陀螺仪。其中地磁和加速度计使用的同一个权限,估计地磁是用加速度计进行计算而得。
下面为module.json5文件中权限代码
"requestPermissions": [
{
"name" : "ohos.permission.ACCELEROMETER",
"reason": "$string:EntryAbility_label",
"usedScene": {
"abilities": [
"FormAbility"
],
"when":"inuse"
}
},
{
"name": "ohos.permission.GYROSCOPE",
"reason": "$string:EntryAbility_label",
"usedScene": {
"abilities": ["EntryAbility"], // 替换为你的Ability名称
"when": "inuse"
}
}
]
三、所有源码,实现了按下监测按钮,将加速度计,地磁,陀螺仪的数据显示到页面上的功能
以下为Index.ets的代码
import { sensor } from '@kit.SensorServiceKit';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct Index {
@State message: string = 'Hello World';
@State acc_x: string = '';
@State acc_y: string = '';
@State acc_z: string = '';
@State mag_x: string = '';
@State mag_y: string = '';
@State mag_z: string = '';
@State gyr_x: string = '';
@State gyr_y: string = '';
@State gyr_z: string = '';
myCheck()
{
sensor.getSensorList((error: BusinessError, data: Array<sensor.Sensor>) => {
if (error) {
console.error('getSensorList failed');
} else {
console.info('getSensorList success');
for (let i = 0; i < data.length; i++) {
console.info("sersorprint:",JSON.stringify(data[i]));
}
/*
for (let i = 0; i < data.length; i++) {
let tmp =JSON.stringify(data[i]);
if(tmp.includes("acc_s") || tmp.includes("gyro_s") || tmp.includes("als_s") || tmp.includes("mag_s"))
{
console.info("sersorprint:",tmp);
}
}
* */
}
});
}
myListenAcc()
{
try {
sensor.on(sensor.SensorId.ACCELEROMETER, (data: sensor.AccelerometerResponse) => {
console.info("Succeeded in ACCELEROMETER data. x: " + data.x + " y: " + data.y + " z: " + data.z);
this.acc_x = data.x.toString().substring(0, 5);;
this.acc_y = data.y.toString().substring(0, 5);;
this.acc_z = data.z.toString().substring(0, 5);;
}, { interval: 1000000000 });
/*
sensor.once(sensor.SensorId.ACCELEROMETER, (data: sensor.AccelerometerResponse) => {
console.info("Succeeded in obtaining data. x: " + data.x + " y: " + data.y + " z: " + data.z);
});
*/
} catch (error) {
let e: BusinessError = error as BusinessError;
console.error(`Failed to get sensorList. Code: ${e.code}, message: ${e.message}`);
}
}
myListenMAG() {
try {
// 使用磁力计传感器ID和正确的数据类型
sensor.on(sensor.SensorId.MAGNETIC_FIELD, (data: sensor.MagneticFieldResponse) => {
console.info(
"磁力计数据: " +
"X=" + data.x.toFixed(2) + " μT, " + // X轴磁场强度(微特斯拉)
"Y=" + data.y.toFixed(2) + " μT, " + // Y轴磁场强度
"Z=" + data.z.toFixed(2) + " μT" // Z轴磁场强度
);
this.mag_x = data.x.toString().substring(0, 5);;
this.mag_y = data.y.toString().substring(0, 5);;
this.mag_z = data.z.toString().substring(0, 5);;
}, { interval: 1000000000 }); // 采样间隔200ms(单位:纳秒)
} catch (error) {
let e: BusinessError = error as BusinessError;
console.error(`磁力计监听失败. Code: ${e.code}, message: ${e.message}`);
}
}
myListenGYR() {
try {
// 使用陀螺仪传感器ID和正确的数据类型
sensor.on(sensor.SensorId.GYROSCOPE, (data: sensor.GyroscopeResponse) => {
console.info(
"陀螺仪数据: " +
"X=" + data.x.toFixed(4) + " rad/s, " + // X轴角速度(弧度/秒)
"Y=" + data.y.toFixed(4) + " rad/s, " + // Y轴角速度
"Z=" + data.z.toFixed(4) + " rad/s" // Z轴角速度
);
this.gyr_x = data.x.toString().substring(0, 5);;
this.gyr_y = data.y.toString().substring(0, 5);;
this.gyr_z = data.z.toString().substring(0, 5);;
}, { interval: 100000000 }); // 采样间隔100ms(单位:纳秒)
} catch (error) {
let e: BusinessError = error as BusinessError;
console.error(`陀螺仪监听失败. Code: ${e.code}, message: ${e.message}`);
}
}
build() {
RelativeContainer() {
Column() {
// 加速度计数据卡片
Column() {
Text('加速度计 (m/s²)')
.fontSize(18)
.fontColor('#1E90FF')
.margin({ bottom: 8 })
Row() {
Column() {
Text('X轴')
.fontSize(14)
.fontColor('#666')
Text(this.acc_x)
.fontSize(16)
.fontWeight(FontWeight.Bold)
}
.width('33%')
.alignItems(HorizontalAlign.Center)
Column() {
Text('Y轴')
.fontSize(14)
.fontColor('#666')
Text(this.acc_y)
.fontSize(16)
.fontWeight(FontWeight.Bold)
}
.width('33%')
.alignItems(HorizontalAlign.Center)
Column() {
Text('Z轴')
.fontSize(14)
.fontColor('#666')
Text(this.acc_z)
.fontSize(16)
.fontWeight(FontWeight.Bold)
}
.width('33%')
.alignItems(HorizontalAlign.Center)
}
.width('100%')
.margin({ bottom: 16 })
}
.padding(12)
.backgroundColor('#F5F5F5')
.borderRadius(8)
.width('96%')
// 磁力计数据卡片
Column() {
Text('磁力计 (μT)')
.fontSize(18)
.fontColor('#FF6B81')
.margin({ bottom: 8 })
Row() {
Column() {
Text('X轴')
.fontSize(14)
.fontColor('#666')
Text(this.mag_x)
.fontSize(16)
.fontWeight(FontWeight.Bold)
}
.width('33%')
.alignItems(HorizontalAlign.Center)
Column() {
Text('Y轴')
.fontSize(14)
.fontColor('#666')
Text(this.mag_y)
.fontSize(16)
.fontWeight(FontWeight.Bold)
}
.width('33%')
.alignItems(HorizontalAlign.Center)
Column() {
Text('Z轴')
.fontSize(14)
.fontColor('#666')
Text(this.mag_z)
.fontSize(16)
.fontWeight(FontWeight.Bold)
}
.width('33%')
.alignItems(HorizontalAlign.Center)
}
.width('100%')
.margin({ bottom: 16 })
}
.padding(12)
.backgroundColor('#FFF0F5')
.borderRadius(8)
.width('96%')
// 陀螺仪数据卡片
Column() {
Text('陀螺仪 (rad/s)')
.fontSize(18)
.fontColor('#32CD32')
.margin({ bottom: 8 })
Row() {
Column() {
Text('X轴')
.fontSize(14)
.fontColor('#666')
Text(this.gyr_x)
.fontSize(16)
.fontWeight(FontWeight.Bold)
}
.width('33%')
.alignItems(HorizontalAlign.Center)
Column() {
Text('Y轴')
.fontSize(14)
.fontColor('#666')
Text(this.gyr_y)
.fontSize(16)
.fontWeight(FontWeight.Bold)
}
.width('33%')
.alignItems(HorizontalAlign.Center)
Column() {
Text('Z轴')
.fontSize(14)
.fontColor('#666')
Text(this.gyr_z)
.fontSize(16)
.fontWeight(FontWeight.Bold)
}
.width('33%')
.alignItems(HorizontalAlign.Center)
}
.width('100%')
}
.padding(12)
.backgroundColor('#F0FFF0')
.borderRadius(8)
.width('96%')
Column() {
Button('开始监测')
.width(150)
.height(50)
.margin(10)
.onClick(() => {
this.myCheck()
this.myListenAcc();
this.myListenMAG();
this.myListenGYR();
})
}
}
.width('100%')
.padding(8)
}
}
}
四、显示效果