2010-08-18 42 views

回答

5
+0

是啊,我发现的文件中。还有两个问题:你将R和值初始化为什么?另外,是否有获取通知的方法,或者是否已弃用整个工作模型? – 2010-08-19 03:44:38

+1

好的,在源代码中找到了一个很好的例子。我不会在这里复制它,但如果你浏览Android的git仓库,看看开发/样本/指南针/ src/com/example/android/compass/CompassActivity.java的末尾 – 2010-08-19 15:54:13

+1

通知/事件是一个糟糕的方式做传感器,这就是为什么它是depacated afaik。每一个细微的方面变化都会触发大量的事件,实质上是用数据扼杀UI线程。 – CodeFusionMobile 2010-08-20 14:08:11

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); 
} 
} 

以下是相关的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> 
+3

这是否仍然使用OP提到的弃用的方向传感器? – Tim 2013-02-25 16:14:40

+0

是的 - 不推荐使用。 – Vaiden 2013-05-19 08:44:10