Android实现传感器功能
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.util.Log;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements SensorEventListener {
private TextView tvAccelerometer;
private SensorManager sensorManager;
private float[] gravity = new float[3];
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvAccelerometer = (TextView) findViewById(R.id.tvAccelerometer);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
}
@Override
public void onSensorChanged(SensorEvent event) {
switch (event.sensor.getType()){
case Sensor.TYPE_ACCELEROMETER:
final float alpha = (float)0.8;
gravity[0] = alpha*gravity[0]+(1-alpha)*event.values[0];
gravity[1] = alpha*gravity[1]+(1-alpha)*event.values[1];
gravity[2] = alpha*gravity[2]+(1-alpha)*event.values[2];
String accelerometer = "加速度
"+"X:"+(event.values[0]-gravity[0])+"
"+"Y:"+
(event.values[1]-gravity[1])+"
"+"Z:"+(event.values[2]-gravity[2]);
Log.d("Z",String.valueOf((event.values[2]-gravity[2])));
tvAccelerometer.setText(accelerometer);
break;
case Sensor.TYPE_GRAVITY:
gravity[0] = event.values[0];
gravity[1] = event.values[1];
gravity[2] = event.values[2];
break;
case Sensor.TYPE_PROXIMITY:
setTitle(String.valueOf(event.values[0]));
default:
break;
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
protected void onResume(){
super.onResume();
sensorManager.registerListener(this,sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_UI);
sensorManager.registerListener(this,sensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY),
SensorManager.SENSOR_DELAY_FASTEST);
sensorManager.registerListener(this,sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY),
SensorManager.SENSOR_DELAY_NORMAL);
}
protected void onPause(){
super.onPause();
sensorManager.unregisterListener(this);
}
}
- .NET Core系列之MemoryCache 初识
- 007手机一键Root(安机网一键Root) v3.0 官方最新版 一键ROOT您的Android手机
- 12306密码被盗了怎么办?12306密码外泄解决方法
- 12个字的qq网名
- 150M迷你型无线路由器怎么设置?
- 192.168.1.1打不开怎么办?路由器192.168.1.1打不开的原因以及解决办法
- 2011年电子报合订本 电子报 编辑部 中文 PDF版 [84M]
- 2015年1月15日小米新旗舰发布会现场图文直播
- 2016.3.1vivo Xplay5新品发布会现场视频直播 优酷直播
- 2016华为P9发布会视频直播地址 4月15日华为P9国行发布会直播