android方向传感器(SENSOR_TYPE_ORIENTATION)
发表时间:2020-10-19
发布人:葵宇科技
浏览次数:169
SENSOR_TYPE_ORIENTATION这个android 2.2之后就不推荐用了!!!
手机状况
数值状况
数值范围
手机程度放置,顶部指向正北方
x、y、z偏向值为0
0
程度逆时针扭转
x赓续削减
360 ~ 0
程度顺时针扭转
x赓续增大年夜
0 ~ 360
当手机左侧抬起时
z赓续削减
0 ~ -180
当手机右侧抬起时
z赓续增大年夜
0 ~ 180
当手机顶部抬起时
y赓续削减
0 ~ -180
当手机底部抬起时
y赓续增大年夜
0 ~ 180
经由实验,我们发明当手机顶部指向正北方时偏向值为0,顶部指向正东方时偏向值为90,顶部指向正南边时偏向值为180,顶部指向正西方时偏向值为270。根据这些数据我们就可以根据偏向值典范围盘端当前我们的方位,可以肯定指南针的读数。
示例代码:
package com.example.sensors; import android.app.Activity; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.widget.TextView; public class MainActivity extends Activity implements SensorEventListener{ private TextView changeText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); SensorManager sensorManager= (SensorManager) getSystemService(SENSOR_SERVICE) ; Sensor gyposcope = sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION); sensorManager.registerListener(this, gyposcope, SensorManager.SENSOR_DELAY_GAME); changeText = (TextView) findViewById(R.id.changeText); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public void onSensorChanged(SensorEvent event) { Log.i("test", event.values.toString()); changeText.setText(event.values[0]+" "+event.values[1]+" "+event.values[2]); } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } }