Android的大部分手机中都有传感器,传感器类型有方向、加速度(重力)、光线、磁场、距离(临近性)、温度等。

方向传感器:   Sensor.TYPE_ORIENTATION

加速度(重力)传感器: Sensor.TYPE_ACCELEROMETER

光线传感器:    Sensor.TYPE_LIGHT

磁场传感器:   Sensor.TYPE_MAGNETIC_FIELD

距离(临近性)传感器: Sensor.TYPE_PROXIMITY

温度传感器:   Sensor.TYPE_TEMPERATURE

//获取某种类型的感应器

Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

//注册监听,获取传感器变化值

sensorManager.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_GAME);

上面第三个参数为采样率:最快、游戏、普通、用户界面。当应用程序请求特定的采样率时,其实只是对传感器子系统的一个建议,不保证特定的采样率可用。

最快: SensorManager.SENSOR_DELAY_FASTEST

最低延迟,一般不是特别敏感的处理不推荐使用,该种模式可能造成手机电力大量消耗,由于传递的为原始数据,算法不处理好将会影响游戏逻辑和UI的性能。

游戏: SensorManager.SENSOR_DELAY_GAME

游戏延迟,一般绝大多数的实时性较高的游戏都使用该级别。

普通: SensorManager.SENSOR_DELAY_NORMAL

标准延迟,对于一般的益智类或EASY级别的游戏可以使用,但过低的采样率可能对一些赛车类游戏有跳帧现象。

用户界面: SensorManager.SENSOR_DELAY_UI

一般对于屏幕方向自动旋转使用,相对节省电能和逻辑处理,一般游戏开发中我们不使用。

使用传感器做应用的难点在于获取数据后如何处理,获得相应需要的效果,这里涉及很多数学物理的知识……

下面使用一个代码实例演示如何获取方向和磁场强度的数据:

package com.magnetic;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView; public class MainActivity extends Activity {
private TextView magneticView;
private TextView orientationView;
private TextView totalMageticView;
private SensorManager sensorManager;
private MySensorEventListener sensorEventListener; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); sensorEventListener = new MySensorEventListener();
magneticView = (TextView) this.findViewById(R.id.magneticView);
orientationView = (TextView) this.findViewById(R.id.orientationView);
totalMageticView=(TextView) this.findViewById(R.id.totalMageticView);
//获取感应器管理器
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
}
@Override
protected void onResume()
{
//获取方向传感器
@SuppressWarnings("deprecation")
Sensor orientationSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
sensorManager.registerListener(sensorEventListener, orientationSensor, SensorManager.SENSOR_DELAY_NORMAL); //获取加速度传感器
Sensor accelerometerSensor = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
sensorManager.registerListener(sensorEventListener, accelerometerSensor, SensorManager.SENSOR_DELAY_NORMAL);
super.onResume();
} @Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
} private final class MySensorEventListener implements SensorEventListener
{
//可以得到传感器实时测量出来的变化值
@Override
public void onSensorChanged(SensorEvent event)
{
//得到方向的值
if(event.sensor.getType()==Sensor.TYPE_ORIENTATION)
{
float x = event.values[SensorManager.DATA_X];
float y = event.values[SensorManager.DATA_Y];
float z = event.values[SensorManager.DATA_Z];
orientationView.setText("方向: " + x + ", " + y + ", " + z);
}
//得到加速度的值
else if(event.sensor.getType()==Sensor.TYPE_MAGNETIC_FIELD)
{
float x = event.values[SensorManager.DATA_X];
float y = event.values[SensorManager.DATA_Y];
float z = event.values[SensorManager.DATA_Z];
magneticView.setText("合磁场强度X、Y、Z分量: " + x + ", " + y + ", " + z);
//计算和磁场强度
float total=(float)(Math.sqrt(Math.pow(x,2)+Math.pow(y,2)+Math.pow(z, 2)));
totalMageticView.setText("合磁场强度: " + total);
}
}
//重写变化
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy)
{
}
} //暂停传感器的捕获
@Override
protected void onPause()
{
sensorManager.unregisterListener(sensorEventListener);
super.onPause();
} }
<?xml version="1.0" encoding="utf-8"?>
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"> <TableRow>
<TextView
android:id="@+id/orientationView"
android:text="方向传感器:"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
/>
</TableRow>
<TableRow>
<TextView
android:id="@+id/magneticView"
android:text="磁传感器:"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</TableRow>
<TableRow>
<TextView
android:id="@+id/totalMageticView"
android:text="合磁强度:"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</TableRow>
</TableLayout>

Android之使用传感器获取相应数据的更多相关文章

  1. android客户端从服务器端获取json数据并解析的实现代码

    今天总结一下android客户端从服务器端获取json数据的实现代码,需要的朋友可以参考下   首先客户端从服务器端获取json数据 1.利用HttpUrlConnection /** * 从指定的U ...

  2. (转)android客户端从服务器端获取json数据并解析的实现代码

    今天总结一下android客户端从服务器端获取json数据的实现代码,需要的朋友可以参考下       首先客户端从服务器端获取json数据 1.利用HttpUrlConnection   复制代码 ...

  3. android客户端从服务器端获取json数据并解析的实现代码(重要)

    首先客户端从服务器端获取json数据 1.利用HttpUrlConnection /** * 从指定的URL中获取数组 * @param urlPath * @return * @throws Exc ...

  4. android通过httpClient请求获取JSON数据并且解析

    使用.net创建一个ashx文件,并response.write  json格式 public void ProcessRequest(HttpContext context) { context.R ...

  5. Android 将从网络获取的数据缓存到私有文件

    1:activity_main.xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/androi ...

  6. ListView获取网络数据并展示优化练习

    权限: <uses-permission android:name="android.permission.INTERNET"></uses-permission ...

  7. Android网络开发之实时获取最新数据

    在实际开发中更多的是需要我们实时获取最新数据,比如道路流量.实时天气信息等,这时就需要通过一个线程来控制视图的更新. 示例:我们首先创建一个网页来显示系统当前的时间,然后在Android程序中每隔5秒 ...

  8. Android中通过代码获取arrays.xml文件中的数据

    android工程res/valuse文件夹下的arrays.xml文件中用于放各种数组数据,比如字符串数组.整型数组等,数组中的数据可能是具体的值,也有可能是对资源数据的引用,下面针对这两种情况通过 ...

  9. Android中获取网络数据时的分页加载

    //此实在Fragment中实现的,黄色部分为自动加载,红色部分是需要注意的和手动加载,    蓝色部分是睡眠时间,自我感觉不用写  ,还有就是手动加载时,不知道为什么进去后显示的就是最后一行,求大神 ...

随机推荐

  1. OAuth2.0 知多少(好)

    https://www.cnblogs.com/sheng-jie/p/6564520.html 简书集成的社交登录,大大简化了我们的注册登录流程,真是一号在手上网无忧啊.这看似简单的集成,但背后的技 ...

  2. AtCoder Beginner Contest 088 (ABC)

    A - Infinite Coins 题目链接:https://abc088.contest.atcoder.jp/tasks/abc088_a Time limit : 2sec / Memory ...

  3. <转>jmeter(八)断言

    本博客转载自:http://www.cnblogs.com/imyalost/category/846346.html 个人感觉不错,对jmeter讲解非常详细,担心以后找不到了,所以转发出来,留着慢 ...

  4. SQLServer将服务器A表写到服务器B表

       不同服务器数据库之间的数据操作    --创建链接服务器  exec sp_addlinkedserver  'ITSV ', ' ', 'SQLOLEDB ', '远程服务器名或ip地址 '  ...

  5. 怎样从外网访问内网Node.js?

    本地安装了一个Node.js,只能在局域网内访问,怎样从外网也能访问到本地的Node.js呢?本文将介绍具体的实现步骤. 1. 准备工作 1.1 安装并启动Node.js 默认安装的Node.js端口 ...

  6. 4~20mA

    4~20mA电流输出芯片XTR111完整电路 0-5v转0-20ma和0-5v转4-20ma 压控恒流源电路 4-20mA电流环路发送器入门

  7. HFA and outhandler differentiate or not

    better trouble shooting auto-open accidently? HFA not stable? check code modification ASAP!!!

  8. Python 2、8、10、16进制间的转换

    进制转换一直是初学者所头疼的,下面就简单的列出各进制之间都是以什么方式转换的. # print('2-->8: ', oct(int('0b1010', 2))) # 2-10-8 # prin ...

  9. Cookie&Session与自定义session

    cookie与session的区别? cookie是保存在浏览器端的键值对 session是保存在服务器端的键值对 session依赖于cookie 摘自: http://bubkoo.com/201 ...

  10. 【4OpenCV】OpenCV和RTSP的综合研究

    一.RTSP是什么?用来干什么? RTSP(Real Time Streaming Protocol),RFC2326,实时流传输协议,是TCP/IP协议体系中的一个应用层协议,由哥伦比亚大学.网景和 ...