如何获得Android罗盘阅读?

Edw*_*alk 8 android

现在不推荐使用SENSOR_ORIENTATION,获取罗盘标题的最佳做法是什么?旧的方式很简单.

Mar*_*ood 8

以下是获取罗盘标题并在TextView中显示它的基本示例.它通过实现SensorEventListener接口来实现.您可以通过更改以下代码行中的常量来更改事件传递到系统的速率(即"mSensorManager.registerListener(this,mCompass,SensorManager.SENSOR_DELAY_NORMAL);")(请参阅OnResume()事件); 但是,该设置仅是对系统的建议.此示例还使用onReuse()和onPause()方法通过在不使用时注册和取消注册监听器来延长电池寿命.希望这可以帮助.

package edu.uw.android.thorm.wayfinder;

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.widget.TextView;

public class CSensorActivity extends Activity implements SensorEventListener {
private SensorManager mSensorManager;
private Sensor mCompass;
private TextView mTextView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layoutsensor);
    mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
    mCompass = mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
    mTextView = (TextView) findViewById(R.id.tvSensor);
}

// The following method is required by the SensorEventListener interface;
public void onAccuracyChanged(Sensor sensor, int accuracy) {    
}

// The following method is required by the SensorEventListener interface;
// Hook this event to process updates;
public void onSensorChanged(SensorEvent event) {
    float azimuth = Math.round(event.values[0]);
    // The other values provided are: 
    //  float pitch = event.values[1];
    //  float roll = event.values[2];
    mTextView.setText("Azimuth: " + Float.toString(azimuth));
}

@Override
protected void onPause() {
    // Unregister the listener on the onPause() event to preserve battery life;
    super.onPause();
    mSensorManager.unregisterListener(this);
}

@Override
protected void onResume() {
    super.onResume();
    mSensorManager.registerListener(this, mCompass, SensorManager.SENSOR_DELAY_NORMAL);
}
}
Run Code Online (Sandbox Code Playgroud)

以下是关联的XML文件:

<?xml version="1.0" encoding="utf-8"?>
<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/tvSensor"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

  • 这是不是仍然使用OP提到的弃用的方向传感器? (4认同)

Cod*_*ile 5

SensorManager.getOrientation(float [] R,float [] values)是自API级别3以来使用的标准API调用.

  • 好的,在源代码库中找到了一个很好的例子。这里我就不复制了,不过如果你浏览一下Android的git仓库,看最后开发/samples/Compass/src/com/example/android/compass/CompassActivity.java (2认同)