package com.example.day9sensor;
import java.util.List;
import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
TextView tv,tv1;
boolean flag = true;
private SensorManager manager;
MyAcc acc;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tv);
tv1 = (TextView) findViewById(R.id.tv1);
acc = new MyAcc();
manager = (SensorManager) getSystemService(SENSOR_SERVICE);
//步骤2:使用传感器的管理器 获取当前设备中的所有传感器信息
List<Sensor> sensorList = manager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensorList) {
tv.append("\r\n" + sensor.getName());
}
//使用加速度传感器完成摇一摇功能
//1、获取到加速度传感器
Sensor sensorAcc = manager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
//2、使用加速度传感器 注册一个监听
//参数1:监听器
//参数2:使用的传感器对象
//参数3:传感器精度
// SENSOR_DELAY_NORMAL, 传感器的默认延时
// SENSOR_DELAY_UI, 传感器适用于 UI更新的延时
// SENSOR_DELAY_GAME, 传感器适用于 游戏的延时
// SENSOR_DELAY_FASTEST 传感器最快延时
manager.registerListener(acc, sensorAcc, SensorManager.SENSOR_DELAY_UI);
}
class MyAcc implements SensorEventListener {
//当传感器数据方法改变时调用该方法
@Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
tv1.setText(x + "\r\n" + y + "\r\n" + z + "\r\n");
if(Math.abs(x) > 17 || Math.abs(y) > 17 || Math.abs(z) > 17){
if(flag){
Toast.makeText(MainActivity.this, "摇一摇", 0).show();
}
flag = false;
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
SystemClock.sleep(10000);
flag = true;
}
}).start();
}
}
//当传感器精度方法改变时 调用该方法
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
}
@Override
protected void onPause() {
manager.unregisterListener(acc);
super.onPause();
}
}
sensor传感器-摇一摇
最新推荐文章于 2022-05-10 00:25:50 发布