说到传感器,还是有很多的,有加速度啊,光照啊,磁传感器等等。当然android手机之所以称为智能手机,少不了这几款传感器的功劳了。下面就学习下了,这里主要学习光照,加速度和磁。

新建工程emSensorStudy,布局如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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:orientation="vertical"
android:layout_margin="5dp"
tools:context="com.jared.emsensorsstudy.MainActivity"> <TextView
android:text="Hello Sensors"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="22dp"/> <Button
android:id="@+id/startLightSensor"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="启动LightSensor"
android:textAllCaps="false"/> <Button
android:id="@+id/startAccelerSensor"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="启动AccelerSensor"
android:textAllCaps="false"/> <Button
android:id="@+id/startMagneticSensor"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="启动MagneticSensor"
android:textAllCaps="false"/>
</LinearLayout>

添加LightSensor,AccelerSensor,MagnetiSensor的Activity,修改MainActivity代码如下:

package com.jared.emsensorsstudy;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button; public class MainActivity extends AppCompatActivity { private Button startLightSensorBtn;
private Button startAccelerSensorBtn;
private Button startMagneticSensorBtn; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); startLightSensorBtn = (Button)findViewById(R.id.startLightSensor);
startAccelerSensorBtn = (Button)findViewById(R.id.startAccelerSensor);
startMagneticSensorBtn = (Button)findViewById(R.id.startMagneticSensor); startLightSensorBtn.setOnClickListener(new myOnClickListener());
startAccelerSensorBtn.setOnClickListener(new myOnClickListener());
startMagneticSensorBtn.setOnClickListener(new myOnClickListener());
} private class myOnClickListener implements View.OnClickListener {
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.startAccelerSensor:
Intent intent1 = new Intent(getApplicationContext(), AccelerSensor.class);
startActivity(intent1);
break;
case R.id.startLightSensor:
Intent intent2 = new Intent(getApplicationContext(), LightSensor.class);
startActivity(intent2);
break;
case R.id.startMagneticSensor:
Intent intent3 = new Intent(getApplicationContext(), MagneticSensor.class);
startActivity(intent3);
break;
default:
break;
}
}
} }

先要实现Light的功能,先修改布局如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:layout_margin="10dp"
tools:context="com.jared.emsensorsstudy.LightSensor"> <TextView
android:id="@+id/light_level"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="22dp"/> </LinearLayout>

简单地实现了一个textview用来显示光照强度。接着修改LightSensor代码如下:

package com.jared.emsensorsstudy;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView; public class LightSensor extends AppCompatActivity { private SensorManager sensorManager;
private TextView lightLevel; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_light_sensor); lightLevel = (TextView)findViewById(R.id.light_level); initWithLight();
} @Override
protected void onDestroy() {
super.onDestroy();
if(sensorManager != null) {
sensorManager.unregisterListener(listener);
}
} public void initWithLight() {
sensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorManager.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_NORMAL);
} private SensorEventListener listener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
float value = sensorEvent.values[0];
lightLevel.setText("Currrent light level is "+value+"lx");
} @Override
public void onAccuracyChanged(Sensor sensor, int i) { }
};
}

这里先通过getSystemService获取sensor,然后通过注册一个listener来监听传感器的变化,当值有变化的时候会调用onSensorChanged方法,具体运行后,用手遮挡听筒附近的传感器,显示如下:

 
   

从上可见光照的效果很明显了。接着我们来试下加速度传感器。这里实现微信摇一摇功能,并且成功了震动。

修改布局如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
android:layout_margin="10dp"
tools:context="com.jared.emsensorsstudy.AccelerSensor"> <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="摇一摇获取更多哦!"
android:layout_gravity=""
android:textSize="22dp"/> <TextView
android:id="@+id/shack"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textSize="22dp"/> </LinearLayout>

接着添加代码如下:

package com.jared.emsensorsstudy;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView; public class AccelerSensor extends AppCompatActivity { private SensorManager sensorManager;
private TextView shackPhone;
private Vibrator vibrator; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_acceler_sensor);
shackPhone = (TextView)findViewById(R.id.shack); initWithAcceler();
} @Override
protected void onDestroy() {
super.onDestroy();
if(sensorManager != null) {
sensorManager.unregisterListener(listener);
}
} private void initWithAcceler() {
sensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorManager.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_NORMAL);
vibrator = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
} private SensorEventListener listener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
float xValue = Math.abs(sensorEvent.values[0]);
float yValue = Math.abs(sensorEvent.values[1]);
float zValue = Math.abs(sensorEvent.values[2]);
int medumValue = 19;
if(xValue > medumValue || yValue > medumValue || zValue > medumValue) {
vibrator.vibrate(200);
shackPhone.setText("恭喜你摇一摇成功,新年快乐!");
} else {
//Toast.makeText(getApplicationContext(), "请使劲摇哦!", Toast.LENGTH_SHORT).show();
}
} @Override
public void onAccuracyChanged(Sensor sensor, int i) { }
};
}

这里的代码和LightSensor的代码差不多,主要是当三个方向的加速度大于19的时候就表示在摇动了,然后震动下手机就ok了。效果如下:

 
  

最后来学习下magneticSensor了。这里实现个compass。首先就是提供一张图片了,修改布局如下:

<?xml version="1.0" encoding="utf-8"?>
<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:layout_margin="10dp"
tools:context="com.jared.emsensorsstudy.MagneticSensor"> <ImageView
android:id="@+id/compass_img"
android:layout_width="250dp"
android:layout_height="250dp"
android:layout_centerInParent="true"
android:src="@drawable/compass" /> </RelativeLayout>

接着就是修改MagneticSensor的代码了:

package com.jared.emsensorsstudy;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView; public class MagneticSensor extends AppCompatActivity { private SensorManager sensorManager;
private ImageView compassImage; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_magnetic_sensor); compassImage = (ImageView)findViewById(R.id.compass_img); initWithCompass();
} @Override
protected void onDestroy() {
super.onDestroy();
sensorManager.unregisterListener(listener);
} private void initWithCompass() {
sensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
Sensor magneticSensor = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
Sensor acclerSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorManager.registerListener(listener, magneticSensor, SensorManager.SENSOR_DELAY_GAME);
sensorManager.registerListener(listener, acclerSensor, SensorManager.SENSOR_DELAY_GAME); } private SensorEventListener listener = new SensorEventListener() { float[] acclerValues = new float[3];
float[] magneticValues = new float[3];
private float lastRotateDegree; @Override
public void onSensorChanged(SensorEvent sensorEvent) {
switch (sensorEvent.sensor.getType()) {
case Sensor.TYPE_ACCELEROMETER:
acclerValues = sensorEvent.values.clone();
break;
case Sensor.TYPE_MAGNETIC_FIELD:
magneticValues = sensorEvent.values.clone();
break;
default:
break;
}
float[] values = new float[3];
float[] R = new float[9];
//调用getRotaionMatrix获得变换矩阵R[]
SensorManager.getRotationMatrix(R, null, acclerValues, magneticValues);
SensorManager.getOrientation(R, values);
//经过SensorManager.getOrientation(R, values);得到的values值为弧度
//转换为角度 float rotateDegree = -(float)Math.toDegrees(values[0]);
if(Math.abs(rotateDegree - lastRotateDegree) > 2) {
RotateAnimation animation = new RotateAnimation(
lastRotateDegree, rotateDegree, Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF, 0.5f);
animation.setFillAfter(true);
compassImage.startAnimation(animation);
lastRotateDegree = rotateDegree;
}
} @Override
public void onAccuracyChanged(Sensor sensor, int i) { }
};
}

这里通过加速度和磁传感器来实现一个方向,因为方向传感器官方已经不提倡使用了。运行效果如下:

传感器就先学习这些了。

附:参考《第一行代码》

Android开发学习之路--传感器之初体验的更多相关文章

  1. Android开发学习之路--Activity之初体验

    环境也搭建好了,android系统也基本了解了,那么接下来就可以开始学习android开发了,相信这么学下去肯定可以把android开发学习好的,再加上时而再温故下linux下的知识,看看androi ...

  2. Android开发学习之路--React-Native之初体验

      近段时间业余在学node.js,租了个阿里云准备搭建后端,想用node.js,偶尔得知react-native可以在不同平台跑,js在iOS和android上都可以运行ok,今天就简单学习下rea ...

  3. Android开发学习之路--Service之初体验

    android最后一个组件便是service了,终于学习到最后一个组件了,从年前的开发环境的搭建,到现在学到最后一个组件花了三周的时间,期间记录的点点滴滴,照着书本学习编写的代码都受益匪浅,这里要感谢 ...

  4. Android开发学习之路--RxAndroid之初体验

    学了一段时间android,看了部分的项目代码,然后想想老是学基础也够枯燥乏味的,那么就来学习学习新东西吧,相信很多学java的都听说过RxJava,那么android下也有RxAndroid. Rx ...

  5. Android开发学习之路--Camera之初体验

    顾名思义Camera就是拍照和录像的功能,像微信里面,我们想拍照传一下照片,就可以通过camera来拍照,然后存储照片,发送给好友.那么微信的app里面是不会直接通过camera api来实现的,因为 ...

  6. Android开发学习之路--UI之初体验

    之前都是学习Activity,对于布局都没有做过学习,这里就简单学习下吧.下面看下Android Studio下有哪些控件: 这里分为Widgets,Text Fields,Containers,Da ...

  7. Android开发学习之路--Notification之初体验

    一般当我们收到短信啊,微信啊,或者有些app的提醒,我们都会在通知栏收到一天简单的消息,然后点击消息进入到app里面,其实android中有专门的Notification的类可以完成这个工作,这里就实 ...

  8. Android开发学习之路--Android Studio cmake编译ffmpeg

      最新的android studio2.2引入了cmake可以很好地实现ndk的编写.这里使用最新的方式,对于以前的android下的ndk编译什么的可以参考之前的文章:Android开发学习之路– ...

  9. Android开发学习之路--网络编程之xml、json

    一般网络数据通过http来get,post,那么其中的数据不可能杂乱无章,比如我要post一段数据,肯定是要有一定的格式,协议的.常用的就是xml和json了.在此先要搭建个简单的服务器吧,首先呢下载 ...

随机推荐

  1. [2017/5/28]FJ四校联考

    来自FallDream的博客,未经允许,请勿转载,谢谢. 话说这一段时间算是过去了,好久好久之后终于又有联考了  没想到这次到我们学校出题,昨天才想起来,临时花一天赶了一套,我出了一个sbFFT,质量 ...

  2. Java并发编程:JMM(Java内存模型)和volatile

    1. 并发编程的3个概念 并发编程时,要想并发程序正确地执行,必须要保证原子性.可见性和有序性.只要有一个没有被保证,就有可能会导致程序运行不正确. 1.1. 原子性 原子性:即一个或多个操作要么全部 ...

  3. 视频人脸检测——OpenCV版(三)

    视频人脸检测是图片人脸检测的高级版本,图片检测详情点击查看我的上一篇<图片人脸检测——OpenCV版(二)> 实现思路: 调用电脑的摄像头,把摄像的信息逐帧分解成图片,基于图片检测标识出人 ...

  4. map内置函数、lambda表达式、快捷生成想要的列表、filter内置函数

      map函数                             语法 map(function, iterable, ...) 参数 function -- 函数,有两个参数 iterable ...

  5. vue拦截器实现统一token,并兼容IE9验证

    项目中使用vue搭建前端页面,并通过axios请求后台api接口,完成数据交互.如果验证口令token写在在每次的接口中,也是个不小的体力活,而且也不灵活.这里分享使用vue自带拦截器,给每次请求的头 ...

  6. 天梯赛-L1-018. 大笨钟

    L1-018. 大笨钟 时间限制 400 ms 内存限制 65536 kB 代码长度限制 8000 B 判题程序 Standard 作者 陈越 微博上有个自称"大笨钟V"的家伙,每 ...

  7. LintCode题解之斐波纳契数列

    直接使用递归的方法会导致TLE,加个缓存就好了: public class Solution { private Integer[] buff = new Integer[1000]; /* * @p ...

  8. Docker的名字空间

    名字空间是 Linux 内核一个强大的特性.每个容器都有自己单独的名字空间,运行在其中的应用都像是在独立的操作系统中运行一样.名字空间保证了容器之间彼此互不影响. pid 名字空间 不同用户的进程就是 ...

  9. Gradle 1.12用户指南翻译——第四十八章. Wrapper 插件

    本文由CSDN博客貌似掉线翻译,其他章节的翻译请参见: http://blog.csdn.net/column/details/gradle-translation.html 翻译项目请关注Githu ...

  10. 自定义下拉刷新上拉加载View

    MainActivity.java package com.heima52.pullrefresh; import java.util.ArrayList; import com.heima52.pu ...