1、加速传感器方向
手机加速传感器检测:
可以想想中间位置有一个空气球,
1、手机上部抬起时,气球上移,Y变大。
2、手机右部抬起时,气球右移,X变大。
3、手机正面平方时,气球升起,Z变大。
反向一样,取值范围-10~10.
2、功能显示
3、xml文件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.albert.myapplication.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="200dp"
android:layout_gravity="center"
android:orientation="horizontal">
<TextView
android:id="@+id/view_id"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:text="sensor"
android:textSize="40dp"/>
</LinearLayout>
</RelativeLayout>
4、功能代码
package com.example.albert.myapplication;
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 MainActivity extends AppCompatActivity implements SensorEventListener{
SensorManager sm; //传感器管理器
Sensor sr; //加速传感器对象
TextView txv; //界面中的文本组件
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//从系统服务获取传感器管理器
sm = (SensorManager) getSystemService(SENSOR_SERVICE);
sr = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);//获取加速传感器
txv = (TextView) findViewById(R.id.view_id);//获取textView组件
}
public void onSensorChanged(SensorEvent event) { //当加速的值改变的时候执行此函数
txv.setText(String.format("X轴: %1.2f\n\nY轴:%1.2f\n\nZ轴:%1.2f",event.values[0],
event.values[1], event.values[2]));
}
public void onAccuracyChanged(Sensor arg0, int arg1) {
//精度改变时不需要处理
}
protected void onResume(){ //当Activity 界面显示出来的时候
super.onResume();
//向加速传感器(sr)注册监听对象this
sm.registerListener(this,sr,SensorManager.SENSOR_DELAY_NORMAL);
}
protected void onPause() { //当activity 界面被取消焦点的时候
super.onPause();
//取消监听对象thisd的注册
sm.unregisterListener(this);
}
}
文献参考:
android app开发入门 施威铭 编著
本人郑重声明,本博客所著文章、图片版权归权利人持有,本博只做学习交流分享所用,不做任何商业用途。访问者可將本博提供的內容或服务用于个人学习、研究或欣赏,不得用于商业使用。同時,访问者应遵守著作权法及其他相关法律的规定,不得侵犯相关权利人的合法权利;如果用于商业用途,须征得相关权利人的书面授权。若以上文章、图片的原作者不愿意在此展示內容,请及时通知在下,將及时予以刪除。