Android 简明教程

Android - Sensors

大多数安卓设备都内置有测量运动、方向和各种环境条件的传感器。Android 平台支持三大类传感器。

Most of the android devices have built-in sensors that measure motion, orientation, and various environmental condition. The android platform supports three broad categories of sensors.

  1. Motion Sensors

  2. Environmental sensors

  3. Position sensors

一些传感器是基于硬件的,一些是基于软件的传感器。无论传感器是什么,Android 允许我们获取这些传感器的原始数据并在我们的应用程序中使用它。为此,Android 为我们提供了一些类。

Some of the sensors are hardware based and some are software based sensors. Whatever the sensor is, android allows us to get the raw data from these sensors and use it in our application. For this android provides us with some classes.

Android 提供了 SensorManager 和 Sensor 类来在我们应用程序中使用传感器。要使用传感器,你需要做的第一件事是实例化 SensorManager 类的对象。可以通过以下方法实现。

Android provides SensorManager and Sensor classes to use the sensors in our application. In order to use sensors, first thing you need to do is to instantiate the object of SensorManager class. It can be achieved as follows.

SensorManager sMgr;
sMgr = (SensorManager)this.getSystemService(SENSOR_SERVICE);

你需要做的下一件事是通过调用 SensorManager 类的 getDefaultSensor() 方法,实例化 Sensor 类的对象。它的语法如下:

The next thing you need to do is to instantiate the object of Sensor class by calling the getDefaultSensor() method of the SensorManager class. Its syntax is given below −

Sensor light;
light = sMgr.getDefaultSensor(Sensor.TYPE_LIGHT);

声明该传感器后,你需要注册它的监听器并重写 onAccuracyChanged 和 onSensorChanged 这两个方法。它语法如下:

Once that sensor is declared , you need to register its listener and override two methods which are onAccuracyChanged and onSensorChanged. Its syntax is as follows −

sMgr.registerListener(this, light,SensorManager.SENSOR_DELAY_NORMAL);
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}

public void onSensorChanged(SensorEvent event) {
}

Getting list of sensors supported

你可以通过调用 getSensorList 方法来获取设备支持的传感器列表,该方法将返回一个传感器列表,其中包含传感器名称、版本号及更多信息。然后,你可以遍历列表以获取信息。它的语法如下:

You can get a list of sensors supported by your device by calling the getSensorList method, which will return a list of sensors containing their name and version number and much more information. You can then iterate the list to get the information. Its syntax is given below −

sMgr = (SensorManager)this.getSystemService(SENSOR_SERVICE);
List<Sensor> list = sMgr.getSensorList(Sensor.TYPE_ALL);
for(Sensor sensor: list){
}

除了这些方法,SensorManager 类还提供了其他方法来管理传感器框架。这些方法如下所列:

Apart from the these methods, there are other methods provided by the SensorManager class for managing sensors framework. These methods are listed below −

Sr.No

Method & description

1

getDefaultSensor(int type) This method get the default sensor for a given type.

2

getInclination(float[] I) This method computes the geomagnetic inclination angle in radians from the inclination matrix.

3

registerListener(SensorListener listener, int sensors, int rate) This method registers a listener for the sensor

4

unregisterListener(SensorEventListener listener, Sensor sensor) This method unregisters a listener for the sensors with which it is registered.

5

getOrientation(float[] R, float[] values) This method computes the device’s orientation based on the rotation matrix.

6

getAltitude(float p0, float p) This method computes the Altitude in meters from the atmospheric pressure and the pressure at sea level.

Example

下面是一个演示 SensorManager 类的用法示例。它创建了一个基础应用程序,让你能够查看设备上的传感器列表。

Here is an example demonstrating the use of SensorManager class. It creates a basic application that allows you to view the list of sensors on your device.

要使用此示例,你可以在实际设备或模拟器上运行此示例。

To experiment with this example , you can run this on an actual device or in an emulator.

Steps

Description

1

You will use Android studio to create an Android application under a package com.example.sairamkrishna.myapplication.

2

Modify src/MainActivity.java file to add necessary code.

3

Modify the res/layout/activity_main to add respective XML components.

4

Run the application and choose a running android device and install the application on it and verify the results.

下面是已修改的 MainActivity.java 的内容。

Following is the content of the modified MainActivity.java.

package com.example.sairamkrishna.myapplication;

import android.app.Activity;
import android.hardware.SensorManager;
import android.os.Bundle;

import android.util.Log;

import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import android.widget.TextView;

import java.util.List;
import android.hardware.Sensor;
import android.hardware.SensorManager;

public class MainActivity extends Activity {
   TextView tv1=null;
   private SensorManager mSensorManager;
   @Override

   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      tv1 = (TextView) findViewById(R.id.textView2);
      tv1.setVisibility(View.GONE);

      mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
      List<Sensor> mList= mSensorManager.getSensorList(Sensor.TYPE_ALL);

      for (int i = 1; i < mList.size(); i++) {
         tv1.setVisibility(View.VISIBLE);
         tv1.append("\n" + mList.get(i).getName() + "\n" + mList.get(i).getVendor() + "\n" + mList.get(i).getVersion());
      }
   }

   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
      // Inflate the menu; this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu.menu_main, menu);
      return true;
   }

   @Override
   public boolean onOptionsItemSelected(MenuItem item) {
      // Handle action bar item clicks here. The action bar will
      // automatically handle clicks on the Home/Up button, so long
      // as you specify a parent activity in AndroidManifest.xml.

      int id = item.getItemId();

      //noinspection SimplifiableIfStatement
      if (id == R.id.action_settings) {
         return true;
      }
      return super.onOptionsItemSelected(item);
   }
}

下面是经过修改的 xml 的内容 activity_main.xml

Following is the modified content of the xml activity_main.xml.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
   android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   android:paddingBottom="@dimen/activity_vertical_margin"
   tools:context=".MainActivity"
   android:transitionGroup="true">

   <TextView android:text="Sensor " android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/textview"
      android:textSize="35dp"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true" />

   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Tutorials point"
      android:id="@+id/textView"
      android:layout_below="@+id/textview"
      android:layout_centerHorizontal="true"
      android:textColor="#ff7aff24"
      android:textSize="35dp" />

   <ImageView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/imageView"
      android:src="@drawable/abc"
      android:layout_below="@+id/textView"
      android:layout_centerHorizontal="true"
      android:theme="@style/Base.TextAppearance.AppCompat" />

   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="New Text"
      android:id="@+id/textView2"
      android:layout_below="@+id/imageView"
      android:layout_alignParentBottom="true"
      android:layout_alignParentRight="true"
      android:layout_alignParentEnd="true"
      android:layout_alignParentLeft="true"
      android:layout_alignParentStart="true" />

</RelativeLayout>

以下是 res/values/string.xml 的内容。

Following is the content of the res/values/string.xml.

<resources>
   <string name="app_name">My Application</string>
   <string name="hello_world">Hello world!</string>
   <string name="action_settings">Settings</string>
</resources>

下面是 AndroidManifest.xml 文件的内容。

Following is the content of AndroidManifest.xml file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.sairamkrishna.myapplication" >
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >

      <activity
         android:name=".MainActivity"
         android:label="@string/app_name" >

         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>

      </activity>

   </application>
</manifest>

让我们尝试运行我们刚刚修改的应用程序。我假设你在进行环境设置时已创建了 AVD 。要从 Android Studio 运行该应用程序,请打开一个项目的活动文件,并单击工具栏中的运行图标。Android Studio 会将该应用程序安装在你的 AVD 上并启动它,如果你的设置和应用程序一切正常,它将显示以下模拟器窗口−

Let’s try to run our application we just modified. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project’s activity files and click Run icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window −

sensor

现在,如果你查看你的设备屏幕,你会看到设备支持的传感器列表以及它们的名称和版本以及其他信息。

Now if you will look at your device screen, you will see the list of sensors supported by your device along with their name and version and other information.

如果你在不同的设备上运行此应用程序,输出将是不同的,因为输出取决于设备支持的传感器数量。

If you would run this application on different devices, the output would be different because the output depends upon the number of sensors supported by your device.