android传感器详解

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >


    <TextView
    android:id="@+id/tv3"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="TextView" />


    <TextView
    android:id="@+id/tv2"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="TextView" />


<TextView
android:id="@+id/tv1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="TextView" />


</LinearLayout>



MainActivity 

package com.example.sensordemo;


import android.app.Activity;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;


public class MainActivity extends Activity {
SensorManager mySensorManager;
TextView tvX, tvY, tvZ;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvX = (TextView) findViewById(R.id.tv1);
tvY = (TextView) findViewById(R.id.tv2);
tvZ = (TextView) findViewById(R.id.tv3);
mySensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);


}


@Override
protected void onResume() {
mySensorManager.registerListener(mySensorListener,
mySensorManager.getDefaultSensor(SensorManager.SENSOR_ACCELEROMETER),//传感器类型
SensorManager.SENSOR_DELAY_UI);//传感器事件传递的频度


super.onResume();
}


@Override
protected void onPause() {//取消注册监听器
mySensorManager.unregisterListener(mySensorListener);
// TODO Auto-generated method stub
super.onPause();
}


private SensorEventListener mySensorListener = new SensorEventListener() {


@Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
if (event.sensor.getType() == SensorManager.SENSOR_ACCELEROMETER) {// 判定是否为加速度传感器变化产生
float[]values=event.values;
tvX.setText("x轴方向上的加速度:" + values[0]);
tvY.setText("y轴方向上加速度:" + values[1]);
tvZ.setText("z轴方向上加速度:" + values[2]);


}
}
public void onAccuracyChanged(android.hardware.Sensor sensor, int accuracy) {};
};


}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值