Android手机屏幕位置查找

时间:2013-03-14 10:25:10

标签: android android-screen

我在新的应用程序中面临挑战,我想找到面向天花板或地板的Android手机屏幕。我能用安卓传感器制作这个。如果有人试过这个请分享你的宝贵意见和教程如果可用。

2 个答案:

答案 0 :(得分:1)

您可以使用SensorEventListener来实现此目的。看看下面的代码,以便更好地理解。您还可以在开发人员文档中查看this以获取有关传感器的更多信息。

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;

public class SensorClass implements SensorEventListener {
    private float   mInR[];
    private float   mI[];
    private float   mGravity[];
    private float   mGeomag[];
    private float   mOrientVals[];

    final float rad2deg = 180/((float) Math.PI);

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
        // Do something here when accuracy changed
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        float azimuth = 0f;
        float pitch = 0f;
        float roll = 0f;

        // If the sensor data is unreliable return
        if (event.accuracy == SensorManager.SENSOR_STATUS_UNRELIABLE)
            return;

        // Gets the value of the sensor that has been changed
        switch (event.sensor.getType()){  
        case Sensor.TYPE_ACCELEROMETER:
            mGravity = event.values.clone();
            break;
        case Sensor.TYPE_MAGNETIC_FIELD:
            mGeomag = event.values.clone();
            break;
        }

         if (mGravity != null && mGeomag != null){
            // checks that the rotation matrix is found
            if (SensorManager.getRotationMatrix(mInR, mI, mGravity, mGeomag)){

                // magnetic north and the horizon respectively
                SensorManager.getOrientation(mInR, mOrientVals);

                azimuth = mOrientVals[0]*rad2deg;
                pitch = mOrientVals[1]*rad2deg;
                roll = mOrientVals[2]*rad2deg;
            }
        }
    }
}

答案 1 :(得分:1)

oncreate

    sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
    List<Sensor> sensorList = sensorManager
            .getSensorList(Sensor.TYPE_ACCELEROMETER);
    if (sensorList.size() > 0) {
        accelerometerPresent = true;
        accelerometerSensor = sensorList.get(0);
    }

注册SensorEventListener

        sensorManager.registerListener(accelerometerListener,
                accelerometerSensor, SensorManager.SENSOR_DELAY_NORMAL);

SensorEventListener实施

private SensorEventListener accelerometerListener = new SensorEventListener() {

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

    public void onSensorChanged(SensorEvent event) {
        float z_value = event.values[2];
        if (z_value == 10) {
            // up facing
        } else if(z_value == -10)
            // down facing
        }           
    }
};

在我的两个设备中,当它向上和水平时显示z_values = 10,而在相反的情况下它显示 - 10.检查你的情况。