Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/188.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 方向传感器_Android_Android Sensors - Fatal编程技术网

Android 方向传感器

Android 方向传感器,android,android-sensors,Android,Android Sensors,在我的应用程序中,我想显示设备的方向,如北、南、东、西。为此,我使用加速度计和磁传感器,并尝试以下代码 public class MainActivity extends Activity implements SensorEventListener { public static float swRoll; public static float swPitch; public static float swAzimuth; public static SensorManager mS

在我的应用程序中,我想显示设备的方向,如北、南、东、西。为此,我使用加速度计和磁传感器,并尝试以下代码

public class MainActivity extends Activity implements SensorEventListener 
{

public static float swRoll;
public static float swPitch;
public static float swAzimuth;


public static SensorManager mSensorManager;
public static Sensor accelerometer;
public static Sensor magnetometer;

public static float[] mAccelerometer = null;
public static float[] mGeomagnetic = null;


public void onAccuracyChanged(Sensor sensor, int accuracy) {
}

@Override
public void onSensorChanged(SensorEvent event) 
{
    // onSensorChanged gets called for each sensor so we have to remember the values
    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) 
    {
        mAccelerometer = event.values;
    }

    if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) 
    {
        mGeomagnetic = event.values;
    }

    if (mAccelerometer != null && mGeomagnetic != null) 
    {
        float R[] = new float[9];
        float I[] = new float[9];
        boolean success = SensorManager.getRotationMatrix(R, I, mAccelerometer, mGeomagnetic);

        if (success) 
        {
            float orientation[] = new float[3];
            SensorManager.getOrientation(R, orientation);
            // at this point, orientation contains the azimuth(direction), pitch and roll values.
            double azimuth = 180 * orientation[0] / Math.PI;
            //double pitch = 180 * orientation[1] / Math.PI;
            //double roll = 180 * orientation[2] / Math.PI;

            Toast.makeText(getApplicationContext(), "azimuth: "+azimuth, Toast.LENGTH_SHORT).show();
            //Toast.makeText(getApplicationContext(), "pitch: "+pitch, Toast.LENGTH_SHORT).show();
            //Toast.makeText(getApplicationContext(), "roll: "+roll, Toast.LENGTH_SHORT).show();
        }
    }
}



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
    accelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    magnetometer = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
}

@Override
protected void onResume() {
    super.onResume();

    mSensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_GAME);
    mSensorManager.registerListener(this, magnetometer, SensorManager.SENSOR_DELAY_GAME);
}

@Override
protected void onPause() {
    super.onPause();
    mSensorManager.unregisterListener(this, accelerometer);
    mSensorManager.unregisterListener(this, magnetometer);
}
}
我读了一些文章,了解到方位值是用来获取方向的。但它没有显示正确的值,即它在任何方向上始终显示103到140之间的值。我使用三星galaxy s进行测试。我哪里出错了。
任何帮助都将不胜感激……谢谢你编辑:我将继续回答这个问题,因为这里没有其他答案,但我再次查看这段代码时的直觉是,它可能工作不好。使用风险自负,如果有人给出合理的答案,我会删除这个

这是我自己写的罗盘传感器。它在某种程度上起作用。事实上,它需要更好的过滤——来自传感器的结果非常嘈杂,我在它上面构建了一个过滤器来减缓更新,它改进了一些东西,但是如果要在生产中使用它,它需要一个更好的过滤器

package com.gabesechan.android.reusable.sensor;

import java.lang.ref.WeakReference;
import java.util.HashSet;


import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Handler;
import android.os.Message;

public class CompassSensor {

SensorManager sm;
int lastDirection = -1;
int lastPitch;
int lastRoll;
boolean firstReading = true;
HashSet<CompassListener> listeners = new HashSet<CompassListener>();

static CompassSensor mInstance;

public static CompassSensor getInstance(Context ctx){
    if(mInstance == null){
        mInstance = new CompassSensor(ctx);
    }
    return mInstance;
}

private CompassSensor(Context ctx){
    sm = (SensorManager) ctx.getSystemService(Context.SENSOR_SERVICE);
    onResume();
}

public void onResume(){
    sm.registerListener(sensorListener, sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
    sm.registerListener(sensorListener, sm.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD), SensorManager.SENSOR_DELAY_UI);
    firstReading = true;
    //Restart the timer only if we have listeners
    if(listeners.size()>0){
        handler.sendMessageDelayed(Message.obtain(handler, 1),1000);
    }
}

public void onPause(){
    sm.unregisterListener(sensorListener);
    handler.removeMessages(1);
}

private final SensorEventListener sensorListener = new SensorEventListener(){
    float accelerometerValues[] = null;
    float geomagneticMatrix[] = null;
    public void onSensorChanged(SensorEvent event) {
        if (event.accuracy == SensorManager.SENSOR_STATUS_UNRELIABLE)
            return;

        switch (event.sensor.getType()) {
        case Sensor.TYPE_ACCELEROMETER:
            accelerometerValues = event.values.clone();

            break;
        case Sensor.TYPE_MAGNETIC_FIELD:
            geomagneticMatrix = event.values.clone();
            break;
        }   

        if (geomagneticMatrix != null && accelerometerValues != null && event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {

            float[] R = new float[16];
            float[] I = new float[16];
            float[] outR = new float[16];

            //Get the rotation matrix, then remap it from camera surface to world coordinates
            SensorManager.getRotationMatrix(R, I, accelerometerValues, geomagneticMatrix);
            SensorManager.remapCoordinateSystem(R, SensorManager.AXIS_X, SensorManager.AXIS_Z, outR);
            float values[] = new float[4];
            SensorManager.getOrientation(outR,values);

            int direction = normalizeDegrees(filterChange((int)Math.toDegrees(values[0])));
            int pitch = normalizeDegrees(Math.toDegrees(values[1]));
            int roll = normalizeDegrees(Math.toDegrees(values[2]));
            if((int)direction != (int)lastDirection){
                lastDirection = (int)direction;
                lastPitch = (int)pitch;
                lastRoll = (int)roll;
            }
        }
    }

    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }
};


//Normalize a degree from 0 to 360 instead of -180 to 180
private int normalizeDegrees(double rads){
    return (int)((rads+360)%360);
}

//We want to ignore large bumps in individual readings.  So we're going to cap the number of degrees we can change per report
private static final int MAX_CHANGE = 3;
private int filterChange(int newDir){
    newDir = normalizeDegrees(newDir);
    //On the first reading, assume it's right.  Otherwise NW readings take forever to ramp up
    if(firstReading){
        firstReading = false;
        return newDir;
    }       

    //Figure out how many degrees to move
    int delta = newDir - lastDirection;
    int normalizedDelta = normalizeDegrees(delta);
    int change = Math.min(Math.abs(delta),MAX_CHANGE);

    //We always want to move in the direction of lower distance.  So if newDir is lower and delta is less than half a circle, lower lastDir
    // Same if newDir is higher but the delta is more than half a circle (you'd be faster in the other direction going lower).
    if( normalizedDelta > 180 ){
        change = -change;
    }

    return lastDirection+change;
}

public void addListener(CompassListener listener){
    if(listeners.size() == 0){
        //Start the timer on first listener
        handler.sendMessageDelayed(Message.obtain(handler, 1),1000);
    }
    listeners.add(listener);
}

public void removeListener(CompassListener listener){
    listeners.remove(listener);
    if(listeners.size() == 0){
        handler.removeMessages(1);
    }

}

public int getLastDirection(){
    return lastDirection;
}
public int getLastPitch(){
    return lastPitch;
}
public int getLastRoll(){
    return lastPitch;
}

private void callListeners(){
    for(CompassListener listener: listeners){
        listener.onDirectionChanged(lastDirection, lastPitch, lastRoll);
    }             

}

//This handler is run every 1s, and updates the listeners
//Static class because otherwise we leak, Eclipse told me so
static class IncomingHandler extends Handler {
    private final WeakReference<CompassSensor> compassSensor; 

    IncomingHandler(CompassSensor sensor) {
        compassSensor = new WeakReference<CompassSensor>(sensor);
    }
    @Override
    public void handleMessage(Message msg)
    {
        CompassSensor sensor = compassSensor.get();
         if (sensor != null) {
              sensor.callListeners();
         }
        sendMessageDelayed(Message.obtain(this, 1), 1000);
    }
}

IncomingHandler handler = new IncomingHandler(this);

public interface CompassListener {
    void onDirectionChanged(int direction, int pitch, int roll);
}

}
package com.gabeschen.android.reusables.sensor;
导入java.lang.ref.WeakReference;
导入java.util.HashSet;
导入android.content.Context;
导入android.hardware.Sensor;
导入android.hardware.SensorEvent;
导入android.hardware.SensorEventListener;
导入android.hardware.SensorManager;
导入android.os.Handler;
导入android.os.Message;
公共类罗盘传感器{
传感器管理器sm;
int lastDirection=-1;
最后音高;
最后一卷;
布尔值firstReading=true;
HashSet侦听器=新HashSet();
静态罗盘传感器;
公共静态CompassSensor getInstance(上下文ctx){
if(minInstance==null){
MinInstance=新的CompassSensor(ctx);
}
回报率;
}
专用CompassSensor(上下文ctx){
sm=(SensorManager)ctx.getSystemService(Context.SENSOR\u服务);
onResume();
}
恢复时公开作废(){
sm.registerListener(sensorListener,sm.getDefaultSensor(Sensor.TYPE\u Accelerator),SensorManager.Sensor\u DELAY\u NORMAL);
sm.registerListener(sensorListener、sm.getDefaultSensor(Sensor.TYPE\u MAGNETIC\u FIELD)、SensorManager.Sensor\u DELAY\u UI);
首次阅读=正确;
//只有在有侦听器时才重新启动计时器
if(listeners.size()>0){
handler.sendMessageDelayed(Message.get(handler,1),1000);
}
}
公共无效暂停(){
sm.未注册侦听器(sensorListener);
handler.removeMessages(1);
}
private final SensorEventListener sensorListener=新建SensorEventListener(){
浮动加速计值[]=null;
浮动地磁矩阵[]=null;
传感器更改时的公共无效(传感器事件){
if(event.accurity==SensorManager.SENSOR\u状态\u不可靠)
返回;
开关(event.sensor.getType()){
外壳传感器.U型加速计:
accelerometerValues=event.values.clone();
打破
外壳传感器。类型\u磁场:
地磁矩阵=event.values.clone();
打破
}   
if(地磁矩阵!=null&&accelerometerValues!=null&&event.sensor.getType()==sensor.TYPE\U磁场){
浮动[]R=新浮动[16];
浮动[]I=新浮动[16];
浮动[]输出=新浮动[16];
//获取旋转矩阵,然后将其从摄影机曲面重新映射到世界坐标
SensorManager.getRotationMatrix(R、I、加速度计值、地磁矩阵);
SensorManager.remapCoordinationSystem(R,SensorManager.AXIS_X,SensorManager.AXIS_Z,outR);
浮动值[]=新浮动[4];
SensorManager.getOrientation(输出、值);
int direction=normalizedgrees(filterChange((int)Math.toDegrees(值[0]));
int pitch=标准化程度(数学到度(值[1]);
int roll=normalizedgrees(数学toDegrees(值[2]);
如果((int)方向!=(int)最后方向){
lastDirection=(int)方向;
lastPitch=(int)音高;
lastRoll=(int)roll;
}
}
}
精度更改时的公共无效(传感器,int精度){
}
};
//将0到360度的角度规格化,而不是-180到180度
专用整数规格化灰度(双拉德){
返回值(整数)((rads+360)%360);
}
//我们希望忽略单个读数中的大起伏。因此,我们将限制每个报告可以更改的度数
私有静态最终整数最大变化=3;
私有int filterChange(int newDir){
newDir=标准化的灰度(newDir);
//在第一次读数时,假设它是对的,否则NW读数需要很长时间才能上升
如果(一读){
首次阅读=错误;
返回newDir;
}       
//计算出要移动多少度
int delta=newDir-lastDirection;
int normalizedDelta=normalizedgrees(delta);
int change=Math.min(Math.abs(delta),MAX_change);
//我们总是想朝着较低距离的方向移动,所以如果newDir较低,delta小于半个圆,那么就降低lastDir
//如果newDir更高,但delta大于半个圆,则相同(在另一个方向降低时,速度会更快)。
如果(归一化delta>180){
改变=-改变;
}
返回方向+改变;
}
public void addListener(CompassListener侦听器){
if(listeners.size()==0){
//在第一个侦听器上启动计时器
handler.sendMessageDelayed(Message.get(handler,1),1000);
}
添加(侦听器);
}
公共无效删除侦听器(CompassListener侦听器){
删除(侦听器);
if(listeners.size()==0){
handler.removeMessages(1);
}
}
public int getLastDirection(){
返回方向;
}
public int getLastPitch(){
回音音高;
}
public int getLastRoll(){
回音音高;
}
私有void callListeners(){
for(CompassListener:侦听器){
onDirectionChanged(lastDirection、lastPitch、lastRoll);
}             
}
//这个处理程序