android传感器

In this tutorial, we’ll be digging deep into the world of Android Sensors. Our smartphones are much more than just speed, UI and animations.

在本教程中,我们将深入研究Android传感器的世界。 我们的智能手机不仅限于速度,UI和动画。

Android传感器 (Android Sensors)

Android Sensors contains properties to detect changes in the environment such as light, proximity, rotation, movements, magnetic fields and much more.

Android Sensors包含可检测环境变化的属性,例如光线,接近度,旋转,运动,磁场等。

Broadly speaking, the Android Sensors fall under the following categories:

从广义上讲,Android传感器属于以下类别:

  • Environment Sensors环境传感器
  • Motion Sensors运动传感器
  • Orientation and Position Sensors方向和位置传感器

To access the various Sensors in Android, you must use the SensorManager class.

要访问Android中的各种Sensor,必须使用SensorManager类。

Following code shows how to initialize a SensorManager:

以下代码显示了如何初始化SensorManager

SensorManager sensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);

Next, you can use the Sensor class to instantiate the specific Sensor.

接下来,您可以使用Sensor类来实例化特定的Sensor。

Sensor lightSensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);

Next, you can register the sensor using the following code:

接下来,您可以使用以下代码注册传感器:

sensorManager.registerListener(this, lightSensor,SensorManager.SENSOR_DELAY_NORMAL);

It’s recommended to register the listener in the onResume() method and unregister it in the onPause method in order to save battery power.

建议您在onResume()方法中注册侦听器,然后在onPause方法中取消注册侦听器,以节省电池电量。

In order to listen to sensor events, you can implement the SensorEventListener interface in the activity.

为了监听传感器事件,您可以在活动中实现SensorEventListener接口。

You need to override the following methods for that:

您需要为此重写以下方法:

@Overridepublic void onSensorChanged(SensorEvent event) {}@Overridepublic void onAccuracyChanged(Sensor sensor, int accuracy) {}

To get a list of all the available sensors on the device, use the following code:

要获取设备上所有可用传感器的列表,请使用以下代码:

List<Sensor> sensorList = sensorManager.getSensorList(Sensor.TYPE_ALL);String sensorInfo = "";
for (Sensor s : sensorList){sensorInfo= sensorInfo + s.getName()+ "\n";
}

In the next section, we’ll discuss some of the common types of Sensors.

在下一节中,我们将讨论一些常见的传感器类型。

Android传感器类型 (Android Sensors Types)

  • Photometer is used to sense and control the brightness. Besides, there are sensors for pressure, humidity, and temperature.光度计用于感应和控制亮度。 此外,还有压力,湿度和温度传感器。
  • For movements, Accelerometer is used to detect shakes/tilt gestures.对于运动, 加速度计用于检测摇动/倾斜手势。
  • Proximity Sensors are used to detect how close the object is to the device. It’s commonly present in Call Applications. As you bring the phone close to the ear, the screen goes black, thanks to this sensor. Though the maximum range of proximity is 5 cms.接近传感器用于检测物体与设备的距离。 它通常出现在呼叫应用程序中。 当您将手机靠近耳朵时,借助此传感器,屏幕会变黑。 虽然最大接近范围是5厘米。
  • Gyroscope is used to measure rotation/spin. Gravity sensors are used to measure the force of gravity.陀螺仪用于测量旋转/旋转。 重力传感器用于测量重力。
  • Magneto Meter is used to get the device position.磁力仪用于获取设备位置。
  • Pedometer is used to detect the number of steps the user takes.计步器用于检测用户执行的步数。

Following image depicts a few sensor types and their event data values with the respective formats.

下图描绘了几种传感器类型及其事件数据值以及相应的格式。

Android Sensors Types

Android传感器类型

如何检查Android Sensor是否可用? (How to Check if Android Sensor is Available?)

Some devices don’t support certain Sensors. So you can simply add the permissions in the Manifest file.
Google ensures that the Application on the Play store would not be visible to users with unsupported devices.

某些设备不支持某些传感器。 因此,您只需在清单文件中添加权限。
Google确保Play商店中的应用程序对于不支持设备的用户不可见。

<uses-feature android:name="android.hardware.accelerometer"android:required="true" /><uses-feature android:name="android.hardware.sensor.proximity"android:required="true" /><uses-feature android:name="android.hardware.sensor.gyroscope"android:required="true" />
Accelerometer is not available on Android Emulators.
加速度计在Android模拟器上不可用。

In the next section, we’ll implement certain sensors in our Android Application.

在下一部分中,我们将在Android应用程序中实现某些传感器。

Android传感器示例项目结构 (Android Sensors Example Project Structure)

Android Sensor Example Project Structure

Android Sensor示例项目结构

Android传感器示例代码 (Android Sensors Example Code)

The code for the activity_main.xml is given below:

下面给出了activity_main.xml的代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"xmlns:app="https://schemas.android.com/apk/res-auto"xmlns:tools="https://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_gravity="center"android:layout_margin="16dp"android:gravity="center"android:orientation="vertical"tools:context=".MainActivity"><Buttonandroid:id="@+id/btnAccelerometer"android:layout_width="wrap_content"android:layout_height="wrap_content"android:onClick="accelerometerSensorOnClick"android:text="Accelerometer" /><Buttonandroid:id="@+id/btnProximity"android:layout_width="wrap_content"android:layout_height="wrap_content"android:onClick="proximitySensorOnClick"android:text="Proximity Sensor" /><Buttonandroid:id="@+id/btnGyro"android:layout_width="wrap_content"android:layout_height="wrap_content"android:onClick="gyroscopeSensorOnClick"android:text="Gyroscope" /><Buttonandroid:id="@+id/btnLightSensor"android:layout_width="wrap_content"android:layout_height="wrap_content"android:onClick="lightSensorOnClick"android:text="Light Sensor" /><Buttonandroid:id="@+id/btnStepCounterOnClick"android:layout_width="wrap_content"android:layout_height="wrap_content"android:onClick="stepCounterOnClick"android:text="Step Counter Sensor" /><Buttonandroid:id="@+id/btnAmbientTemp"android:layout_width="wrap_content"android:layout_height="wrap_content"android:onClick="ambientTempSensorOnClick"android:text="Ambient Temperature Sensor" /><TextViewandroid:id="@+id/tvResult"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginTop="8dp"android:text="Values would be entered here..." /></LinearLayout>

The code for the MainActivity.java is given below:

MainActivity.java的代码如下:

package com.journaldev.androidsensors;import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;public class MainActivity extends AppCompatActivity implements SensorEventListener {private TextView textView;private SensorManager sensorManager;private Sensor accelerometerSensor;private Sensor proximitySensor;private Sensor lightSensor;private Sensor stepCounterSensor;private Sensor tempSensor;private Sensor gyroscopeSensor;private int currentSensor;private long lastUpdate = 0;private float last_x, last_y, last_z;private static final int SHAKE_THRESHOLD = 600;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);textView = findViewById(R.id.tvResult);sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);accelerometerSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);proximitySensor = sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);lightSensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);stepCounterSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR);gyroscopeSensor = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);tempSensor = sensorManager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE);}public boolean checkSensorAvailability(int sensorType) {boolean isSensor = false;if (sensorManager.getDefaultSensor(sensorType) != null) {isSensor = true;}return isSensor;}@Overridepublic void onSensorChanged(SensorEvent event) {if (event.sensor.getType() == currentSensor) {if (currentSensor == Sensor.TYPE_LIGHT) {float valueZ = event.values[0];textView.setText("Brightness " + valueZ);} else if (currentSensor == Sensor.TYPE_PROXIMITY) {float distance = event.values[0];textView.setText("Proximity " + distance);} else if (currentSensor == Sensor.TYPE_STEP_DETECTOR) {float steps = event.values[0];textView.setText("Steps : " + steps);} else if (currentSensor == Sensor.TYPE_ACCELEROMETER) {float x = event.values[0];float y = event.values[1];float z = event.values[2];long curTime = System.currentTimeMillis();if ((curTime - lastUpdate) > 100) {long diffTime = (curTime - lastUpdate);lastUpdate = curTime;float speed = Math.abs(x + y + z - last_x - last_y - last_z) / diffTime * 10000;if (speed > SHAKE_THRESHOLD) {Toast.makeText(getApplicationContext(), "Your phone just shook", Toast.LENGTH_LONG).show();}last_x = x;last_y = y;last_z = z;}} else if (currentSensor == Sensor.TYPE_GYROSCOPE) {if (event.values[2] > 0.5f) {textView.setText("Anti Clock");} else if (event.values[2] < -0.5f) {textView.setText("Clock");}} else if (currentSensor == Sensor.TYPE_AMBIENT_TEMPERATURE) {textView.setText("Ambient Temp in Celsius :" + event.values[0]);}}}@Overridepublic void onAccuracyChanged(Sensor sensor, int accuracy) {}public void accelerometerSensorOnClick(View view) {if (checkSensorAvailability(Sensor.TYPE_ACCELEROMETER)) {currentSensor = Sensor.TYPE_ACCELEROMETER;}textView.setText("Accelerometer not available");}public void proximitySensorOnClick(View view) {if (checkSensorAvailability(Sensor.TYPE_PROXIMITY)) {currentSensor = Sensor.TYPE_PROXIMITY;}textView.setText("Proximity Sensor not available");}public void gyroscopeSensorOnClick(View view) {if (checkSensorAvailability(Sensor.TYPE_GYROSCOPE)) {currentSensor = Sensor.TYPE_GYROSCOPE;} else {textView.setText("Gyroscope Sensor not available");}}public void lightSensorOnClick(View view) {if (checkSensorAvailability(Sensor.TYPE_LIGHT)) {currentSensor = Sensor.TYPE_LIGHT;} else {textView.setText("Light Sensor not available");}}public void stepCounterOnClick(View view) {if (checkSensorAvailability(Sensor.TYPE_STEP_DETECTOR)) {currentSensor = Sensor.TYPE_STEP_DETECTOR;} else {textView.setText("Step Counter Sensor not available");}}public void ambientTempSensorOnClick(View view) {if (checkSensorAvailability(Sensor.TYPE_AMBIENT_TEMPERATURE)) {currentSensor = Sensor.TYPE_AMBIENT_TEMPERATURE;} else {textView.setText("Ambient Temperature Sensor not available");}}@Overrideprotected void onResume() {super.onResume();sensorManager.registerListener(this, accelerometerSensor,SensorManager.SENSOR_DELAY_NORMAL);sensorManager.registerListener(this, lightSensor,SensorManager.SENSOR_DELAY_NORMAL);sensorManager.registerListener(this, proximitySensor,SensorManager.SENSOR_DELAY_NORMAL);sensorManager.registerListener(this, stepCounterSensor,SensorManager.SENSOR_DELAY_NORMAL);sensorManager.registerListener(this, tempSensor,SensorManager.SENSOR_DELAY_NORMAL);sensorManager.registerListener(this, gyroscopeSensor,SensorManager.SENSOR_DELAY_NORMAL);}@Overrideprotected void onPause() {super.onPause();sensorManager.unregisterListener(this);}}

For the accelerometer, we need to get the position of all the three coordinates from each of the three axes. The accelerometer is so sensitive that it keeps updating these points.

对于加速度计,我们需要从三个轴中的每个轴获取所有三个坐标的位置。 加速度计非常灵敏,因此会不断更新这些点。

In order to detect whether it’s a shake or not, we take the difference of the points within a given time frame to detect how quickly they moved.

为了检测是否晃动,我们采用给定时间范围内的点差来检测它们移动的速度。

The gyroscope detects whether the phone is rotated anticlockwise or clockwise in the z plane.

陀螺仪检测手机在z平面中是逆时针方向还是顺时针方向旋转。

Light sensor’s hardware is located at the top of the phone to the right of the front camera lens.
光传感器的硬件位于手机顶部,位于前置摄像头镜头的右侧。

The output of the above application in action is given below. Since we cannot show a live demo, we’ve just displayed the sensor value for brightness.

下面给出了上面应用程序的输出。 由于我们无法显示实时演示,因此我们只显示了亮度的传感器值。

Android Sensors App Output

Android传感器应用程序输出

That brings an end to this android sensors tutorial. You can download the project from the link below.

这结束了本android传感器教程。 您可以从下面的链接下载项目。

AndroidSensorsAndroid传感器
Github Project LinkGithub项目链接

翻译自: https://www.journaldev.com/25691/android-sensors

android传感器

android传感器_Android传感器相关推荐

  1. android 气压传感器_Android传感器教程:气压计传感器

    android 气压传感器 我认为最有趣的主题之一是如何在Android中使用Sensor . 如今,我们的智能手机充满了传感器,我们可以用它来控制我们的应用程序. 最常见的传感器是: 全球定位系统 ...

  2. Android Sensors (2) 传感器API的使用

    识别传感器和传感器能力 Android sensor framework提供了一些方法,使得你在运行时可以方便地查看设备上都有哪些传感器. API也提供了一些让你获取每个传感器性能的方法. 首先,你需 ...

  3. Android 利用方向传感器获得手机的相对角度

    1.android 的坐标系是如何定义x, y z 轴的. x轴的方向是沿着屏幕的水平方向从左向右,如果手机不是正方形的话,较短的边需要水平放置,较长的边需要垂直放置. Y轴的方向是从屏幕的左下角开始 ...

  4. 玩转Android之加速度传感器的使用,模仿微信摇一摇

    Android系统带的传感器有很多种,最常见的莫过于微信的摇一摇了,那么今天我们就来看看Anroid中传感器的使用,做一个类似于微信摇一摇的效果. OK ,废话不多说,我们就先来看看效果图吧: 当我摇 ...

  5. 我的Android进阶之旅------Android利用Sensor(传感器)实现水平仪功能的小例

    这里介绍的水平仪,指的是比较传统的气泡水平仪,在一个透明圆盘内充满液体,液体中留有一个气泡,当一端翘起时,该气泡就会浮向翘起的一端.    利用方向传感器返回的第一个参数,实现了一个指南针小应用.   ...

  6. android 获取加速度传感器值,Android开发获取传感器数据的方法示例【加速度传感器,磁场传感器,光线传感器,方向传感器】...

    本文实例讲述了Android开发获取传感器数据的方法.分享给大家供大家参考,具体如下: package mobile.android.sensor; import java.util.List; im ...

  7. Android笔记 方向传感器

    1传感器概念 图片资源来自传智播客张泽华视频114集 demo 1布局一张图片 网上随便找一张指南针图片 <RelativeLayout xmlns:android="http://s ...

  8. android开发中磁场传感器,Android开发获取传感器数据的方法示例【加速度传感器,磁场传感器,光线传感器,方向传感器】...

    本文实例讲述了Android开发获取传感器数据的方法.分享给大家供大家参考,具体如下: package mobile.android.sensor; import java.util.List; im ...

  9. Android 如何获取传感器的数据

    1 传感器简介 传感器 Sensor 是一种检测装置,能感受到被测量的信息,并能将感受到的信息,按一定规律变换成为电信号或其他所需形式的信息输出,以满足信息的传输.处理.存储.显示.记录和控制等要求. ...

最新文章

  1. Java:多线程之线程池
  2. 排序算法_桶排序(箱排序)
  3. 如何让你用 Python 年薪 40 万?答案早就写到 JD 上了
  4. 微软Azure的access control - IAM
  5. ubuntu15.10下code::blocks设置运行窗口为gnome命令行
  6. html css页脚代码,HTML CSS - 页脚 - 下面的空格
  7. 关于互斥锁,条件变量的内核源码解析
  8. python冒泡排序实验报告_python中的冒泡排序
  9. Spring容器启动时出现Failed to read schema document错误
  10. 读书笔记-----Oracle字符处理函数列表
  11. Linux命令 查看端口占用情况
  12. 郑君里 信号与系统,傅里叶级数,逼近函数仿真,吉布斯验证
  13. 如何利用区块链技术保护知识产权
  14. 爬虫 爬取百思不得姐网站
  15. 云科技时代力作:《读懂新基建,数字技术带来全民机遇》上市
  16. 微信分享不显示右边缩略图
  17. ES6 Set() 数组去重
  18. Amadis发布OLA支付处理标准
  19. 分享一个破解百度网盘下载速度的工具
  20. 龙芯2k1000-pmon(6)- spiflash的底层操作

热门文章

  1. 王者调整期选股技术之喇叭花开
  2. Java程序猿从笨鸟到菜鸟之(九十二)深入java虚拟机(一)——java虚拟机底层结构具体解释...
  3. Visual Studio 2013中因Browser Link引起的Javascript错误
  4. spring学习笔记(六)
  5. WPF在一个窗口中实现多个视图
  6. Web前端-JavaScript基础教程下
  7. Mysql-sql_mode
  8. 收缩Vcenter数据库
  9. 20169212《Linux内核原理及分析》第十二周作业
  10. Android Studio类中实现Serializable自动生成serialVersionUID